1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw__Float16:
142   case tok::kw___float128:
143   case tok::kw_wchar_t:
144   case tok::kw_bool:
145   case tok::kw___underlying_type:
146   case tok::kw___auto_type:
147     return true;
148 
149   case tok::annot_typename:
150   case tok::kw_char16_t:
151   case tok::kw_char32_t:
152   case tok::kw_typeof:
153   case tok::annot_decltype:
154   case tok::kw_decltype:
155     return getLangOpts().CPlusPlus;
156 
157   case tok::kw_char8_t:
158     return getLangOpts().Char8;
159 
160   default:
161     break;
162   }
163 
164   return false;
165 }
166 
167 namespace {
168 enum class UnqualifiedTypeNameLookupResult {
169   NotFound,
170   FoundNonType,
171   FoundType
172 };
173 } // end anonymous namespace
174 
175 /// Tries to perform unqualified lookup of the type decls in bases for
176 /// dependent class.
177 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
178 /// type decl, \a FoundType if only type decls are found.
179 static UnqualifiedTypeNameLookupResult
180 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
181                                 SourceLocation NameLoc,
182                                 const CXXRecordDecl *RD) {
183   if (!RD->hasDefinition())
184     return UnqualifiedTypeNameLookupResult::NotFound;
185   // Look for type decls in base classes.
186   UnqualifiedTypeNameLookupResult FoundTypeDecl =
187       UnqualifiedTypeNameLookupResult::NotFound;
188   for (const auto &Base : RD->bases()) {
189     const CXXRecordDecl *BaseRD = nullptr;
190     if (auto *BaseTT = Base.getType()->getAs<TagType>())
191       BaseRD = BaseTT->getAsCXXRecordDecl();
192     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
193       // Look for type decls in dependent base classes that have known primary
194       // templates.
195       if (!TST || !TST->isDependentType())
196         continue;
197       auto *TD = TST->getTemplateName().getAsTemplateDecl();
198       if (!TD)
199         continue;
200       if (auto *BasePrimaryTemplate =
201           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
202         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
203           BaseRD = BasePrimaryTemplate;
204         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
205           if (const ClassTemplatePartialSpecializationDecl *PS =
206                   CTD->findPartialSpecialization(Base.getType()))
207             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
208               BaseRD = PS;
209         }
210       }
211     }
212     if (BaseRD) {
213       for (NamedDecl *ND : BaseRD->lookup(&II)) {
214         if (!isa<TypeDecl>(ND))
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217       }
218       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
219         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
220         case UnqualifiedTypeNameLookupResult::FoundNonType:
221           return UnqualifiedTypeNameLookupResult::FoundNonType;
222         case UnqualifiedTypeNameLookupResult::FoundType:
223           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224           break;
225         case UnqualifiedTypeNameLookupResult::NotFound:
226           break;
227         }
228       }
229     }
230   }
231 
232   return FoundTypeDecl;
233 }
234 
235 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
236                                                       const IdentifierInfo &II,
237                                                       SourceLocation NameLoc) {
238   // Lookup in the parent class template context, if any.
239   const CXXRecordDecl *RD = nullptr;
240   UnqualifiedTypeNameLookupResult FoundTypeDecl =
241       UnqualifiedTypeNameLookupResult::NotFound;
242   for (DeclContext *DC = S.CurContext;
243        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
244        DC = DC->getParent()) {
245     // Look for type decls in dependent base classes that have known primary
246     // templates.
247     RD = dyn_cast<CXXRecordDecl>(DC);
248     if (RD && RD->getDescribedClassTemplate())
249       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
250   }
251   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
252     return nullptr;
253 
254   // We found some types in dependent base classes.  Recover as if the user
255   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
256   // lookup during template instantiation.
257   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
258 
259   ASTContext &Context = S.Context;
260   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
261                                           cast<Type>(Context.getRecordType(RD)));
262   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
263 
264   CXXScopeSpec SS;
265   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
266 
267   TypeLocBuilder Builder;
268   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
269   DepTL.setNameLoc(NameLoc);
270   DepTL.setElaboratedKeywordLoc(SourceLocation());
271   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
272   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
273 }
274 
275 /// If the identifier refers to a type name within this scope,
276 /// return the declaration of that type.
277 ///
278 /// This routine performs ordinary name lookup of the identifier II
279 /// within the given scope, with optional C++ scope specifier SS, to
280 /// determine whether the name refers to a type. If so, returns an
281 /// opaque pointer (actually a QualType) corresponding to that
282 /// type. Otherwise, returns NULL.
283 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
284                              Scope *S, CXXScopeSpec *SS,
285                              bool isClassName, bool HasTrailingDot,
286                              ParsedType ObjectTypePtr,
287                              bool IsCtorOrDtorName,
288                              bool WantNontrivialTypeSourceInfo,
289                              bool IsClassTemplateDeductionContext,
290                              IdentifierInfo **CorrectedII) {
291   // FIXME: Consider allowing this outside C++1z mode as an extension.
292   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
293                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
294                               !isClassName && !HasTrailingDot;
295 
296   // Determine where we will perform name lookup.
297   DeclContext *LookupCtx = nullptr;
298   if (ObjectTypePtr) {
299     QualType ObjectType = ObjectTypePtr.get();
300     if (ObjectType->isRecordType())
301       LookupCtx = computeDeclContext(ObjectType);
302   } else if (SS && SS->isNotEmpty()) {
303     LookupCtx = computeDeclContext(*SS, false);
304 
305     if (!LookupCtx) {
306       if (isDependentScopeSpecifier(*SS)) {
307         // C++ [temp.res]p3:
308         //   A qualified-id that refers to a type and in which the
309         //   nested-name-specifier depends on a template-parameter (14.6.2)
310         //   shall be prefixed by the keyword typename to indicate that the
311         //   qualified-id denotes a type, forming an
312         //   elaborated-type-specifier (7.1.5.3).
313         //
314         // We therefore do not perform any name lookup if the result would
315         // refer to a member of an unknown specialization.
316         if (!isClassName && !IsCtorOrDtorName)
317           return nullptr;
318 
319         // We know from the grammar that this name refers to a type,
320         // so build a dependent node to describe the type.
321         if (WantNontrivialTypeSourceInfo)
322           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
323 
324         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
325         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
326                                        II, NameLoc);
327         return ParsedType::make(T);
328       }
329 
330       return nullptr;
331     }
332 
333     if (!LookupCtx->isDependentContext() &&
334         RequireCompleteDeclContext(*SS, LookupCtx))
335       return nullptr;
336   }
337 
338   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
339   // lookup for class-names.
340   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
341                                       LookupOrdinaryName;
342   LookupResult Result(*this, &II, NameLoc, Kind);
343   if (LookupCtx) {
344     // Perform "qualified" name lookup into the declaration context we
345     // computed, which is either the type of the base of a member access
346     // expression or the declaration context associated with a prior
347     // nested-name-specifier.
348     LookupQualifiedName(Result, LookupCtx);
349 
350     if (ObjectTypePtr && Result.empty()) {
351       // C++ [basic.lookup.classref]p3:
352       //   If the unqualified-id is ~type-name, the type-name is looked up
353       //   in the context of the entire postfix-expression. If the type T of
354       //   the object expression is of a class type C, the type-name is also
355       //   looked up in the scope of class C. At least one of the lookups shall
356       //   find a name that refers to (possibly cv-qualified) T.
357       LookupName(Result, S);
358     }
359   } else {
360     // Perform unqualified name lookup.
361     LookupName(Result, S);
362 
363     // For unqualified lookup in a class template in MSVC mode, look into
364     // dependent base classes where the primary class template is known.
365     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
366       if (ParsedType TypeInBase =
367               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
368         return TypeInBase;
369     }
370   }
371 
372   NamedDecl *IIDecl = nullptr;
373   switch (Result.getResultKind()) {
374   case LookupResult::NotFound:
375   case LookupResult::NotFoundInCurrentInstantiation:
376     if (CorrectedII) {
377       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
378                                AllowDeducedTemplate);
379       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
380                                               S, SS, CCC, CTK_ErrorRecovery);
381       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
382       TemplateTy Template;
383       bool MemberOfUnknownSpecialization;
384       UnqualifiedId TemplateName;
385       TemplateName.setIdentifier(NewII, NameLoc);
386       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
387       CXXScopeSpec NewSS, *NewSSPtr = SS;
388       if (SS && NNS) {
389         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
390         NewSSPtr = &NewSS;
391       }
392       if (Correction && (NNS || NewII != &II) &&
393           // Ignore a correction to a template type as the to-be-corrected
394           // identifier is not a template (typo correction for template names
395           // is handled elsewhere).
396           !(getLangOpts().CPlusPlus && NewSSPtr &&
397             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
398                            Template, MemberOfUnknownSpecialization))) {
399         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
400                                     isClassName, HasTrailingDot, ObjectTypePtr,
401                                     IsCtorOrDtorName,
402                                     WantNontrivialTypeSourceInfo,
403                                     IsClassTemplateDeductionContext);
404         if (Ty) {
405           diagnoseTypo(Correction,
406                        PDiag(diag::err_unknown_type_or_class_name_suggest)
407                          << Result.getLookupName() << isClassName);
408           if (SS && NNS)
409             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
410           *CorrectedII = NewII;
411           return Ty;
412         }
413       }
414     }
415     // If typo correction failed or was not performed, fall through
416     LLVM_FALLTHROUGH;
417   case LookupResult::FoundOverloaded:
418   case LookupResult::FoundUnresolvedValue:
419     Result.suppressDiagnostics();
420     return nullptr;
421 
422   case LookupResult::Ambiguous:
423     // Recover from type-hiding ambiguities by hiding the type.  We'll
424     // do the lookup again when looking for an object, and we can
425     // diagnose the error then.  If we don't do this, then the error
426     // about hiding the type will be immediately followed by an error
427     // that only makes sense if the identifier was treated like a type.
428     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
429       Result.suppressDiagnostics();
430       return nullptr;
431     }
432 
433     // Look to see if we have a type anywhere in the list of results.
434     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
435          Res != ResEnd; ++Res) {
436       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
437           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
438         if (!IIDecl ||
439             (*Res)->getLocation().getRawEncoding() <
440               IIDecl->getLocation().getRawEncoding())
441           IIDecl = *Res;
442       }
443     }
444 
445     if (!IIDecl) {
446       // None of the entities we found is a type, so there is no way
447       // to even assume that the result is a type. In this case, don't
448       // complain about the ambiguity. The parser will either try to
449       // perform this lookup again (e.g., as an object name), which
450       // will produce the ambiguity, or will complain that it expected
451       // a type name.
452       Result.suppressDiagnostics();
453       return nullptr;
454     }
455 
456     // We found a type within the ambiguous lookup; diagnose the
457     // ambiguity and then return that type. This might be the right
458     // answer, or it might not be, but it suppresses any attempt to
459     // perform the name lookup again.
460     break;
461 
462   case LookupResult::Found:
463     IIDecl = Result.getFoundDecl();
464     break;
465   }
466 
467   assert(IIDecl && "Didn't find decl");
468 
469   QualType T;
470   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
471     // C++ [class.qual]p2: A lookup that would find the injected-class-name
472     // instead names the constructors of the class, except when naming a class.
473     // This is ill-formed when we're not actually forming a ctor or dtor name.
474     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
475     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
476     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
477         FoundRD->isInjectedClassName() &&
478         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
479       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
480           << &II << /*Type*/1;
481 
482     DiagnoseUseOfDecl(IIDecl, NameLoc);
483 
484     T = Context.getTypeDeclType(TD);
485     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
486   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
487     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
488     if (!HasTrailingDot)
489       T = Context.getObjCInterfaceType(IDecl);
490   } else if (AllowDeducedTemplate) {
491     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
492       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
493                                                        QualType(), false);
494   }
495 
496   if (T.isNull()) {
497     // If it's not plausibly a type, suppress diagnostics.
498     Result.suppressDiagnostics();
499     return nullptr;
500   }
501 
502   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
503   // constructor or destructor name (in such a case, the scope specifier
504   // will be attached to the enclosing Expr or Decl node).
505   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
506       !isa<ObjCInterfaceDecl>(IIDecl)) {
507     if (WantNontrivialTypeSourceInfo) {
508       // Construct a type with type-source information.
509       TypeLocBuilder Builder;
510       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
511 
512       T = getElaboratedType(ETK_None, *SS, T);
513       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
514       ElabTL.setElaboratedKeywordLoc(SourceLocation());
515       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
516       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
517     } else {
518       T = getElaboratedType(ETK_None, *SS, T);
519     }
520   }
521 
522   return ParsedType::make(T);
523 }
524 
525 // Builds a fake NNS for the given decl context.
526 static NestedNameSpecifier *
527 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
528   for (;; DC = DC->getLookupParent()) {
529     DC = DC->getPrimaryContext();
530     auto *ND = dyn_cast<NamespaceDecl>(DC);
531     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
532       return NestedNameSpecifier::Create(Context, nullptr, ND);
533     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
534       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
535                                          RD->getTypeForDecl());
536     else if (isa<TranslationUnitDecl>(DC))
537       return NestedNameSpecifier::GlobalSpecifier(Context);
538   }
539   llvm_unreachable("something isn't in TU scope?");
540 }
541 
542 /// Find the parent class with dependent bases of the innermost enclosing method
543 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
544 /// up allowing unqualified dependent type names at class-level, which MSVC
545 /// correctly rejects.
546 static const CXXRecordDecl *
547 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
548   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
549     DC = DC->getPrimaryContext();
550     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
551       if (MD->getParent()->hasAnyDependentBases())
552         return MD->getParent();
553   }
554   return nullptr;
555 }
556 
557 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
558                                           SourceLocation NameLoc,
559                                           bool IsTemplateTypeArg) {
560   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
561 
562   NestedNameSpecifier *NNS = nullptr;
563   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
564     // If we weren't able to parse a default template argument, delay lookup
565     // until instantiation time by making a non-dependent DependentTypeName. We
566     // pretend we saw a NestedNameSpecifier referring to the current scope, and
567     // lookup is retried.
568     // FIXME: This hurts our diagnostic quality, since we get errors like "no
569     // type named 'Foo' in 'current_namespace'" when the user didn't write any
570     // name specifiers.
571     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
572     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
573   } else if (const CXXRecordDecl *RD =
574                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
575     // Build a DependentNameType that will perform lookup into RD at
576     // instantiation time.
577     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
578                                       RD->getTypeForDecl());
579 
580     // Diagnose that this identifier was undeclared, and retry the lookup during
581     // template instantiation.
582     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
583                                                                       << RD;
584   } else {
585     // This is not a situation that we should recover from.
586     return ParsedType();
587   }
588 
589   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
590 
591   // Build type location information.  We synthesized the qualifier, so we have
592   // to build a fake NestedNameSpecifierLoc.
593   NestedNameSpecifierLocBuilder NNSLocBuilder;
594   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
595   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
596 
597   TypeLocBuilder Builder;
598   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
599   DepTL.setNameLoc(NameLoc);
600   DepTL.setElaboratedKeywordLoc(SourceLocation());
601   DepTL.setQualifierLoc(QualifierLoc);
602   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
603 }
604 
605 /// isTagName() - This method is called *for error recovery purposes only*
606 /// to determine if the specified name is a valid tag name ("struct foo").  If
607 /// so, this returns the TST for the tag corresponding to it (TST_enum,
608 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
609 /// cases in C where the user forgot to specify the tag.
610 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
611   // Do a tag name lookup in this scope.
612   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
613   LookupName(R, S, false);
614   R.suppressDiagnostics();
615   if (R.getResultKind() == LookupResult::Found)
616     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
617       switch (TD->getTagKind()) {
618       case TTK_Struct: return DeclSpec::TST_struct;
619       case TTK_Interface: return DeclSpec::TST_interface;
620       case TTK_Union:  return DeclSpec::TST_union;
621       case TTK_Class:  return DeclSpec::TST_class;
622       case TTK_Enum:   return DeclSpec::TST_enum;
623       }
624     }
625 
626   return DeclSpec::TST_unspecified;
627 }
628 
629 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
630 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
631 /// then downgrade the missing typename error to a warning.
632 /// This is needed for MSVC compatibility; Example:
633 /// @code
634 /// template<class T> class A {
635 /// public:
636 ///   typedef int TYPE;
637 /// };
638 /// template<class T> class B : public A<T> {
639 /// public:
640 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
641 /// };
642 /// @endcode
643 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
644   if (CurContext->isRecord()) {
645     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
646       return true;
647 
648     const Type *Ty = SS->getScopeRep()->getAsType();
649 
650     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
651     for (const auto &Base : RD->bases())
652       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
653         return true;
654     return S->isFunctionPrototypeScope();
655   }
656   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
657 }
658 
659 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
660                                    SourceLocation IILoc,
661                                    Scope *S,
662                                    CXXScopeSpec *SS,
663                                    ParsedType &SuggestedType,
664                                    bool IsTemplateName) {
665   // Don't report typename errors for editor placeholders.
666   if (II->isEditorPlaceholder())
667     return;
668   // We don't have anything to suggest (yet).
669   SuggestedType = nullptr;
670 
671   // There may have been a typo in the name of the type. Look up typo
672   // results, in case we have something that we can suggest.
673   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
674                            /*AllowTemplates=*/IsTemplateName,
675                            /*AllowNonTemplates=*/!IsTemplateName);
676   if (TypoCorrection Corrected =
677           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
678                       CCC, CTK_ErrorRecovery)) {
679     // FIXME: Support error recovery for the template-name case.
680     bool CanRecover = !IsTemplateName;
681     if (Corrected.isKeyword()) {
682       // We corrected to a keyword.
683       diagnoseTypo(Corrected,
684                    PDiag(IsTemplateName ? diag::err_no_template_suggest
685                                         : diag::err_unknown_typename_suggest)
686                        << II);
687       II = Corrected.getCorrectionAsIdentifierInfo();
688     } else {
689       // We found a similarly-named type or interface; suggest that.
690       if (!SS || !SS->isSet()) {
691         diagnoseTypo(Corrected,
692                      PDiag(IsTemplateName ? diag::err_no_template_suggest
693                                           : diag::err_unknown_typename_suggest)
694                          << II, CanRecover);
695       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
696         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
697         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
698                                 II->getName().equals(CorrectedStr);
699         diagnoseTypo(Corrected,
700                      PDiag(IsTemplateName
701                                ? diag::err_no_member_template_suggest
702                                : diag::err_unknown_nested_typename_suggest)
703                          << II << DC << DroppedSpecifier << SS->getRange(),
704                      CanRecover);
705       } else {
706         llvm_unreachable("could not have corrected a typo here");
707       }
708 
709       if (!CanRecover)
710         return;
711 
712       CXXScopeSpec tmpSS;
713       if (Corrected.getCorrectionSpecifier())
714         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
715                           SourceRange(IILoc));
716       // FIXME: Support class template argument deduction here.
717       SuggestedType =
718           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
719                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
720                       /*IsCtorOrDtorName=*/false,
721                       /*WantNontrivialTypeSourceInfo=*/true);
722     }
723     return;
724   }
725 
726   if (getLangOpts().CPlusPlus && !IsTemplateName) {
727     // See if II is a class template that the user forgot to pass arguments to.
728     UnqualifiedId Name;
729     Name.setIdentifier(II, IILoc);
730     CXXScopeSpec EmptySS;
731     TemplateTy TemplateResult;
732     bool MemberOfUnknownSpecialization;
733     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
734                        Name, nullptr, true, TemplateResult,
735                        MemberOfUnknownSpecialization) == TNK_Type_template) {
736       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
737       return;
738     }
739   }
740 
741   // FIXME: Should we move the logic that tries to recover from a missing tag
742   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
743 
744   if (!SS || (!SS->isSet() && !SS->isInvalid()))
745     Diag(IILoc, IsTemplateName ? diag::err_no_template
746                                : diag::err_unknown_typename)
747         << II;
748   else if (DeclContext *DC = computeDeclContext(*SS, false))
749     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
750                                : diag::err_typename_nested_not_found)
751         << II << DC << SS->getRange();
752   else if (isDependentScopeSpecifier(*SS)) {
753     unsigned DiagID = diag::err_typename_missing;
754     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
755       DiagID = diag::ext_typename_missing;
756 
757     Diag(SS->getRange().getBegin(), DiagID)
758       << SS->getScopeRep() << II->getName()
759       << SourceRange(SS->getRange().getBegin(), IILoc)
760       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
761     SuggestedType = ActOnTypenameType(S, SourceLocation(),
762                                       *SS, *II, IILoc).get();
763   } else {
764     assert(SS && SS->isInvalid() &&
765            "Invalid scope specifier has already been diagnosed");
766   }
767 }
768 
769 /// Determine whether the given result set contains either a type name
770 /// or
771 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
772   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
773                        NextToken.is(tok::less);
774 
775   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
776     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
777       return true;
778 
779     if (CheckTemplate && isa<TemplateDecl>(*I))
780       return true;
781   }
782 
783   return false;
784 }
785 
786 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
787                                     Scope *S, CXXScopeSpec &SS,
788                                     IdentifierInfo *&Name,
789                                     SourceLocation NameLoc) {
790   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
791   SemaRef.LookupParsedName(R, S, &SS);
792   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
793     StringRef FixItTagName;
794     switch (Tag->getTagKind()) {
795       case TTK_Class:
796         FixItTagName = "class ";
797         break;
798 
799       case TTK_Enum:
800         FixItTagName = "enum ";
801         break;
802 
803       case TTK_Struct:
804         FixItTagName = "struct ";
805         break;
806 
807       case TTK_Interface:
808         FixItTagName = "__interface ";
809         break;
810 
811       case TTK_Union:
812         FixItTagName = "union ";
813         break;
814     }
815 
816     StringRef TagName = FixItTagName.drop_back();
817     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
818       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
819       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
820 
821     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
822          I != IEnd; ++I)
823       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
824         << Name << TagName;
825 
826     // Replace lookup results with just the tag decl.
827     Result.clear(Sema::LookupTagName);
828     SemaRef.LookupParsedName(Result, S, &SS);
829     return true;
830   }
831 
832   return false;
833 }
834 
835 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
836 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
837                                   QualType T, SourceLocation NameLoc) {
838   ASTContext &Context = S.Context;
839 
840   TypeLocBuilder Builder;
841   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
842 
843   T = S.getElaboratedType(ETK_None, SS, T);
844   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
845   ElabTL.setElaboratedKeywordLoc(SourceLocation());
846   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
847   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
848 }
849 
850 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
851                                             IdentifierInfo *&Name,
852                                             SourceLocation NameLoc,
853                                             const Token &NextToken,
854                                             CorrectionCandidateCallback *CCC) {
855   DeclarationNameInfo NameInfo(Name, NameLoc);
856   ObjCMethodDecl *CurMethod = getCurMethodDecl();
857 
858   assert(NextToken.isNot(tok::coloncolon) &&
859          "parse nested name specifiers before calling ClassifyName");
860   if (getLangOpts().CPlusPlus && SS.isSet() &&
861       isCurrentClassName(*Name, S, &SS)) {
862     // Per [class.qual]p2, this names the constructors of SS, not the
863     // injected-class-name. We don't have a classification for that.
864     // There's not much point caching this result, since the parser
865     // will reject it later.
866     return NameClassification::Unknown();
867   }
868 
869   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
870   LookupParsedName(Result, S, &SS, !CurMethod);
871 
872   if (SS.isInvalid())
873     return NameClassification::Error();
874 
875   // For unqualified lookup in a class template in MSVC mode, look into
876   // dependent base classes where the primary class template is known.
877   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
878     if (ParsedType TypeInBase =
879             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
880       return TypeInBase;
881   }
882 
883   // Perform lookup for Objective-C instance variables (including automatically
884   // synthesized instance variables), if we're in an Objective-C method.
885   // FIXME: This lookup really, really needs to be folded in to the normal
886   // unqualified lookup mechanism.
887   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
888     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
889     if (Ivar.isInvalid())
890       return NameClassification::Error();
891     if (Ivar.isUsable())
892       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
893 
894     // We defer builtin creation until after ivar lookup inside ObjC methods.
895     if (Result.empty())
896       LookupBuiltin(Result);
897   }
898 
899   bool SecondTry = false;
900   bool IsFilteredTemplateName = false;
901 
902 Corrected:
903   switch (Result.getResultKind()) {
904   case LookupResult::NotFound:
905     // If an unqualified-id is followed by a '(', then we have a function
906     // call.
907     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
908       // In C++, this is an ADL-only call.
909       // FIXME: Reference?
910       if (getLangOpts().CPlusPlus)
911         return NameClassification::UndeclaredNonType();
912 
913       // C90 6.3.2.2:
914       //   If the expression that precedes the parenthesized argument list in a
915       //   function call consists solely of an identifier, and if no
916       //   declaration is visible for this identifier, the identifier is
917       //   implicitly declared exactly as if, in the innermost block containing
918       //   the function call, the declaration
919       //
920       //     extern int identifier ();
921       //
922       //   appeared.
923       //
924       // We also allow this in C99 as an extension.
925       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
926         return NameClassification::NonType(D);
927     }
928 
929     if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
930       // In C++20 onwards, this could be an ADL-only call to a function
931       // template, and we're required to assume that this is a template name.
932       //
933       // FIXME: Find a way to still do typo correction in this case.
934       TemplateName Template =
935           Context.getAssumedTemplateName(NameInfo.getName());
936       return NameClassification::UndeclaredTemplate(Template);
937     }
938 
939     // In C, we first see whether there is a tag type by the same name, in
940     // which case it's likely that the user just forgot to write "enum",
941     // "struct", or "union".
942     if (!getLangOpts().CPlusPlus && !SecondTry &&
943         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
944       break;
945     }
946 
947     // Perform typo correction to determine if there is another name that is
948     // close to this name.
949     if (!SecondTry && CCC) {
950       SecondTry = true;
951       if (TypoCorrection Corrected =
952               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
953                           &SS, *CCC, CTK_ErrorRecovery)) {
954         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
955         unsigned QualifiedDiag = diag::err_no_member_suggest;
956 
957         NamedDecl *FirstDecl = Corrected.getFoundDecl();
958         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
959         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
960             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
961           UnqualifiedDiag = diag::err_no_template_suggest;
962           QualifiedDiag = diag::err_no_member_template_suggest;
963         } else if (UnderlyingFirstDecl &&
964                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
965                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
966                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
967           UnqualifiedDiag = diag::err_unknown_typename_suggest;
968           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
969         }
970 
971         if (SS.isEmpty()) {
972           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
973         } else {// FIXME: is this even reachable? Test it.
974           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
975           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
976                                   Name->getName().equals(CorrectedStr);
977           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
978                                     << Name << computeDeclContext(SS, false)
979                                     << DroppedSpecifier << SS.getRange());
980         }
981 
982         // Update the name, so that the caller has the new name.
983         Name = Corrected.getCorrectionAsIdentifierInfo();
984 
985         // Typo correction corrected to a keyword.
986         if (Corrected.isKeyword())
987           return Name;
988 
989         // Also update the LookupResult...
990         // FIXME: This should probably go away at some point
991         Result.clear();
992         Result.setLookupName(Corrected.getCorrection());
993         if (FirstDecl)
994           Result.addDecl(FirstDecl);
995 
996         // If we found an Objective-C instance variable, let
997         // LookupInObjCMethod build the appropriate expression to
998         // reference the ivar.
999         // FIXME: This is a gross hack.
1000         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1001           DeclResult R =
1002               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1003           if (R.isInvalid())
1004             return NameClassification::Error();
1005           if (R.isUsable())
1006             return NameClassification::NonType(Ivar);
1007         }
1008 
1009         goto Corrected;
1010       }
1011     }
1012 
1013     // We failed to correct; just fall through and let the parser deal with it.
1014     Result.suppressDiagnostics();
1015     return NameClassification::Unknown();
1016 
1017   case LookupResult::NotFoundInCurrentInstantiation: {
1018     // We performed name lookup into the current instantiation, and there were
1019     // dependent bases, so we treat this result the same way as any other
1020     // dependent nested-name-specifier.
1021 
1022     // C++ [temp.res]p2:
1023     //   A name used in a template declaration or definition and that is
1024     //   dependent on a template-parameter is assumed not to name a type
1025     //   unless the applicable name lookup finds a type name or the name is
1026     //   qualified by the keyword typename.
1027     //
1028     // FIXME: If the next token is '<', we might want to ask the parser to
1029     // perform some heroics to see if we actually have a
1030     // template-argument-list, which would indicate a missing 'template'
1031     // keyword here.
1032     return NameClassification::DependentNonType();
1033   }
1034 
1035   case LookupResult::Found:
1036   case LookupResult::FoundOverloaded:
1037   case LookupResult::FoundUnresolvedValue:
1038     break;
1039 
1040   case LookupResult::Ambiguous:
1041     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1042         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1043                                       /*AllowDependent=*/false)) {
1044       // C++ [temp.local]p3:
1045       //   A lookup that finds an injected-class-name (10.2) can result in an
1046       //   ambiguity in certain cases (for example, if it is found in more than
1047       //   one base class). If all of the injected-class-names that are found
1048       //   refer to specializations of the same class template, and if the name
1049       //   is followed by a template-argument-list, the reference refers to the
1050       //   class template itself and not a specialization thereof, and is not
1051       //   ambiguous.
1052       //
1053       // This filtering can make an ambiguous result into an unambiguous one,
1054       // so try again after filtering out template names.
1055       FilterAcceptableTemplateNames(Result);
1056       if (!Result.isAmbiguous()) {
1057         IsFilteredTemplateName = true;
1058         break;
1059       }
1060     }
1061 
1062     // Diagnose the ambiguity and return an error.
1063     return NameClassification::Error();
1064   }
1065 
1066   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1067       (IsFilteredTemplateName ||
1068        hasAnyAcceptableTemplateNames(
1069            Result, /*AllowFunctionTemplates=*/true,
1070            /*AllowDependent=*/false,
1071            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1072                getLangOpts().CPlusPlus2a))) {
1073     // C++ [temp.names]p3:
1074     //   After name lookup (3.4) finds that a name is a template-name or that
1075     //   an operator-function-id or a literal- operator-id refers to a set of
1076     //   overloaded functions any member of which is a function template if
1077     //   this is followed by a <, the < is always taken as the delimiter of a
1078     //   template-argument-list and never as the less-than operator.
1079     // C++2a [temp.names]p2:
1080     //   A name is also considered to refer to a template if it is an
1081     //   unqualified-id followed by a < and name lookup finds either one
1082     //   or more functions or finds nothing.
1083     if (!IsFilteredTemplateName)
1084       FilterAcceptableTemplateNames(Result);
1085 
1086     bool IsFunctionTemplate;
1087     bool IsVarTemplate;
1088     TemplateName Template;
1089     if (Result.end() - Result.begin() > 1) {
1090       IsFunctionTemplate = true;
1091       Template = Context.getOverloadedTemplateName(Result.begin(),
1092                                                    Result.end());
1093     } else if (!Result.empty()) {
1094       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1095           *Result.begin(), /*AllowFunctionTemplates=*/true,
1096           /*AllowDependent=*/false));
1097       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1098       IsVarTemplate = isa<VarTemplateDecl>(TD);
1099 
1100       if (SS.isNotEmpty())
1101         Template =
1102             Context.getQualifiedTemplateName(SS.getScopeRep(),
1103                                              /*TemplateKeyword=*/false, TD);
1104       else
1105         Template = TemplateName(TD);
1106     } else {
1107       // All results were non-template functions. This is a function template
1108       // name.
1109       IsFunctionTemplate = true;
1110       Template = Context.getAssumedTemplateName(NameInfo.getName());
1111     }
1112 
1113     if (IsFunctionTemplate) {
1114       // Function templates always go through overload resolution, at which
1115       // point we'll perform the various checks (e.g., accessibility) we need
1116       // to based on which function we selected.
1117       Result.suppressDiagnostics();
1118 
1119       return NameClassification::FunctionTemplate(Template);
1120     }
1121 
1122     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1123                          : NameClassification::TypeTemplate(Template);
1124   }
1125 
1126   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1127   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1128     DiagnoseUseOfDecl(Type, NameLoc);
1129     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1130     QualType T = Context.getTypeDeclType(Type);
1131     if (SS.isNotEmpty())
1132       return buildNestedType(*this, SS, T, NameLoc);
1133     return ParsedType::make(T);
1134   }
1135 
1136   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1137   if (!Class) {
1138     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1139     if (ObjCCompatibleAliasDecl *Alias =
1140             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1141       Class = Alias->getClassInterface();
1142   }
1143 
1144   if (Class) {
1145     DiagnoseUseOfDecl(Class, NameLoc);
1146 
1147     if (NextToken.is(tok::period)) {
1148       // Interface. <something> is parsed as a property reference expression.
1149       // Just return "unknown" as a fall-through for now.
1150       Result.suppressDiagnostics();
1151       return NameClassification::Unknown();
1152     }
1153 
1154     QualType T = Context.getObjCInterfaceType(Class);
1155     return ParsedType::make(T);
1156   }
1157 
1158   if (isa<ConceptDecl>(FirstDecl))
1159     return NameClassification::Concept(
1160         TemplateName(cast<TemplateDecl>(FirstDecl)));
1161 
1162   // We can have a type template here if we're classifying a template argument.
1163   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1164       !isa<VarTemplateDecl>(FirstDecl))
1165     return NameClassification::TypeTemplate(
1166         TemplateName(cast<TemplateDecl>(FirstDecl)));
1167 
1168   // Check for a tag type hidden by a non-type decl in a few cases where it
1169   // seems likely a type is wanted instead of the non-type that was found.
1170   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1171   if ((NextToken.is(tok::identifier) ||
1172        (NextIsOp &&
1173         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1174       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1175     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1176     DiagnoseUseOfDecl(Type, NameLoc);
1177     QualType T = Context.getTypeDeclType(Type);
1178     if (SS.isNotEmpty())
1179       return buildNestedType(*this, SS, T, NameLoc);
1180     return ParsedType::make(T);
1181   }
1182 
1183   // FIXME: This is context-dependent. We need to defer building the member
1184   // expression until the classification is consumed.
1185   if (FirstDecl->isCXXClassMember())
1186     return NameClassification::ContextIndependentExpr(
1187         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1188                                         S));
1189 
1190   // If we already know which single declaration is referenced, just annotate
1191   // that declaration directly.
1192   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1193   if (Result.isSingleResult() && !ADL)
1194     return NameClassification::NonType(Result.getRepresentativeDecl());
1195 
1196   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1197   // context in which we performed classification, so it's safe to do now.
1198   return NameClassification::ContextIndependentExpr(
1199       BuildDeclarationNameExpr(SS, Result, ADL));
1200 }
1201 
1202 ExprResult
1203 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1204                                              SourceLocation NameLoc) {
1205   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1206   CXXScopeSpec SS;
1207   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1208   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1209 }
1210 
1211 ExprResult
1212 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1213                                             IdentifierInfo *Name,
1214                                             SourceLocation NameLoc,
1215                                             bool IsAddressOfOperand) {
1216   DeclarationNameInfo NameInfo(Name, NameLoc);
1217   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1218                                     NameInfo, IsAddressOfOperand,
1219                                     /*TemplateArgs=*/nullptr);
1220 }
1221 
1222 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1223                                               NamedDecl *Found,
1224                                               SourceLocation NameLoc,
1225                                               const Token &NextToken) {
1226   if (getCurMethodDecl() && SS.isEmpty())
1227     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1228       return BuildIvarRefExpr(S, NameLoc, Ivar);
1229 
1230   // Reconstruct the lookup result.
1231   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1232   Result.addDecl(Found);
1233   Result.resolveKind();
1234 
1235   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1236   return BuildDeclarationNameExpr(SS, Result, ADL);
1237 }
1238 
1239 Sema::TemplateNameKindForDiagnostics
1240 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1241   auto *TD = Name.getAsTemplateDecl();
1242   if (!TD)
1243     return TemplateNameKindForDiagnostics::DependentTemplate;
1244   if (isa<ClassTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::ClassTemplate;
1246   if (isa<FunctionTemplateDecl>(TD))
1247     return TemplateNameKindForDiagnostics::FunctionTemplate;
1248   if (isa<VarTemplateDecl>(TD))
1249     return TemplateNameKindForDiagnostics::VarTemplate;
1250   if (isa<TypeAliasTemplateDecl>(TD))
1251     return TemplateNameKindForDiagnostics::AliasTemplate;
1252   if (isa<TemplateTemplateParmDecl>(TD))
1253     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1254   if (isa<ConceptDecl>(TD))
1255     return TemplateNameKindForDiagnostics::Concept;
1256   return TemplateNameKindForDiagnostics::DependentTemplate;
1257 }
1258 
1259 // Determines the context to return to after temporarily entering a
1260 // context.  This depends in an unnecessarily complicated way on the
1261 // exact ordering of callbacks from the parser.
1262 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1263 
1264   // Functions defined inline within classes aren't parsed until we've
1265   // finished parsing the top-level class, so the top-level class is
1266   // the context we'll need to return to.
1267   // A Lambda call operator whose parent is a class must not be treated
1268   // as an inline member function.  A Lambda can be used legally
1269   // either as an in-class member initializer or a default argument.  These
1270   // are parsed once the class has been marked complete and so the containing
1271   // context would be the nested class (when the lambda is defined in one);
1272   // If the class is not complete, then the lambda is being used in an
1273   // ill-formed fashion (such as to specify the width of a bit-field, or
1274   // in an array-bound) - in which case we still want to return the
1275   // lexically containing DC (which could be a nested class).
1276   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1277     DC = DC->getLexicalParent();
1278 
1279     // A function not defined within a class will always return to its
1280     // lexical context.
1281     if (!isa<CXXRecordDecl>(DC))
1282       return DC;
1283 
1284     // A C++ inline method/friend is parsed *after* the topmost class
1285     // it was declared in is fully parsed ("complete");  the topmost
1286     // class is the context we need to return to.
1287     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1288       DC = RD;
1289 
1290     // Return the declaration context of the topmost class the inline method is
1291     // declared in.
1292     return DC;
1293   }
1294 
1295   return DC->getLexicalParent();
1296 }
1297 
1298 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1299   assert(getContainingDC(DC) == CurContext &&
1300       "The next DeclContext should be lexically contained in the current one.");
1301   CurContext = DC;
1302   S->setEntity(DC);
1303 }
1304 
1305 void Sema::PopDeclContext() {
1306   assert(CurContext && "DeclContext imbalance!");
1307 
1308   CurContext = getContainingDC(CurContext);
1309   assert(CurContext && "Popped translation unit!");
1310 }
1311 
1312 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1313                                                                     Decl *D) {
1314   // Unlike PushDeclContext, the context to which we return is not necessarily
1315   // the containing DC of TD, because the new context will be some pre-existing
1316   // TagDecl definition instead of a fresh one.
1317   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1318   CurContext = cast<TagDecl>(D)->getDefinition();
1319   assert(CurContext && "skipping definition of undefined tag");
1320   // Start lookups from the parent of the current context; we don't want to look
1321   // into the pre-existing complete definition.
1322   S->setEntity(CurContext->getLookupParent());
1323   return Result;
1324 }
1325 
1326 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1327   CurContext = static_cast<decltype(CurContext)>(Context);
1328 }
1329 
1330 /// EnterDeclaratorContext - Used when we must lookup names in the context
1331 /// of a declarator's nested name specifier.
1332 ///
1333 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1334   // C++0x [basic.lookup.unqual]p13:
1335   //   A name used in the definition of a static data member of class
1336   //   X (after the qualified-id of the static member) is looked up as
1337   //   if the name was used in a member function of X.
1338   // C++0x [basic.lookup.unqual]p14:
1339   //   If a variable member of a namespace is defined outside of the
1340   //   scope of its namespace then any name used in the definition of
1341   //   the variable member (after the declarator-id) is looked up as
1342   //   if the definition of the variable member occurred in its
1343   //   namespace.
1344   // Both of these imply that we should push a scope whose context
1345   // is the semantic context of the declaration.  We can't use
1346   // PushDeclContext here because that context is not necessarily
1347   // lexically contained in the current context.  Fortunately,
1348   // the containing scope should have the appropriate information.
1349 
1350   assert(!S->getEntity() && "scope already has entity");
1351 
1352 #ifndef NDEBUG
1353   Scope *Ancestor = S->getParent();
1354   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1355   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1356 #endif
1357 
1358   CurContext = DC;
1359   S->setEntity(DC);
1360 }
1361 
1362 void Sema::ExitDeclaratorContext(Scope *S) {
1363   assert(S->getEntity() == CurContext && "Context imbalance!");
1364 
1365   // Switch back to the lexical context.  The safety of this is
1366   // enforced by an assert in EnterDeclaratorContext.
1367   Scope *Ancestor = S->getParent();
1368   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1369   CurContext = Ancestor->getEntity();
1370 
1371   // We don't need to do anything with the scope, which is going to
1372   // disappear.
1373 }
1374 
1375 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1376   // We assume that the caller has already called
1377   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1378   FunctionDecl *FD = D->getAsFunction();
1379   if (!FD)
1380     return;
1381 
1382   // Same implementation as PushDeclContext, but enters the context
1383   // from the lexical parent, rather than the top-level class.
1384   assert(CurContext == FD->getLexicalParent() &&
1385     "The next DeclContext should be lexically contained in the current one.");
1386   CurContext = FD;
1387   S->setEntity(CurContext);
1388 
1389   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1390     ParmVarDecl *Param = FD->getParamDecl(P);
1391     // If the parameter has an identifier, then add it to the scope
1392     if (Param->getIdentifier()) {
1393       S->AddDecl(Param);
1394       IdResolver.AddDecl(Param);
1395     }
1396   }
1397 }
1398 
1399 void Sema::ActOnExitFunctionContext() {
1400   // Same implementation as PopDeclContext, but returns to the lexical parent,
1401   // rather than the top-level class.
1402   assert(CurContext && "DeclContext imbalance!");
1403   CurContext = CurContext->getLexicalParent();
1404   assert(CurContext && "Popped translation unit!");
1405 }
1406 
1407 /// Determine whether we allow overloading of the function
1408 /// PrevDecl with another declaration.
1409 ///
1410 /// This routine determines whether overloading is possible, not
1411 /// whether some new function is actually an overload. It will return
1412 /// true in C++ (where we can always provide overloads) or, as an
1413 /// extension, in C when the previous function is already an
1414 /// overloaded function declaration or has the "overloadable"
1415 /// attribute.
1416 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1417                                        ASTContext &Context,
1418                                        const FunctionDecl *New) {
1419   if (Context.getLangOpts().CPlusPlus)
1420     return true;
1421 
1422   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1423     return true;
1424 
1425   return Previous.getResultKind() == LookupResult::Found &&
1426          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1427           New->hasAttr<OverloadableAttr>());
1428 }
1429 
1430 /// Add this decl to the scope shadowed decl chains.
1431 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1432   // Move up the scope chain until we find the nearest enclosing
1433   // non-transparent context. The declaration will be introduced into this
1434   // scope.
1435   while (S->getEntity() && S->getEntity()->isTransparentContext())
1436     S = S->getParent();
1437 
1438   // Add scoped declarations into their context, so that they can be
1439   // found later. Declarations without a context won't be inserted
1440   // into any context.
1441   if (AddToContext)
1442     CurContext->addDecl(D);
1443 
1444   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1445   // are function-local declarations.
1446   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1447       !D->getDeclContext()->getRedeclContext()->Equals(
1448         D->getLexicalDeclContext()->getRedeclContext()) &&
1449       !D->getLexicalDeclContext()->isFunctionOrMethod())
1450     return;
1451 
1452   // Template instantiations should also not be pushed into scope.
1453   if (isa<FunctionDecl>(D) &&
1454       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1455     return;
1456 
1457   // If this replaces anything in the current scope,
1458   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1459                                IEnd = IdResolver.end();
1460   for (; I != IEnd; ++I) {
1461     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1462       S->RemoveDecl(*I);
1463       IdResolver.RemoveDecl(*I);
1464 
1465       // Should only need to replace one decl.
1466       break;
1467     }
1468   }
1469 
1470   S->AddDecl(D);
1471 
1472   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1473     // Implicitly-generated labels may end up getting generated in an order that
1474     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1475     // the label at the appropriate place in the identifier chain.
1476     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1477       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1478       if (IDC == CurContext) {
1479         if (!S->isDeclScope(*I))
1480           continue;
1481       } else if (IDC->Encloses(CurContext))
1482         break;
1483     }
1484 
1485     IdResolver.InsertDeclAfter(I, D);
1486   } else {
1487     IdResolver.AddDecl(D);
1488   }
1489 }
1490 
1491 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1492                          bool AllowInlineNamespace) {
1493   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1494 }
1495 
1496 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1497   DeclContext *TargetDC = DC->getPrimaryContext();
1498   do {
1499     if (DeclContext *ScopeDC = S->getEntity())
1500       if (ScopeDC->getPrimaryContext() == TargetDC)
1501         return S;
1502   } while ((S = S->getParent()));
1503 
1504   return nullptr;
1505 }
1506 
1507 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1508                                             DeclContext*,
1509                                             ASTContext&);
1510 
1511 /// Filters out lookup results that don't fall within the given scope
1512 /// as determined by isDeclInScope.
1513 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1514                                 bool ConsiderLinkage,
1515                                 bool AllowInlineNamespace) {
1516   LookupResult::Filter F = R.makeFilter();
1517   while (F.hasNext()) {
1518     NamedDecl *D = F.next();
1519 
1520     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1521       continue;
1522 
1523     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1524       continue;
1525 
1526     F.erase();
1527   }
1528 
1529   F.done();
1530 }
1531 
1532 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1533 /// have compatible owning modules.
1534 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1535   // FIXME: The Modules TS is not clear about how friend declarations are
1536   // to be treated. It's not meaningful to have different owning modules for
1537   // linkage in redeclarations of the same entity, so for now allow the
1538   // redeclaration and change the owning modules to match.
1539   if (New->getFriendObjectKind() &&
1540       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1541     New->setLocalOwningModule(Old->getOwningModule());
1542     makeMergedDefinitionVisible(New);
1543     return false;
1544   }
1545 
1546   Module *NewM = New->getOwningModule();
1547   Module *OldM = Old->getOwningModule();
1548 
1549   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1550     NewM = NewM->Parent;
1551   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1552     OldM = OldM->Parent;
1553 
1554   if (NewM == OldM)
1555     return false;
1556 
1557   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1558   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1559   if (NewIsModuleInterface || OldIsModuleInterface) {
1560     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1561     //   if a declaration of D [...] appears in the purview of a module, all
1562     //   other such declarations shall appear in the purview of the same module
1563     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1564       << New
1565       << NewIsModuleInterface
1566       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1567       << OldIsModuleInterface
1568       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1569     Diag(Old->getLocation(), diag::note_previous_declaration);
1570     New->setInvalidDecl();
1571     return true;
1572   }
1573 
1574   return false;
1575 }
1576 
1577 static bool isUsingDecl(NamedDecl *D) {
1578   return isa<UsingShadowDecl>(D) ||
1579          isa<UnresolvedUsingTypenameDecl>(D) ||
1580          isa<UnresolvedUsingValueDecl>(D);
1581 }
1582 
1583 /// Removes using shadow declarations from the lookup results.
1584 static void RemoveUsingDecls(LookupResult &R) {
1585   LookupResult::Filter F = R.makeFilter();
1586   while (F.hasNext())
1587     if (isUsingDecl(F.next()))
1588       F.erase();
1589 
1590   F.done();
1591 }
1592 
1593 /// Check for this common pattern:
1594 /// @code
1595 /// class S {
1596 ///   S(const S&); // DO NOT IMPLEMENT
1597 ///   void operator=(const S&); // DO NOT IMPLEMENT
1598 /// };
1599 /// @endcode
1600 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1601   // FIXME: Should check for private access too but access is set after we get
1602   // the decl here.
1603   if (D->doesThisDeclarationHaveABody())
1604     return false;
1605 
1606   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1607     return CD->isCopyConstructor();
1608   return D->isCopyAssignmentOperator();
1609 }
1610 
1611 // We need this to handle
1612 //
1613 // typedef struct {
1614 //   void *foo() { return 0; }
1615 // } A;
1616 //
1617 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1618 // for example. If 'A', foo will have external linkage. If we have '*A',
1619 // foo will have no linkage. Since we can't know until we get to the end
1620 // of the typedef, this function finds out if D might have non-external linkage.
1621 // Callers should verify at the end of the TU if it D has external linkage or
1622 // not.
1623 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1624   const DeclContext *DC = D->getDeclContext();
1625   while (!DC->isTranslationUnit()) {
1626     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1627       if (!RD->hasNameForLinkage())
1628         return true;
1629     }
1630     DC = DC->getParent();
1631   }
1632 
1633   return !D->isExternallyVisible();
1634 }
1635 
1636 // FIXME: This needs to be refactored; some other isInMainFile users want
1637 // these semantics.
1638 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1639   if (S.TUKind != TU_Complete)
1640     return false;
1641   return S.SourceMgr.isInMainFile(Loc);
1642 }
1643 
1644 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1645   assert(D);
1646 
1647   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1648     return false;
1649 
1650   // Ignore all entities declared within templates, and out-of-line definitions
1651   // of members of class templates.
1652   if (D->getDeclContext()->isDependentContext() ||
1653       D->getLexicalDeclContext()->isDependentContext())
1654     return false;
1655 
1656   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1657     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1658       return false;
1659     // A non-out-of-line declaration of a member specialization was implicitly
1660     // instantiated; it's the out-of-line declaration that we're interested in.
1661     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1662         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1663       return false;
1664 
1665     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1666       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1667         return false;
1668     } else {
1669       // 'static inline' functions are defined in headers; don't warn.
1670       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1671         return false;
1672     }
1673 
1674     if (FD->doesThisDeclarationHaveABody() &&
1675         Context.DeclMustBeEmitted(FD))
1676       return false;
1677   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1678     // Constants and utility variables are defined in headers with internal
1679     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1680     // like "inline".)
1681     if (!isMainFileLoc(*this, VD->getLocation()))
1682       return false;
1683 
1684     if (Context.DeclMustBeEmitted(VD))
1685       return false;
1686 
1687     if (VD->isStaticDataMember() &&
1688         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1689       return false;
1690     if (VD->isStaticDataMember() &&
1691         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1692         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1693       return false;
1694 
1695     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1696       return false;
1697   } else {
1698     return false;
1699   }
1700 
1701   // Only warn for unused decls internal to the translation unit.
1702   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1703   // for inline functions defined in the main source file, for instance.
1704   return mightHaveNonExternalLinkage(D);
1705 }
1706 
1707 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1708   if (!D)
1709     return;
1710 
1711   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1712     const FunctionDecl *First = FD->getFirstDecl();
1713     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1714       return; // First should already be in the vector.
1715   }
1716 
1717   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1718     const VarDecl *First = VD->getFirstDecl();
1719     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1720       return; // First should already be in the vector.
1721   }
1722 
1723   if (ShouldWarnIfUnusedFileScopedDecl(D))
1724     UnusedFileScopedDecls.push_back(D);
1725 }
1726 
1727 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1728   if (D->isInvalidDecl())
1729     return false;
1730 
1731   bool Referenced = false;
1732   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1733     // For a decomposition declaration, warn if none of the bindings are
1734     // referenced, instead of if the variable itself is referenced (which
1735     // it is, by the bindings' expressions).
1736     for (auto *BD : DD->bindings()) {
1737       if (BD->isReferenced()) {
1738         Referenced = true;
1739         break;
1740       }
1741     }
1742   } else if (!D->getDeclName()) {
1743     return false;
1744   } else if (D->isReferenced() || D->isUsed()) {
1745     Referenced = true;
1746   }
1747 
1748   if (Referenced || D->hasAttr<UnusedAttr>() ||
1749       D->hasAttr<ObjCPreciseLifetimeAttr>())
1750     return false;
1751 
1752   if (isa<LabelDecl>(D))
1753     return true;
1754 
1755   // Except for labels, we only care about unused decls that are local to
1756   // functions.
1757   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1758   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1759     // For dependent types, the diagnostic is deferred.
1760     WithinFunction =
1761         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1762   if (!WithinFunction)
1763     return false;
1764 
1765   if (isa<TypedefNameDecl>(D))
1766     return true;
1767 
1768   // White-list anything that isn't a local variable.
1769   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1770     return false;
1771 
1772   // Types of valid local variables should be complete, so this should succeed.
1773   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1774 
1775     // White-list anything with an __attribute__((unused)) type.
1776     const auto *Ty = VD->getType().getTypePtr();
1777 
1778     // Only look at the outermost level of typedef.
1779     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1780       if (TT->getDecl()->hasAttr<UnusedAttr>())
1781         return false;
1782     }
1783 
1784     // If we failed to complete the type for some reason, or if the type is
1785     // dependent, don't diagnose the variable.
1786     if (Ty->isIncompleteType() || Ty->isDependentType())
1787       return false;
1788 
1789     // Look at the element type to ensure that the warning behaviour is
1790     // consistent for both scalars and arrays.
1791     Ty = Ty->getBaseElementTypeUnsafe();
1792 
1793     if (const TagType *TT = Ty->getAs<TagType>()) {
1794       const TagDecl *Tag = TT->getDecl();
1795       if (Tag->hasAttr<UnusedAttr>())
1796         return false;
1797 
1798       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1799         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1800           return false;
1801 
1802         if (const Expr *Init = VD->getInit()) {
1803           if (const ExprWithCleanups *Cleanups =
1804                   dyn_cast<ExprWithCleanups>(Init))
1805             Init = Cleanups->getSubExpr();
1806           const CXXConstructExpr *Construct =
1807             dyn_cast<CXXConstructExpr>(Init);
1808           if (Construct && !Construct->isElidable()) {
1809             CXXConstructorDecl *CD = Construct->getConstructor();
1810             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1811                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1812               return false;
1813           }
1814 
1815           // Suppress the warning if we don't know how this is constructed, and
1816           // it could possibly be non-trivial constructor.
1817           if (Init->isTypeDependent())
1818             for (const CXXConstructorDecl *Ctor : RD->ctors())
1819               if (!Ctor->isTrivial())
1820                 return false;
1821         }
1822       }
1823     }
1824 
1825     // TODO: __attribute__((unused)) templates?
1826   }
1827 
1828   return true;
1829 }
1830 
1831 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1832                                      FixItHint &Hint) {
1833   if (isa<LabelDecl>(D)) {
1834     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1835         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1836         true);
1837     if (AfterColon.isInvalid())
1838       return;
1839     Hint = FixItHint::CreateRemoval(
1840         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1841   }
1842 }
1843 
1844 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1845   if (D->getTypeForDecl()->isDependentType())
1846     return;
1847 
1848   for (auto *TmpD : D->decls()) {
1849     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1850       DiagnoseUnusedDecl(T);
1851     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1852       DiagnoseUnusedNestedTypedefs(R);
1853   }
1854 }
1855 
1856 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1857 /// unless they are marked attr(unused).
1858 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1859   if (!ShouldDiagnoseUnusedDecl(D))
1860     return;
1861 
1862   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1863     // typedefs can be referenced later on, so the diagnostics are emitted
1864     // at end-of-translation-unit.
1865     UnusedLocalTypedefNameCandidates.insert(TD);
1866     return;
1867   }
1868 
1869   FixItHint Hint;
1870   GenerateFixForUnusedDecl(D, Context, Hint);
1871 
1872   unsigned DiagID;
1873   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1874     DiagID = diag::warn_unused_exception_param;
1875   else if (isa<LabelDecl>(D))
1876     DiagID = diag::warn_unused_label;
1877   else
1878     DiagID = diag::warn_unused_variable;
1879 
1880   Diag(D->getLocation(), DiagID) << D << Hint;
1881 }
1882 
1883 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1884   // Verify that we have no forward references left.  If so, there was a goto
1885   // or address of a label taken, but no definition of it.  Label fwd
1886   // definitions are indicated with a null substmt which is also not a resolved
1887   // MS inline assembly label name.
1888   bool Diagnose = false;
1889   if (L->isMSAsmLabel())
1890     Diagnose = !L->isResolvedMSAsmLabel();
1891   else
1892     Diagnose = L->getStmt() == nullptr;
1893   if (Diagnose)
1894     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1895 }
1896 
1897 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1898   S->mergeNRVOIntoParent();
1899 
1900   if (S->decl_empty()) return;
1901   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1902          "Scope shouldn't contain decls!");
1903 
1904   for (auto *TmpD : S->decls()) {
1905     assert(TmpD && "This decl didn't get pushed??");
1906 
1907     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1908     NamedDecl *D = cast<NamedDecl>(TmpD);
1909 
1910     // Diagnose unused variables in this scope.
1911     if (!S->hasUnrecoverableErrorOccurred()) {
1912       DiagnoseUnusedDecl(D);
1913       if (const auto *RD = dyn_cast<RecordDecl>(D))
1914         DiagnoseUnusedNestedTypedefs(RD);
1915     }
1916 
1917     if (!D->getDeclName()) continue;
1918 
1919     // If this was a forward reference to a label, verify it was defined.
1920     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1921       CheckPoppedLabel(LD, *this);
1922 
1923     // Remove this name from our lexical scope, and warn on it if we haven't
1924     // already.
1925     IdResolver.RemoveDecl(D);
1926     auto ShadowI = ShadowingDecls.find(D);
1927     if (ShadowI != ShadowingDecls.end()) {
1928       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1929         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1930             << D << FD << FD->getParent();
1931         Diag(FD->getLocation(), diag::note_previous_declaration);
1932       }
1933       ShadowingDecls.erase(ShadowI);
1934     }
1935   }
1936 }
1937 
1938 /// Look for an Objective-C class in the translation unit.
1939 ///
1940 /// \param Id The name of the Objective-C class we're looking for. If
1941 /// typo-correction fixes this name, the Id will be updated
1942 /// to the fixed name.
1943 ///
1944 /// \param IdLoc The location of the name in the translation unit.
1945 ///
1946 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1947 /// if there is no class with the given name.
1948 ///
1949 /// \returns The declaration of the named Objective-C class, or NULL if the
1950 /// class could not be found.
1951 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1952                                               SourceLocation IdLoc,
1953                                               bool DoTypoCorrection) {
1954   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1955   // creation from this context.
1956   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1957 
1958   if (!IDecl && DoTypoCorrection) {
1959     // Perform typo correction at the given location, but only if we
1960     // find an Objective-C class name.
1961     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1962     if (TypoCorrection C =
1963             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1964                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1965       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1966       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1967       Id = IDecl->getIdentifier();
1968     }
1969   }
1970   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1971   // This routine must always return a class definition, if any.
1972   if (Def && Def->getDefinition())
1973       Def = Def->getDefinition();
1974   return Def;
1975 }
1976 
1977 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1978 /// from S, where a non-field would be declared. This routine copes
1979 /// with the difference between C and C++ scoping rules in structs and
1980 /// unions. For example, the following code is well-formed in C but
1981 /// ill-formed in C++:
1982 /// @code
1983 /// struct S6 {
1984 ///   enum { BAR } e;
1985 /// };
1986 ///
1987 /// void test_S6() {
1988 ///   struct S6 a;
1989 ///   a.e = BAR;
1990 /// }
1991 /// @endcode
1992 /// For the declaration of BAR, this routine will return a different
1993 /// scope. The scope S will be the scope of the unnamed enumeration
1994 /// within S6. In C++, this routine will return the scope associated
1995 /// with S6, because the enumeration's scope is a transparent
1996 /// context but structures can contain non-field names. In C, this
1997 /// routine will return the translation unit scope, since the
1998 /// enumeration's scope is a transparent context and structures cannot
1999 /// contain non-field names.
2000 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2001   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2002          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2003          (S->isClassScope() && !getLangOpts().CPlusPlus))
2004     S = S->getParent();
2005   return S;
2006 }
2007 
2008 /// Looks up the declaration of "struct objc_super" and
2009 /// saves it for later use in building builtin declaration of
2010 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2011 /// pre-existing declaration exists no action takes place.
2012 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2013                                         IdentifierInfo *II) {
2014   if (!II->isStr("objc_msgSendSuper"))
2015     return;
2016   ASTContext &Context = ThisSema.Context;
2017 
2018   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2019                       SourceLocation(), Sema::LookupTagName);
2020   ThisSema.LookupName(Result, S);
2021   if (Result.getResultKind() == LookupResult::Found)
2022     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2023       Context.setObjCSuperType(Context.getTagDeclType(TD));
2024 }
2025 
2026 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2027                                ASTContext::GetBuiltinTypeError Error) {
2028   switch (Error) {
2029   case ASTContext::GE_None:
2030     return "";
2031   case ASTContext::GE_Missing_type:
2032     return BuiltinInfo.getHeaderName(ID);
2033   case ASTContext::GE_Missing_stdio:
2034     return "stdio.h";
2035   case ASTContext::GE_Missing_setjmp:
2036     return "setjmp.h";
2037   case ASTContext::GE_Missing_ucontext:
2038     return "ucontext.h";
2039   }
2040   llvm_unreachable("unhandled error kind");
2041 }
2042 
2043 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2044 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2045 /// if we're creating this built-in in anticipation of redeclaring the
2046 /// built-in.
2047 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2048                                      Scope *S, bool ForRedeclaration,
2049                                      SourceLocation Loc) {
2050   LookupPredefedObjCSuperType(*this, S, II);
2051 
2052   ASTContext::GetBuiltinTypeError Error;
2053   QualType R = Context.GetBuiltinType(ID, Error);
2054   if (Error) {
2055     if (!ForRedeclaration)
2056       return nullptr;
2057 
2058     // If we have a builtin without an associated type we should not emit a
2059     // warning when we were not able to find a type for it.
2060     if (Error == ASTContext::GE_Missing_type)
2061       return nullptr;
2062 
2063     // If we could not find a type for setjmp it is because the jmp_buf type was
2064     // not defined prior to the setjmp declaration.
2065     if (Error == ASTContext::GE_Missing_setjmp) {
2066       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2067           << Context.BuiltinInfo.getName(ID);
2068       return nullptr;
2069     }
2070 
2071     // Generally, we emit a warning that the declaration requires the
2072     // appropriate header.
2073     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2074         << getHeaderName(Context.BuiltinInfo, ID, Error)
2075         << Context.BuiltinInfo.getName(ID);
2076     return nullptr;
2077   }
2078 
2079   if (!ForRedeclaration &&
2080       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2081        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2082     Diag(Loc, diag::ext_implicit_lib_function_decl)
2083         << Context.BuiltinInfo.getName(ID) << R;
2084     if (Context.BuiltinInfo.getHeaderName(ID) &&
2085         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2086       Diag(Loc, diag::note_include_header_or_declare)
2087           << Context.BuiltinInfo.getHeaderName(ID)
2088           << Context.BuiltinInfo.getName(ID);
2089   }
2090 
2091   if (R.isNull())
2092     return nullptr;
2093 
2094   DeclContext *Parent = Context.getTranslationUnitDecl();
2095   if (getLangOpts().CPlusPlus) {
2096     LinkageSpecDecl *CLinkageDecl =
2097         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2098                                 LinkageSpecDecl::lang_c, false);
2099     CLinkageDecl->setImplicit();
2100     Parent->addDecl(CLinkageDecl);
2101     Parent = CLinkageDecl;
2102   }
2103 
2104   FunctionDecl *New = FunctionDecl::Create(Context,
2105                                            Parent,
2106                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2107                                            SC_Extern,
2108                                            false,
2109                                            R->isFunctionProtoType());
2110   New->setImplicit();
2111 
2112   // Create Decl objects for each parameter, adding them to the
2113   // FunctionDecl.
2114   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2115     SmallVector<ParmVarDecl*, 16> Params;
2116     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2117       ParmVarDecl *parm =
2118           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2119                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2120                               SC_None, nullptr);
2121       parm->setScopeInfo(0, i);
2122       Params.push_back(parm);
2123     }
2124     New->setParams(Params);
2125   }
2126 
2127   AddKnownFunctionAttributes(New);
2128   RegisterLocallyScopedExternCDecl(New, S);
2129 
2130   // TUScope is the translation-unit scope to insert this function into.
2131   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2132   // relate Scopes to DeclContexts, and probably eliminate CurContext
2133   // entirely, but we're not there yet.
2134   DeclContext *SavedContext = CurContext;
2135   CurContext = Parent;
2136   PushOnScopeChains(New, TUScope);
2137   CurContext = SavedContext;
2138   return New;
2139 }
2140 
2141 /// Typedef declarations don't have linkage, but they still denote the same
2142 /// entity if their types are the same.
2143 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2144 /// isSameEntity.
2145 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2146                                                      TypedefNameDecl *Decl,
2147                                                      LookupResult &Previous) {
2148   // This is only interesting when modules are enabled.
2149   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2150     return;
2151 
2152   // Empty sets are uninteresting.
2153   if (Previous.empty())
2154     return;
2155 
2156   LookupResult::Filter Filter = Previous.makeFilter();
2157   while (Filter.hasNext()) {
2158     NamedDecl *Old = Filter.next();
2159 
2160     // Non-hidden declarations are never ignored.
2161     if (S.isVisible(Old))
2162       continue;
2163 
2164     // Declarations of the same entity are not ignored, even if they have
2165     // different linkages.
2166     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2167       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2168                                 Decl->getUnderlyingType()))
2169         continue;
2170 
2171       // If both declarations give a tag declaration a typedef name for linkage
2172       // purposes, then they declare the same entity.
2173       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2174           Decl->getAnonDeclWithTypedefName())
2175         continue;
2176     }
2177 
2178     Filter.erase();
2179   }
2180 
2181   Filter.done();
2182 }
2183 
2184 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2185   QualType OldType;
2186   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2187     OldType = OldTypedef->getUnderlyingType();
2188   else
2189     OldType = Context.getTypeDeclType(Old);
2190   QualType NewType = New->getUnderlyingType();
2191 
2192   if (NewType->isVariablyModifiedType()) {
2193     // Must not redefine a typedef with a variably-modified type.
2194     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2195     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2196       << Kind << NewType;
2197     if (Old->getLocation().isValid())
2198       notePreviousDefinition(Old, New->getLocation());
2199     New->setInvalidDecl();
2200     return true;
2201   }
2202 
2203   if (OldType != NewType &&
2204       !OldType->isDependentType() &&
2205       !NewType->isDependentType() &&
2206       !Context.hasSameType(OldType, NewType)) {
2207     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2208     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2209       << Kind << NewType << OldType;
2210     if (Old->getLocation().isValid())
2211       notePreviousDefinition(Old, New->getLocation());
2212     New->setInvalidDecl();
2213     return true;
2214   }
2215   return false;
2216 }
2217 
2218 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2219 /// same name and scope as a previous declaration 'Old'.  Figure out
2220 /// how to resolve this situation, merging decls or emitting
2221 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2222 ///
2223 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2224                                 LookupResult &OldDecls) {
2225   // If the new decl is known invalid already, don't bother doing any
2226   // merging checks.
2227   if (New->isInvalidDecl()) return;
2228 
2229   // Allow multiple definitions for ObjC built-in typedefs.
2230   // FIXME: Verify the underlying types are equivalent!
2231   if (getLangOpts().ObjC) {
2232     const IdentifierInfo *TypeID = New->getIdentifier();
2233     switch (TypeID->getLength()) {
2234     default: break;
2235     case 2:
2236       {
2237         if (!TypeID->isStr("id"))
2238           break;
2239         QualType T = New->getUnderlyingType();
2240         if (!T->isPointerType())
2241           break;
2242         if (!T->isVoidPointerType()) {
2243           QualType PT = T->castAs<PointerType>()->getPointeeType();
2244           if (!PT->isStructureType())
2245             break;
2246         }
2247         Context.setObjCIdRedefinitionType(T);
2248         // Install the built-in type for 'id', ignoring the current definition.
2249         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2250         return;
2251       }
2252     case 5:
2253       if (!TypeID->isStr("Class"))
2254         break;
2255       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2256       // Install the built-in type for 'Class', ignoring the current definition.
2257       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2258       return;
2259     case 3:
2260       if (!TypeID->isStr("SEL"))
2261         break;
2262       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2263       // Install the built-in type for 'SEL', ignoring the current definition.
2264       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2265       return;
2266     }
2267     // Fall through - the typedef name was not a builtin type.
2268   }
2269 
2270   // Verify the old decl was also a type.
2271   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2272   if (!Old) {
2273     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2274       << New->getDeclName();
2275 
2276     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2277     if (OldD->getLocation().isValid())
2278       notePreviousDefinition(OldD, New->getLocation());
2279 
2280     return New->setInvalidDecl();
2281   }
2282 
2283   // If the old declaration is invalid, just give up here.
2284   if (Old->isInvalidDecl())
2285     return New->setInvalidDecl();
2286 
2287   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2288     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2289     auto *NewTag = New->getAnonDeclWithTypedefName();
2290     NamedDecl *Hidden = nullptr;
2291     if (OldTag && NewTag &&
2292         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2293         !hasVisibleDefinition(OldTag, &Hidden)) {
2294       // There is a definition of this tag, but it is not visible. Use it
2295       // instead of our tag.
2296       New->setTypeForDecl(OldTD->getTypeForDecl());
2297       if (OldTD->isModed())
2298         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2299                                     OldTD->getUnderlyingType());
2300       else
2301         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2302 
2303       // Make the old tag definition visible.
2304       makeMergedDefinitionVisible(Hidden);
2305 
2306       // If this was an unscoped enumeration, yank all of its enumerators
2307       // out of the scope.
2308       if (isa<EnumDecl>(NewTag)) {
2309         Scope *EnumScope = getNonFieldDeclScope(S);
2310         for (auto *D : NewTag->decls()) {
2311           auto *ED = cast<EnumConstantDecl>(D);
2312           assert(EnumScope->isDeclScope(ED));
2313           EnumScope->RemoveDecl(ED);
2314           IdResolver.RemoveDecl(ED);
2315           ED->getLexicalDeclContext()->removeDecl(ED);
2316         }
2317       }
2318     }
2319   }
2320 
2321   // If the typedef types are not identical, reject them in all languages and
2322   // with any extensions enabled.
2323   if (isIncompatibleTypedef(Old, New))
2324     return;
2325 
2326   // The types match.  Link up the redeclaration chain and merge attributes if
2327   // the old declaration was a typedef.
2328   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2329     New->setPreviousDecl(Typedef);
2330     mergeDeclAttributes(New, Old);
2331   }
2332 
2333   if (getLangOpts().MicrosoftExt)
2334     return;
2335 
2336   if (getLangOpts().CPlusPlus) {
2337     // C++ [dcl.typedef]p2:
2338     //   In a given non-class scope, a typedef specifier can be used to
2339     //   redefine the name of any type declared in that scope to refer
2340     //   to the type to which it already refers.
2341     if (!isa<CXXRecordDecl>(CurContext))
2342       return;
2343 
2344     // C++0x [dcl.typedef]p4:
2345     //   In a given class scope, a typedef specifier can be used to redefine
2346     //   any class-name declared in that scope that is not also a typedef-name
2347     //   to refer to the type to which it already refers.
2348     //
2349     // This wording came in via DR424, which was a correction to the
2350     // wording in DR56, which accidentally banned code like:
2351     //
2352     //   struct S {
2353     //     typedef struct A { } A;
2354     //   };
2355     //
2356     // in the C++03 standard. We implement the C++0x semantics, which
2357     // allow the above but disallow
2358     //
2359     //   struct S {
2360     //     typedef int I;
2361     //     typedef int I;
2362     //   };
2363     //
2364     // since that was the intent of DR56.
2365     if (!isa<TypedefNameDecl>(Old))
2366       return;
2367 
2368     Diag(New->getLocation(), diag::err_redefinition)
2369       << New->getDeclName();
2370     notePreviousDefinition(Old, New->getLocation());
2371     return New->setInvalidDecl();
2372   }
2373 
2374   // Modules always permit redefinition of typedefs, as does C11.
2375   if (getLangOpts().Modules || getLangOpts().C11)
2376     return;
2377 
2378   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2379   // is normally mapped to an error, but can be controlled with
2380   // -Wtypedef-redefinition.  If either the original or the redefinition is
2381   // in a system header, don't emit this for compatibility with GCC.
2382   if (getDiagnostics().getSuppressSystemWarnings() &&
2383       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2384       (Old->isImplicit() ||
2385        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2386        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2387     return;
2388 
2389   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2390     << New->getDeclName();
2391   notePreviousDefinition(Old, New->getLocation());
2392 }
2393 
2394 /// DeclhasAttr - returns true if decl Declaration already has the target
2395 /// attribute.
2396 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2397   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2398   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2399   for (const auto *i : D->attrs())
2400     if (i->getKind() == A->getKind()) {
2401       if (Ann) {
2402         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2403           return true;
2404         continue;
2405       }
2406       // FIXME: Don't hardcode this check
2407       if (OA && isa<OwnershipAttr>(i))
2408         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2409       return true;
2410     }
2411 
2412   return false;
2413 }
2414 
2415 static bool isAttributeTargetADefinition(Decl *D) {
2416   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2417     return VD->isThisDeclarationADefinition();
2418   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2419     return TD->isCompleteDefinition() || TD->isBeingDefined();
2420   return true;
2421 }
2422 
2423 /// Merge alignment attributes from \p Old to \p New, taking into account the
2424 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2425 ///
2426 /// \return \c true if any attributes were added to \p New.
2427 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2428   // Look for alignas attributes on Old, and pick out whichever attribute
2429   // specifies the strictest alignment requirement.
2430   AlignedAttr *OldAlignasAttr = nullptr;
2431   AlignedAttr *OldStrictestAlignAttr = nullptr;
2432   unsigned OldAlign = 0;
2433   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2434     // FIXME: We have no way of representing inherited dependent alignments
2435     // in a case like:
2436     //   template<int A, int B> struct alignas(A) X;
2437     //   template<int A, int B> struct alignas(B) X {};
2438     // For now, we just ignore any alignas attributes which are not on the
2439     // definition in such a case.
2440     if (I->isAlignmentDependent())
2441       return false;
2442 
2443     if (I->isAlignas())
2444       OldAlignasAttr = I;
2445 
2446     unsigned Align = I->getAlignment(S.Context);
2447     if (Align > OldAlign) {
2448       OldAlign = Align;
2449       OldStrictestAlignAttr = I;
2450     }
2451   }
2452 
2453   // Look for alignas attributes on New.
2454   AlignedAttr *NewAlignasAttr = nullptr;
2455   unsigned NewAlign = 0;
2456   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2457     if (I->isAlignmentDependent())
2458       return false;
2459 
2460     if (I->isAlignas())
2461       NewAlignasAttr = I;
2462 
2463     unsigned Align = I->getAlignment(S.Context);
2464     if (Align > NewAlign)
2465       NewAlign = Align;
2466   }
2467 
2468   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2469     // Both declarations have 'alignas' attributes. We require them to match.
2470     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2471     // fall short. (If two declarations both have alignas, they must both match
2472     // every definition, and so must match each other if there is a definition.)
2473 
2474     // If either declaration only contains 'alignas(0)' specifiers, then it
2475     // specifies the natural alignment for the type.
2476     if (OldAlign == 0 || NewAlign == 0) {
2477       QualType Ty;
2478       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2479         Ty = VD->getType();
2480       else
2481         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2482 
2483       if (OldAlign == 0)
2484         OldAlign = S.Context.getTypeAlign(Ty);
2485       if (NewAlign == 0)
2486         NewAlign = S.Context.getTypeAlign(Ty);
2487     }
2488 
2489     if (OldAlign != NewAlign) {
2490       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2491         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2492         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2493       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2494     }
2495   }
2496 
2497   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2498     // C++11 [dcl.align]p6:
2499     //   if any declaration of an entity has an alignment-specifier,
2500     //   every defining declaration of that entity shall specify an
2501     //   equivalent alignment.
2502     // C11 6.7.5/7:
2503     //   If the definition of an object does not have an alignment
2504     //   specifier, any other declaration of that object shall also
2505     //   have no alignment specifier.
2506     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2507       << OldAlignasAttr;
2508     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2509       << OldAlignasAttr;
2510   }
2511 
2512   bool AnyAdded = false;
2513 
2514   // Ensure we have an attribute representing the strictest alignment.
2515   if (OldAlign > NewAlign) {
2516     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2517     Clone->setInherited(true);
2518     New->addAttr(Clone);
2519     AnyAdded = true;
2520   }
2521 
2522   // Ensure we have an alignas attribute if the old declaration had one.
2523   if (OldAlignasAttr && !NewAlignasAttr &&
2524       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2525     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2526     Clone->setInherited(true);
2527     New->addAttr(Clone);
2528     AnyAdded = true;
2529   }
2530 
2531   return AnyAdded;
2532 }
2533 
2534 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2535                                const InheritableAttr *Attr,
2536                                Sema::AvailabilityMergeKind AMK) {
2537   // This function copies an attribute Attr from a previous declaration to the
2538   // new declaration D if the new declaration doesn't itself have that attribute
2539   // yet or if that attribute allows duplicates.
2540   // If you're adding a new attribute that requires logic different from
2541   // "use explicit attribute on decl if present, else use attribute from
2542   // previous decl", for example if the attribute needs to be consistent
2543   // between redeclarations, you need to call a custom merge function here.
2544   InheritableAttr *NewAttr = nullptr;
2545   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2546     NewAttr = S.mergeAvailabilityAttr(
2547         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2548         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2549         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2550         AA->getPriority());
2551   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2552     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2553   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2554     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2555   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2556     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2557   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2558     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2559   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2560     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2561                                 FA->getFirstArg());
2562   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2563     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2564   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2565     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2566   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2567     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2568                                        IA->getInheritanceModel());
2569   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2570     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2571                                       &S.Context.Idents.get(AA->getSpelling()));
2572   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2573            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2574             isa<CUDAGlobalAttr>(Attr))) {
2575     // CUDA target attributes are part of function signature for
2576     // overloading purposes and must not be merged.
2577     return false;
2578   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2579     NewAttr = S.mergeMinSizeAttr(D, *MA);
2580   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2581     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2582   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2583     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2584   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2585     NewAttr = S.mergeCommonAttr(D, *CommonA);
2586   else if (isa<AlignedAttr>(Attr))
2587     // AlignedAttrs are handled separately, because we need to handle all
2588     // such attributes on a declaration at the same time.
2589     NewAttr = nullptr;
2590   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2591            (AMK == Sema::AMK_Override ||
2592             AMK == Sema::AMK_ProtocolImplementation))
2593     NewAttr = nullptr;
2594   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2595     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2596   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2597     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2598   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2599     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2600   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2601     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2602 
2603   if (NewAttr) {
2604     NewAttr->setInherited(true);
2605     D->addAttr(NewAttr);
2606     if (isa<MSInheritanceAttr>(NewAttr))
2607       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2608     return true;
2609   }
2610 
2611   return false;
2612 }
2613 
2614 static const NamedDecl *getDefinition(const Decl *D) {
2615   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2616     return TD->getDefinition();
2617   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2618     const VarDecl *Def = VD->getDefinition();
2619     if (Def)
2620       return Def;
2621     return VD->getActingDefinition();
2622   }
2623   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2624     return FD->getDefinition();
2625   return nullptr;
2626 }
2627 
2628 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2629   for (const auto *Attribute : D->attrs())
2630     if (Attribute->getKind() == Kind)
2631       return true;
2632   return false;
2633 }
2634 
2635 /// checkNewAttributesAfterDef - If we already have a definition, check that
2636 /// there are no new attributes in this declaration.
2637 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2638   if (!New->hasAttrs())
2639     return;
2640 
2641   const NamedDecl *Def = getDefinition(Old);
2642   if (!Def || Def == New)
2643     return;
2644 
2645   AttrVec &NewAttributes = New->getAttrs();
2646   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2647     const Attr *NewAttribute = NewAttributes[I];
2648 
2649     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2650       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2651         Sema::SkipBodyInfo SkipBody;
2652         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2653 
2654         // If we're skipping this definition, drop the "alias" attribute.
2655         if (SkipBody.ShouldSkip) {
2656           NewAttributes.erase(NewAttributes.begin() + I);
2657           --E;
2658           continue;
2659         }
2660       } else {
2661         VarDecl *VD = cast<VarDecl>(New);
2662         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2663                                 VarDecl::TentativeDefinition
2664                             ? diag::err_alias_after_tentative
2665                             : diag::err_redefinition;
2666         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2667         if (Diag == diag::err_redefinition)
2668           S.notePreviousDefinition(Def, VD->getLocation());
2669         else
2670           S.Diag(Def->getLocation(), diag::note_previous_definition);
2671         VD->setInvalidDecl();
2672       }
2673       ++I;
2674       continue;
2675     }
2676 
2677     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2678       // Tentative definitions are only interesting for the alias check above.
2679       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2680         ++I;
2681         continue;
2682       }
2683     }
2684 
2685     if (hasAttribute(Def, NewAttribute->getKind())) {
2686       ++I;
2687       continue; // regular attr merging will take care of validating this.
2688     }
2689 
2690     if (isa<C11NoReturnAttr>(NewAttribute)) {
2691       // C's _Noreturn is allowed to be added to a function after it is defined.
2692       ++I;
2693       continue;
2694     } else if (isa<UuidAttr>(NewAttribute)) {
2695       // msvc will allow a subsequent definition to add an uuid to a class
2696       ++I;
2697       continue;
2698     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2699       if (AA->isAlignas()) {
2700         // C++11 [dcl.align]p6:
2701         //   if any declaration of an entity has an alignment-specifier,
2702         //   every defining declaration of that entity shall specify an
2703         //   equivalent alignment.
2704         // C11 6.7.5/7:
2705         //   If the definition of an object does not have an alignment
2706         //   specifier, any other declaration of that object shall also
2707         //   have no alignment specifier.
2708         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2709           << AA;
2710         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2711           << AA;
2712         NewAttributes.erase(NewAttributes.begin() + I);
2713         --E;
2714         continue;
2715       }
2716     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2717       // If there is a C definition followed by a redeclaration with this
2718       // attribute then there are two different definitions. In C++, prefer the
2719       // standard diagnostics.
2720       if (!S.getLangOpts().CPlusPlus) {
2721         S.Diag(NewAttribute->getLocation(),
2722                diag::err_loader_uninitialized_redeclaration);
2723         S.Diag(Def->getLocation(), diag::note_previous_definition);
2724         NewAttributes.erase(NewAttributes.begin() + I);
2725         --E;
2726         continue;
2727       }
2728     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2729                cast<VarDecl>(New)->isInline() &&
2730                !cast<VarDecl>(New)->isInlineSpecified()) {
2731       // Don't warn about applying selectany to implicitly inline variables.
2732       // Older compilers and language modes would require the use of selectany
2733       // to make such variables inline, and it would have no effect if we
2734       // honored it.
2735       ++I;
2736       continue;
2737     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2738       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2739       // declarations after defintions.
2740       ++I;
2741       continue;
2742     }
2743 
2744     S.Diag(NewAttribute->getLocation(),
2745            diag::warn_attribute_precede_definition);
2746     S.Diag(Def->getLocation(), diag::note_previous_definition);
2747     NewAttributes.erase(NewAttributes.begin() + I);
2748     --E;
2749   }
2750 }
2751 
2752 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2753                                      const ConstInitAttr *CIAttr,
2754                                      bool AttrBeforeInit) {
2755   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2756 
2757   // Figure out a good way to write this specifier on the old declaration.
2758   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2759   // enough of the attribute list spelling information to extract that without
2760   // heroics.
2761   std::string SuitableSpelling;
2762   if (S.getLangOpts().CPlusPlus2a)
2763     SuitableSpelling = std::string(
2764         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2765   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2766     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2767         InsertLoc, {tok::l_square, tok::l_square,
2768                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2769                     S.PP.getIdentifierInfo("require_constant_initialization"),
2770                     tok::r_square, tok::r_square}));
2771   if (SuitableSpelling.empty())
2772     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2773         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2774                     S.PP.getIdentifierInfo("require_constant_initialization"),
2775                     tok::r_paren, tok::r_paren}));
2776   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2777     SuitableSpelling = "constinit";
2778   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2779     SuitableSpelling = "[[clang::require_constant_initialization]]";
2780   if (SuitableSpelling.empty())
2781     SuitableSpelling = "__attribute__((require_constant_initialization))";
2782   SuitableSpelling += " ";
2783 
2784   if (AttrBeforeInit) {
2785     // extern constinit int a;
2786     // int a = 0; // error (missing 'constinit'), accepted as extension
2787     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2788     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2789         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2790     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2791   } else {
2792     // int a = 0;
2793     // constinit extern int a; // error (missing 'constinit')
2794     S.Diag(CIAttr->getLocation(),
2795            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2796                                  : diag::warn_require_const_init_added_too_late)
2797         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2798     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2799         << CIAttr->isConstinit()
2800         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2801   }
2802 }
2803 
2804 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2805 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2806                                AvailabilityMergeKind AMK) {
2807   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2808     UsedAttr *NewAttr = OldAttr->clone(Context);
2809     NewAttr->setInherited(true);
2810     New->addAttr(NewAttr);
2811   }
2812 
2813   if (!Old->hasAttrs() && !New->hasAttrs())
2814     return;
2815 
2816   // [dcl.constinit]p1:
2817   //   If the [constinit] specifier is applied to any declaration of a
2818   //   variable, it shall be applied to the initializing declaration.
2819   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2820   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2821   if (bool(OldConstInit) != bool(NewConstInit)) {
2822     const auto *OldVD = cast<VarDecl>(Old);
2823     auto *NewVD = cast<VarDecl>(New);
2824 
2825     // Find the initializing declaration. Note that we might not have linked
2826     // the new declaration into the redeclaration chain yet.
2827     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2828     if (!InitDecl &&
2829         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2830       InitDecl = NewVD;
2831 
2832     if (InitDecl == NewVD) {
2833       // This is the initializing declaration. If it would inherit 'constinit',
2834       // that's ill-formed. (Note that we do not apply this to the attribute
2835       // form).
2836       if (OldConstInit && OldConstInit->isConstinit())
2837         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2838                                  /*AttrBeforeInit=*/true);
2839     } else if (NewConstInit) {
2840       // This is the first time we've been told that this declaration should
2841       // have a constant initializer. If we already saw the initializing
2842       // declaration, this is too late.
2843       if (InitDecl && InitDecl != NewVD) {
2844         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2845                                  /*AttrBeforeInit=*/false);
2846         NewVD->dropAttr<ConstInitAttr>();
2847       }
2848     }
2849   }
2850 
2851   // Attributes declared post-definition are currently ignored.
2852   checkNewAttributesAfterDef(*this, New, Old);
2853 
2854   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2855     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2856       if (!OldA->isEquivalent(NewA)) {
2857         // This redeclaration changes __asm__ label.
2858         Diag(New->getLocation(), diag::err_different_asm_label);
2859         Diag(OldA->getLocation(), diag::note_previous_declaration);
2860       }
2861     } else if (Old->isUsed()) {
2862       // This redeclaration adds an __asm__ label to a declaration that has
2863       // already been ODR-used.
2864       Diag(New->getLocation(), diag::err_late_asm_label_name)
2865         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2866     }
2867   }
2868 
2869   // Re-declaration cannot add abi_tag's.
2870   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2871     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2872       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2873         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2874                       NewTag) == OldAbiTagAttr->tags_end()) {
2875           Diag(NewAbiTagAttr->getLocation(),
2876                diag::err_new_abi_tag_on_redeclaration)
2877               << NewTag;
2878           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2879         }
2880       }
2881     } else {
2882       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2883       Diag(Old->getLocation(), diag::note_previous_declaration);
2884     }
2885   }
2886 
2887   // This redeclaration adds a section attribute.
2888   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2889     if (auto *VD = dyn_cast<VarDecl>(New)) {
2890       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2891         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2892         Diag(Old->getLocation(), diag::note_previous_declaration);
2893       }
2894     }
2895   }
2896 
2897   // Redeclaration adds code-seg attribute.
2898   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2899   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2900       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2901     Diag(New->getLocation(), diag::warn_mismatched_section)
2902          << 0 /*codeseg*/;
2903     Diag(Old->getLocation(), diag::note_previous_declaration);
2904   }
2905 
2906   if (!Old->hasAttrs())
2907     return;
2908 
2909   bool foundAny = New->hasAttrs();
2910 
2911   // Ensure that any moving of objects within the allocated map is done before
2912   // we process them.
2913   if (!foundAny) New->setAttrs(AttrVec());
2914 
2915   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2916     // Ignore deprecated/unavailable/availability attributes if requested.
2917     AvailabilityMergeKind LocalAMK = AMK_None;
2918     if (isa<DeprecatedAttr>(I) ||
2919         isa<UnavailableAttr>(I) ||
2920         isa<AvailabilityAttr>(I)) {
2921       switch (AMK) {
2922       case AMK_None:
2923         continue;
2924 
2925       case AMK_Redeclaration:
2926       case AMK_Override:
2927       case AMK_ProtocolImplementation:
2928         LocalAMK = AMK;
2929         break;
2930       }
2931     }
2932 
2933     // Already handled.
2934     if (isa<UsedAttr>(I))
2935       continue;
2936 
2937     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2938       foundAny = true;
2939   }
2940 
2941   if (mergeAlignedAttrs(*this, New, Old))
2942     foundAny = true;
2943 
2944   if (!foundAny) New->dropAttrs();
2945 }
2946 
2947 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2948 /// to the new one.
2949 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2950                                      const ParmVarDecl *oldDecl,
2951                                      Sema &S) {
2952   // C++11 [dcl.attr.depend]p2:
2953   //   The first declaration of a function shall specify the
2954   //   carries_dependency attribute for its declarator-id if any declaration
2955   //   of the function specifies the carries_dependency attribute.
2956   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2957   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2958     S.Diag(CDA->getLocation(),
2959            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2960     // Find the first declaration of the parameter.
2961     // FIXME: Should we build redeclaration chains for function parameters?
2962     const FunctionDecl *FirstFD =
2963       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2964     const ParmVarDecl *FirstVD =
2965       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2966     S.Diag(FirstVD->getLocation(),
2967            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2968   }
2969 
2970   if (!oldDecl->hasAttrs())
2971     return;
2972 
2973   bool foundAny = newDecl->hasAttrs();
2974 
2975   // Ensure that any moving of objects within the allocated map is
2976   // done before we process them.
2977   if (!foundAny) newDecl->setAttrs(AttrVec());
2978 
2979   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2980     if (!DeclHasAttr(newDecl, I)) {
2981       InheritableAttr *newAttr =
2982         cast<InheritableParamAttr>(I->clone(S.Context));
2983       newAttr->setInherited(true);
2984       newDecl->addAttr(newAttr);
2985       foundAny = true;
2986     }
2987   }
2988 
2989   if (!foundAny) newDecl->dropAttrs();
2990 }
2991 
2992 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2993                                 const ParmVarDecl *OldParam,
2994                                 Sema &S) {
2995   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2996     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2997       if (*Oldnullability != *Newnullability) {
2998         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2999           << DiagNullabilityKind(
3000                *Newnullability,
3001                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3002                 != 0))
3003           << DiagNullabilityKind(
3004                *Oldnullability,
3005                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3006                 != 0));
3007         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3008       }
3009     } else {
3010       QualType NewT = NewParam->getType();
3011       NewT = S.Context.getAttributedType(
3012                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3013                          NewT, NewT);
3014       NewParam->setType(NewT);
3015     }
3016   }
3017 }
3018 
3019 namespace {
3020 
3021 /// Used in MergeFunctionDecl to keep track of function parameters in
3022 /// C.
3023 struct GNUCompatibleParamWarning {
3024   ParmVarDecl *OldParm;
3025   ParmVarDecl *NewParm;
3026   QualType PromotedType;
3027 };
3028 
3029 } // end anonymous namespace
3030 
3031 // Determine whether the previous declaration was a definition, implicit
3032 // declaration, or a declaration.
3033 template <typename T>
3034 static std::pair<diag::kind, SourceLocation>
3035 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3036   diag::kind PrevDiag;
3037   SourceLocation OldLocation = Old->getLocation();
3038   if (Old->isThisDeclarationADefinition())
3039     PrevDiag = diag::note_previous_definition;
3040   else if (Old->isImplicit()) {
3041     PrevDiag = diag::note_previous_implicit_declaration;
3042     if (OldLocation.isInvalid())
3043       OldLocation = New->getLocation();
3044   } else
3045     PrevDiag = diag::note_previous_declaration;
3046   return std::make_pair(PrevDiag, OldLocation);
3047 }
3048 
3049 /// canRedefineFunction - checks if a function can be redefined. Currently,
3050 /// only extern inline functions can be redefined, and even then only in
3051 /// GNU89 mode.
3052 static bool canRedefineFunction(const FunctionDecl *FD,
3053                                 const LangOptions& LangOpts) {
3054   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3055           !LangOpts.CPlusPlus &&
3056           FD->isInlineSpecified() &&
3057           FD->getStorageClass() == SC_Extern);
3058 }
3059 
3060 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3061   const AttributedType *AT = T->getAs<AttributedType>();
3062   while (AT && !AT->isCallingConv())
3063     AT = AT->getModifiedType()->getAs<AttributedType>();
3064   return AT;
3065 }
3066 
3067 template <typename T>
3068 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3069   const DeclContext *DC = Old->getDeclContext();
3070   if (DC->isRecord())
3071     return false;
3072 
3073   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3074   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3075     return true;
3076   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3077     return true;
3078   return false;
3079 }
3080 
3081 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3082 static bool isExternC(VarTemplateDecl *) { return false; }
3083 
3084 /// Check whether a redeclaration of an entity introduced by a
3085 /// using-declaration is valid, given that we know it's not an overload
3086 /// (nor a hidden tag declaration).
3087 template<typename ExpectedDecl>
3088 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3089                                    ExpectedDecl *New) {
3090   // C++11 [basic.scope.declarative]p4:
3091   //   Given a set of declarations in a single declarative region, each of
3092   //   which specifies the same unqualified name,
3093   //   -- they shall all refer to the same entity, or all refer to functions
3094   //      and function templates; or
3095   //   -- exactly one declaration shall declare a class name or enumeration
3096   //      name that is not a typedef name and the other declarations shall all
3097   //      refer to the same variable or enumerator, or all refer to functions
3098   //      and function templates; in this case the class name or enumeration
3099   //      name is hidden (3.3.10).
3100 
3101   // C++11 [namespace.udecl]p14:
3102   //   If a function declaration in namespace scope or block scope has the
3103   //   same name and the same parameter-type-list as a function introduced
3104   //   by a using-declaration, and the declarations do not declare the same
3105   //   function, the program is ill-formed.
3106 
3107   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3108   if (Old &&
3109       !Old->getDeclContext()->getRedeclContext()->Equals(
3110           New->getDeclContext()->getRedeclContext()) &&
3111       !(isExternC(Old) && isExternC(New)))
3112     Old = nullptr;
3113 
3114   if (!Old) {
3115     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3116     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3117     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3118     return true;
3119   }
3120   return false;
3121 }
3122 
3123 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3124                                             const FunctionDecl *B) {
3125   assert(A->getNumParams() == B->getNumParams());
3126 
3127   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3128     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3129     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3130     if (AttrA == AttrB)
3131       return true;
3132     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3133            AttrA->isDynamic() == AttrB->isDynamic();
3134   };
3135 
3136   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3137 }
3138 
3139 /// If necessary, adjust the semantic declaration context for a qualified
3140 /// declaration to name the correct inline namespace within the qualifier.
3141 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3142                                                DeclaratorDecl *OldD) {
3143   // The only case where we need to update the DeclContext is when
3144   // redeclaration lookup for a qualified name finds a declaration
3145   // in an inline namespace within the context named by the qualifier:
3146   //
3147   //   inline namespace N { int f(); }
3148   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3149   //
3150   // For unqualified declarations, the semantic context *can* change
3151   // along the redeclaration chain (for local extern declarations,
3152   // extern "C" declarations, and friend declarations in particular).
3153   if (!NewD->getQualifier())
3154     return;
3155 
3156   // NewD is probably already in the right context.
3157   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3158   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3159   if (NamedDC->Equals(SemaDC))
3160     return;
3161 
3162   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3163           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3164          "unexpected context for redeclaration");
3165 
3166   auto *LexDC = NewD->getLexicalDeclContext();
3167   auto FixSemaDC = [=](NamedDecl *D) {
3168     if (!D)
3169       return;
3170     D->setDeclContext(SemaDC);
3171     D->setLexicalDeclContext(LexDC);
3172   };
3173 
3174   FixSemaDC(NewD);
3175   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3176     FixSemaDC(FD->getDescribedFunctionTemplate());
3177   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3178     FixSemaDC(VD->getDescribedVarTemplate());
3179 }
3180 
3181 /// MergeFunctionDecl - We just parsed a function 'New' from
3182 /// declarator D which has the same name and scope as a previous
3183 /// declaration 'Old'.  Figure out how to resolve this situation,
3184 /// merging decls or emitting diagnostics as appropriate.
3185 ///
3186 /// In C++, New and Old must be declarations that are not
3187 /// overloaded. Use IsOverload to determine whether New and Old are
3188 /// overloaded, and to select the Old declaration that New should be
3189 /// merged with.
3190 ///
3191 /// Returns true if there was an error, false otherwise.
3192 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3193                              Scope *S, bool MergeTypeWithOld) {
3194   // Verify the old decl was also a function.
3195   FunctionDecl *Old = OldD->getAsFunction();
3196   if (!Old) {
3197     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3198       if (New->getFriendObjectKind()) {
3199         Diag(New->getLocation(), diag::err_using_decl_friend);
3200         Diag(Shadow->getTargetDecl()->getLocation(),
3201              diag::note_using_decl_target);
3202         Diag(Shadow->getUsingDecl()->getLocation(),
3203              diag::note_using_decl) << 0;
3204         return true;
3205       }
3206 
3207       // Check whether the two declarations might declare the same function.
3208       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3209         return true;
3210       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3211     } else {
3212       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3213         << New->getDeclName();
3214       notePreviousDefinition(OldD, New->getLocation());
3215       return true;
3216     }
3217   }
3218 
3219   // If the old declaration is invalid, just give up here.
3220   if (Old->isInvalidDecl())
3221     return true;
3222 
3223   // Disallow redeclaration of some builtins.
3224   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3225     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3226     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3227         << Old << Old->getType();
3228     return true;
3229   }
3230 
3231   diag::kind PrevDiag;
3232   SourceLocation OldLocation;
3233   std::tie(PrevDiag, OldLocation) =
3234       getNoteDiagForInvalidRedeclaration(Old, New);
3235 
3236   // Don't complain about this if we're in GNU89 mode and the old function
3237   // is an extern inline function.
3238   // Don't complain about specializations. They are not supposed to have
3239   // storage classes.
3240   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3241       New->getStorageClass() == SC_Static &&
3242       Old->hasExternalFormalLinkage() &&
3243       !New->getTemplateSpecializationInfo() &&
3244       !canRedefineFunction(Old, getLangOpts())) {
3245     if (getLangOpts().MicrosoftExt) {
3246       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3247       Diag(OldLocation, PrevDiag);
3248     } else {
3249       Diag(New->getLocation(), diag::err_static_non_static) << New;
3250       Diag(OldLocation, PrevDiag);
3251       return true;
3252     }
3253   }
3254 
3255   if (New->hasAttr<InternalLinkageAttr>() &&
3256       !Old->hasAttr<InternalLinkageAttr>()) {
3257     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3258         << New->getDeclName();
3259     notePreviousDefinition(Old, New->getLocation());
3260     New->dropAttr<InternalLinkageAttr>();
3261   }
3262 
3263   if (CheckRedeclarationModuleOwnership(New, Old))
3264     return true;
3265 
3266   if (!getLangOpts().CPlusPlus) {
3267     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3268     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3269       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3270         << New << OldOvl;
3271 
3272       // Try our best to find a decl that actually has the overloadable
3273       // attribute for the note. In most cases (e.g. programs with only one
3274       // broken declaration/definition), this won't matter.
3275       //
3276       // FIXME: We could do this if we juggled some extra state in
3277       // OverloadableAttr, rather than just removing it.
3278       const Decl *DiagOld = Old;
3279       if (OldOvl) {
3280         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3281           const auto *A = D->getAttr<OverloadableAttr>();
3282           return A && !A->isImplicit();
3283         });
3284         // If we've implicitly added *all* of the overloadable attrs to this
3285         // chain, emitting a "previous redecl" note is pointless.
3286         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3287       }
3288 
3289       if (DiagOld)
3290         Diag(DiagOld->getLocation(),
3291              diag::note_attribute_overloadable_prev_overload)
3292           << OldOvl;
3293 
3294       if (OldOvl)
3295         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3296       else
3297         New->dropAttr<OverloadableAttr>();
3298     }
3299   }
3300 
3301   // If a function is first declared with a calling convention, but is later
3302   // declared or defined without one, all following decls assume the calling
3303   // convention of the first.
3304   //
3305   // It's OK if a function is first declared without a calling convention,
3306   // but is later declared or defined with the default calling convention.
3307   //
3308   // To test if either decl has an explicit calling convention, we look for
3309   // AttributedType sugar nodes on the type as written.  If they are missing or
3310   // were canonicalized away, we assume the calling convention was implicit.
3311   //
3312   // Note also that we DO NOT return at this point, because we still have
3313   // other tests to run.
3314   QualType OldQType = Context.getCanonicalType(Old->getType());
3315   QualType NewQType = Context.getCanonicalType(New->getType());
3316   const FunctionType *OldType = cast<FunctionType>(OldQType);
3317   const FunctionType *NewType = cast<FunctionType>(NewQType);
3318   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3319   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3320   bool RequiresAdjustment = false;
3321 
3322   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3323     FunctionDecl *First = Old->getFirstDecl();
3324     const FunctionType *FT =
3325         First->getType().getCanonicalType()->castAs<FunctionType>();
3326     FunctionType::ExtInfo FI = FT->getExtInfo();
3327     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3328     if (!NewCCExplicit) {
3329       // Inherit the CC from the previous declaration if it was specified
3330       // there but not here.
3331       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3332       RequiresAdjustment = true;
3333     } else if (New->getBuiltinID()) {
3334       // Calling Conventions on a Builtin aren't really useful and setting a
3335       // default calling convention and cdecl'ing some builtin redeclarations is
3336       // common, so warn and ignore the calling convention on the redeclaration.
3337       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3338           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3339           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3340       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3341       RequiresAdjustment = true;
3342     } else {
3343       // Calling conventions aren't compatible, so complain.
3344       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3345       Diag(New->getLocation(), diag::err_cconv_change)
3346         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3347         << !FirstCCExplicit
3348         << (!FirstCCExplicit ? "" :
3349             FunctionType::getNameForCallConv(FI.getCC()));
3350 
3351       // Put the note on the first decl, since it is the one that matters.
3352       Diag(First->getLocation(), diag::note_previous_declaration);
3353       return true;
3354     }
3355   }
3356 
3357   // FIXME: diagnose the other way around?
3358   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3359     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3360     RequiresAdjustment = true;
3361   }
3362 
3363   // Merge regparm attribute.
3364   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3365       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3366     if (NewTypeInfo.getHasRegParm()) {
3367       Diag(New->getLocation(), diag::err_regparm_mismatch)
3368         << NewType->getRegParmType()
3369         << OldType->getRegParmType();
3370       Diag(OldLocation, diag::note_previous_declaration);
3371       return true;
3372     }
3373 
3374     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3375     RequiresAdjustment = true;
3376   }
3377 
3378   // Merge ns_returns_retained attribute.
3379   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3380     if (NewTypeInfo.getProducesResult()) {
3381       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3382           << "'ns_returns_retained'";
3383       Diag(OldLocation, diag::note_previous_declaration);
3384       return true;
3385     }
3386 
3387     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3388     RequiresAdjustment = true;
3389   }
3390 
3391   if (OldTypeInfo.getNoCallerSavedRegs() !=
3392       NewTypeInfo.getNoCallerSavedRegs()) {
3393     if (NewTypeInfo.getNoCallerSavedRegs()) {
3394       AnyX86NoCallerSavedRegistersAttr *Attr =
3395         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3396       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3397       Diag(OldLocation, diag::note_previous_declaration);
3398       return true;
3399     }
3400 
3401     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3402     RequiresAdjustment = true;
3403   }
3404 
3405   if (RequiresAdjustment) {
3406     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3407     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3408     New->setType(QualType(AdjustedType, 0));
3409     NewQType = Context.getCanonicalType(New->getType());
3410   }
3411 
3412   // If this redeclaration makes the function inline, we may need to add it to
3413   // UndefinedButUsed.
3414   if (!Old->isInlined() && New->isInlined() &&
3415       !New->hasAttr<GNUInlineAttr>() &&
3416       !getLangOpts().GNUInline &&
3417       Old->isUsed(false) &&
3418       !Old->isDefined() && !New->isThisDeclarationADefinition())
3419     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3420                                            SourceLocation()));
3421 
3422   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3423   // about it.
3424   if (New->hasAttr<GNUInlineAttr>() &&
3425       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3426     UndefinedButUsed.erase(Old->getCanonicalDecl());
3427   }
3428 
3429   // If pass_object_size params don't match up perfectly, this isn't a valid
3430   // redeclaration.
3431   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3432       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3433     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3434         << New->getDeclName();
3435     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3436     return true;
3437   }
3438 
3439   if (getLangOpts().CPlusPlus) {
3440     // C++1z [over.load]p2
3441     //   Certain function declarations cannot be overloaded:
3442     //     -- Function declarations that differ only in the return type,
3443     //        the exception specification, or both cannot be overloaded.
3444 
3445     // Check the exception specifications match. This may recompute the type of
3446     // both Old and New if it resolved exception specifications, so grab the
3447     // types again after this. Because this updates the type, we do this before
3448     // any of the other checks below, which may update the "de facto" NewQType
3449     // but do not necessarily update the type of New.
3450     if (CheckEquivalentExceptionSpec(Old, New))
3451       return true;
3452     OldQType = Context.getCanonicalType(Old->getType());
3453     NewQType = Context.getCanonicalType(New->getType());
3454 
3455     // Go back to the type source info to compare the declared return types,
3456     // per C++1y [dcl.type.auto]p13:
3457     //   Redeclarations or specializations of a function or function template
3458     //   with a declared return type that uses a placeholder type shall also
3459     //   use that placeholder, not a deduced type.
3460     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3461     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3462     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3463         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3464                                        OldDeclaredReturnType)) {
3465       QualType ResQT;
3466       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3467           OldDeclaredReturnType->isObjCObjectPointerType())
3468         // FIXME: This does the wrong thing for a deduced return type.
3469         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3470       if (ResQT.isNull()) {
3471         if (New->isCXXClassMember() && New->isOutOfLine())
3472           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3473               << New << New->getReturnTypeSourceRange();
3474         else
3475           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3476               << New->getReturnTypeSourceRange();
3477         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3478                                     << Old->getReturnTypeSourceRange();
3479         return true;
3480       }
3481       else
3482         NewQType = ResQT;
3483     }
3484 
3485     QualType OldReturnType = OldType->getReturnType();
3486     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3487     if (OldReturnType != NewReturnType) {
3488       // If this function has a deduced return type and has already been
3489       // defined, copy the deduced value from the old declaration.
3490       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3491       if (OldAT && OldAT->isDeduced()) {
3492         New->setType(
3493             SubstAutoType(New->getType(),
3494                           OldAT->isDependentType() ? Context.DependentTy
3495                                                    : OldAT->getDeducedType()));
3496         NewQType = Context.getCanonicalType(
3497             SubstAutoType(NewQType,
3498                           OldAT->isDependentType() ? Context.DependentTy
3499                                                    : OldAT->getDeducedType()));
3500       }
3501     }
3502 
3503     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3504     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3505     if (OldMethod && NewMethod) {
3506       // Preserve triviality.
3507       NewMethod->setTrivial(OldMethod->isTrivial());
3508 
3509       // MSVC allows explicit template specialization at class scope:
3510       // 2 CXXMethodDecls referring to the same function will be injected.
3511       // We don't want a redeclaration error.
3512       bool IsClassScopeExplicitSpecialization =
3513                               OldMethod->isFunctionTemplateSpecialization() &&
3514                               NewMethod->isFunctionTemplateSpecialization();
3515       bool isFriend = NewMethod->getFriendObjectKind();
3516 
3517       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3518           !IsClassScopeExplicitSpecialization) {
3519         //    -- Member function declarations with the same name and the
3520         //       same parameter types cannot be overloaded if any of them
3521         //       is a static member function declaration.
3522         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3523           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3524           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3525           return true;
3526         }
3527 
3528         // C++ [class.mem]p1:
3529         //   [...] A member shall not be declared twice in the
3530         //   member-specification, except that a nested class or member
3531         //   class template can be declared and then later defined.
3532         if (!inTemplateInstantiation()) {
3533           unsigned NewDiag;
3534           if (isa<CXXConstructorDecl>(OldMethod))
3535             NewDiag = diag::err_constructor_redeclared;
3536           else if (isa<CXXDestructorDecl>(NewMethod))
3537             NewDiag = diag::err_destructor_redeclared;
3538           else if (isa<CXXConversionDecl>(NewMethod))
3539             NewDiag = diag::err_conv_function_redeclared;
3540           else
3541             NewDiag = diag::err_member_redeclared;
3542 
3543           Diag(New->getLocation(), NewDiag);
3544         } else {
3545           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3546             << New << New->getType();
3547         }
3548         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3549         return true;
3550 
3551       // Complain if this is an explicit declaration of a special
3552       // member that was initially declared implicitly.
3553       //
3554       // As an exception, it's okay to befriend such methods in order
3555       // to permit the implicit constructor/destructor/operator calls.
3556       } else if (OldMethod->isImplicit()) {
3557         if (isFriend) {
3558           NewMethod->setImplicit();
3559         } else {
3560           Diag(NewMethod->getLocation(),
3561                diag::err_definition_of_implicitly_declared_member)
3562             << New << getSpecialMember(OldMethod);
3563           return true;
3564         }
3565       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3566         Diag(NewMethod->getLocation(),
3567              diag::err_definition_of_explicitly_defaulted_member)
3568           << getSpecialMember(OldMethod);
3569         return true;
3570       }
3571     }
3572 
3573     // C++11 [dcl.attr.noreturn]p1:
3574     //   The first declaration of a function shall specify the noreturn
3575     //   attribute if any declaration of that function specifies the noreturn
3576     //   attribute.
3577     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3578     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3579       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3580       Diag(Old->getFirstDecl()->getLocation(),
3581            diag::note_noreturn_missing_first_decl);
3582     }
3583 
3584     // C++11 [dcl.attr.depend]p2:
3585     //   The first declaration of a function shall specify the
3586     //   carries_dependency attribute for its declarator-id if any declaration
3587     //   of the function specifies the carries_dependency attribute.
3588     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3589     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3590       Diag(CDA->getLocation(),
3591            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3592       Diag(Old->getFirstDecl()->getLocation(),
3593            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3594     }
3595 
3596     // (C++98 8.3.5p3):
3597     //   All declarations for a function shall agree exactly in both the
3598     //   return type and the parameter-type-list.
3599     // We also want to respect all the extended bits except noreturn.
3600 
3601     // noreturn should now match unless the old type info didn't have it.
3602     QualType OldQTypeForComparison = OldQType;
3603     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3604       auto *OldType = OldQType->castAs<FunctionProtoType>();
3605       const FunctionType *OldTypeForComparison
3606         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3607       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3608       assert(OldQTypeForComparison.isCanonical());
3609     }
3610 
3611     if (haveIncompatibleLanguageLinkages(Old, New)) {
3612       // As a special case, retain the language linkage from previous
3613       // declarations of a friend function as an extension.
3614       //
3615       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3616       // and is useful because there's otherwise no way to specify language
3617       // linkage within class scope.
3618       //
3619       // Check cautiously as the friend object kind isn't yet complete.
3620       if (New->getFriendObjectKind() != Decl::FOK_None) {
3621         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3622         Diag(OldLocation, PrevDiag);
3623       } else {
3624         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3625         Diag(OldLocation, PrevDiag);
3626         return true;
3627       }
3628     }
3629 
3630     // If the function types are compatible, merge the declarations. Ignore the
3631     // exception specifier because it was already checked above in
3632     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3633     // about incompatible types under -fms-compatibility.
3634     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3635                                                          NewQType))
3636       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3637 
3638     // If the types are imprecise (due to dependent constructs in friends or
3639     // local extern declarations), it's OK if they differ. We'll check again
3640     // during instantiation.
3641     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3642       return false;
3643 
3644     // Fall through for conflicting redeclarations and redefinitions.
3645   }
3646 
3647   // C: Function types need to be compatible, not identical. This handles
3648   // duplicate function decls like "void f(int); void f(enum X);" properly.
3649   if (!getLangOpts().CPlusPlus &&
3650       Context.typesAreCompatible(OldQType, NewQType)) {
3651     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3652     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3653     const FunctionProtoType *OldProto = nullptr;
3654     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3655         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3656       // The old declaration provided a function prototype, but the
3657       // new declaration does not. Merge in the prototype.
3658       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3659       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3660       NewQType =
3661           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3662                                   OldProto->getExtProtoInfo());
3663       New->setType(NewQType);
3664       New->setHasInheritedPrototype();
3665 
3666       // Synthesize parameters with the same types.
3667       SmallVector<ParmVarDecl*, 16> Params;
3668       for (const auto &ParamType : OldProto->param_types()) {
3669         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3670                                                  SourceLocation(), nullptr,
3671                                                  ParamType, /*TInfo=*/nullptr,
3672                                                  SC_None, nullptr);
3673         Param->setScopeInfo(0, Params.size());
3674         Param->setImplicit();
3675         Params.push_back(Param);
3676       }
3677 
3678       New->setParams(Params);
3679     }
3680 
3681     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3682   }
3683 
3684   // Check if the function types are compatible when pointer size address
3685   // spaces are ignored.
3686   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3687     return false;
3688 
3689   // GNU C permits a K&R definition to follow a prototype declaration
3690   // if the declared types of the parameters in the K&R definition
3691   // match the types in the prototype declaration, even when the
3692   // promoted types of the parameters from the K&R definition differ
3693   // from the types in the prototype. GCC then keeps the types from
3694   // the prototype.
3695   //
3696   // If a variadic prototype is followed by a non-variadic K&R definition,
3697   // the K&R definition becomes variadic.  This is sort of an edge case, but
3698   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3699   // C99 6.9.1p8.
3700   if (!getLangOpts().CPlusPlus &&
3701       Old->hasPrototype() && !New->hasPrototype() &&
3702       New->getType()->getAs<FunctionProtoType>() &&
3703       Old->getNumParams() == New->getNumParams()) {
3704     SmallVector<QualType, 16> ArgTypes;
3705     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3706     const FunctionProtoType *OldProto
3707       = Old->getType()->getAs<FunctionProtoType>();
3708     const FunctionProtoType *NewProto
3709       = New->getType()->getAs<FunctionProtoType>();
3710 
3711     // Determine whether this is the GNU C extension.
3712     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3713                                                NewProto->getReturnType());
3714     bool LooseCompatible = !MergedReturn.isNull();
3715     for (unsigned Idx = 0, End = Old->getNumParams();
3716          LooseCompatible && Idx != End; ++Idx) {
3717       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3718       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3719       if (Context.typesAreCompatible(OldParm->getType(),
3720                                      NewProto->getParamType(Idx))) {
3721         ArgTypes.push_back(NewParm->getType());
3722       } else if (Context.typesAreCompatible(OldParm->getType(),
3723                                             NewParm->getType(),
3724                                             /*CompareUnqualified=*/true)) {
3725         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3726                                            NewProto->getParamType(Idx) };
3727         Warnings.push_back(Warn);
3728         ArgTypes.push_back(NewParm->getType());
3729       } else
3730         LooseCompatible = false;
3731     }
3732 
3733     if (LooseCompatible) {
3734       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3735         Diag(Warnings[Warn].NewParm->getLocation(),
3736              diag::ext_param_promoted_not_compatible_with_prototype)
3737           << Warnings[Warn].PromotedType
3738           << Warnings[Warn].OldParm->getType();
3739         if (Warnings[Warn].OldParm->getLocation().isValid())
3740           Diag(Warnings[Warn].OldParm->getLocation(),
3741                diag::note_previous_declaration);
3742       }
3743 
3744       if (MergeTypeWithOld)
3745         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3746                                              OldProto->getExtProtoInfo()));
3747       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3748     }
3749 
3750     // Fall through to diagnose conflicting types.
3751   }
3752 
3753   // A function that has already been declared has been redeclared or
3754   // defined with a different type; show an appropriate diagnostic.
3755 
3756   // If the previous declaration was an implicitly-generated builtin
3757   // declaration, then at the very least we should use a specialized note.
3758   unsigned BuiltinID;
3759   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3760     // If it's actually a library-defined builtin function like 'malloc'
3761     // or 'printf', just warn about the incompatible redeclaration.
3762     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3763       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3764       Diag(OldLocation, diag::note_previous_builtin_declaration)
3765         << Old << Old->getType();
3766 
3767       // If this is a global redeclaration, just forget hereafter
3768       // about the "builtin-ness" of the function.
3769       //
3770       // Doing this for local extern declarations is problematic.  If
3771       // the builtin declaration remains visible, a second invalid
3772       // local declaration will produce a hard error; if it doesn't
3773       // remain visible, a single bogus local redeclaration (which is
3774       // actually only a warning) could break all the downstream code.
3775       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3776         New->getIdentifier()->revertBuiltin();
3777 
3778       return false;
3779     }
3780 
3781     PrevDiag = diag::note_previous_builtin_declaration;
3782   }
3783 
3784   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3785   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3786   return true;
3787 }
3788 
3789 /// Completes the merge of two function declarations that are
3790 /// known to be compatible.
3791 ///
3792 /// This routine handles the merging of attributes and other
3793 /// properties of function declarations from the old declaration to
3794 /// the new declaration, once we know that New is in fact a
3795 /// redeclaration of Old.
3796 ///
3797 /// \returns false
3798 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3799                                         Scope *S, bool MergeTypeWithOld) {
3800   // Merge the attributes
3801   mergeDeclAttributes(New, Old);
3802 
3803   // Merge "pure" flag.
3804   if (Old->isPure())
3805     New->setPure();
3806 
3807   // Merge "used" flag.
3808   if (Old->getMostRecentDecl()->isUsed(false))
3809     New->setIsUsed();
3810 
3811   // Merge attributes from the parameters.  These can mismatch with K&R
3812   // declarations.
3813   if (New->getNumParams() == Old->getNumParams())
3814       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3815         ParmVarDecl *NewParam = New->getParamDecl(i);
3816         ParmVarDecl *OldParam = Old->getParamDecl(i);
3817         mergeParamDeclAttributes(NewParam, OldParam, *this);
3818         mergeParamDeclTypes(NewParam, OldParam, *this);
3819       }
3820 
3821   if (getLangOpts().CPlusPlus)
3822     return MergeCXXFunctionDecl(New, Old, S);
3823 
3824   // Merge the function types so the we get the composite types for the return
3825   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3826   // was visible.
3827   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3828   if (!Merged.isNull() && MergeTypeWithOld)
3829     New->setType(Merged);
3830 
3831   return false;
3832 }
3833 
3834 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3835                                 ObjCMethodDecl *oldMethod) {
3836   // Merge the attributes, including deprecated/unavailable
3837   AvailabilityMergeKind MergeKind =
3838     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3839       ? AMK_ProtocolImplementation
3840       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3841                                                        : AMK_Override;
3842 
3843   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3844 
3845   // Merge attributes from the parameters.
3846   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3847                                        oe = oldMethod->param_end();
3848   for (ObjCMethodDecl::param_iterator
3849          ni = newMethod->param_begin(), ne = newMethod->param_end();
3850        ni != ne && oi != oe; ++ni, ++oi)
3851     mergeParamDeclAttributes(*ni, *oi, *this);
3852 
3853   CheckObjCMethodOverride(newMethod, oldMethod);
3854 }
3855 
3856 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3857   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3858 
3859   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3860          ? diag::err_redefinition_different_type
3861          : diag::err_redeclaration_different_type)
3862     << New->getDeclName() << New->getType() << Old->getType();
3863 
3864   diag::kind PrevDiag;
3865   SourceLocation OldLocation;
3866   std::tie(PrevDiag, OldLocation)
3867     = getNoteDiagForInvalidRedeclaration(Old, New);
3868   S.Diag(OldLocation, PrevDiag);
3869   New->setInvalidDecl();
3870 }
3871 
3872 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3873 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3874 /// emitting diagnostics as appropriate.
3875 ///
3876 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3877 /// to here in AddInitializerToDecl. We can't check them before the initializer
3878 /// is attached.
3879 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3880                              bool MergeTypeWithOld) {
3881   if (New->isInvalidDecl() || Old->isInvalidDecl())
3882     return;
3883 
3884   QualType MergedT;
3885   if (getLangOpts().CPlusPlus) {
3886     if (New->getType()->isUndeducedType()) {
3887       // We don't know what the new type is until the initializer is attached.
3888       return;
3889     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3890       // These could still be something that needs exception specs checked.
3891       return MergeVarDeclExceptionSpecs(New, Old);
3892     }
3893     // C++ [basic.link]p10:
3894     //   [...] the types specified by all declarations referring to a given
3895     //   object or function shall be identical, except that declarations for an
3896     //   array object can specify array types that differ by the presence or
3897     //   absence of a major array bound (8.3.4).
3898     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3899       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3900       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3901 
3902       // We are merging a variable declaration New into Old. If it has an array
3903       // bound, and that bound differs from Old's bound, we should diagnose the
3904       // mismatch.
3905       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3906         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3907              PrevVD = PrevVD->getPreviousDecl()) {
3908           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3909           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3910             continue;
3911 
3912           if (!Context.hasSameType(NewArray, PrevVDTy))
3913             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3914         }
3915       }
3916 
3917       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3918         if (Context.hasSameType(OldArray->getElementType(),
3919                                 NewArray->getElementType()))
3920           MergedT = New->getType();
3921       }
3922       // FIXME: Check visibility. New is hidden but has a complete type. If New
3923       // has no array bound, it should not inherit one from Old, if Old is not
3924       // visible.
3925       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3926         if (Context.hasSameType(OldArray->getElementType(),
3927                                 NewArray->getElementType()))
3928           MergedT = Old->getType();
3929       }
3930     }
3931     else if (New->getType()->isObjCObjectPointerType() &&
3932                Old->getType()->isObjCObjectPointerType()) {
3933       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3934                                               Old->getType());
3935     }
3936   } else {
3937     // C 6.2.7p2:
3938     //   All declarations that refer to the same object or function shall have
3939     //   compatible type.
3940     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3941   }
3942   if (MergedT.isNull()) {
3943     // It's OK if we couldn't merge types if either type is dependent, for a
3944     // block-scope variable. In other cases (static data members of class
3945     // templates, variable templates, ...), we require the types to be
3946     // equivalent.
3947     // FIXME: The C++ standard doesn't say anything about this.
3948     if ((New->getType()->isDependentType() ||
3949          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3950       // If the old type was dependent, we can't merge with it, so the new type
3951       // becomes dependent for now. We'll reproduce the original type when we
3952       // instantiate the TypeSourceInfo for the variable.
3953       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3954         New->setType(Context.DependentTy);
3955       return;
3956     }
3957     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3958   }
3959 
3960   // Don't actually update the type on the new declaration if the old
3961   // declaration was an extern declaration in a different scope.
3962   if (MergeTypeWithOld)
3963     New->setType(MergedT);
3964 }
3965 
3966 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3967                                   LookupResult &Previous) {
3968   // C11 6.2.7p4:
3969   //   For an identifier with internal or external linkage declared
3970   //   in a scope in which a prior declaration of that identifier is
3971   //   visible, if the prior declaration specifies internal or
3972   //   external linkage, the type of the identifier at the later
3973   //   declaration becomes the composite type.
3974   //
3975   // If the variable isn't visible, we do not merge with its type.
3976   if (Previous.isShadowed())
3977     return false;
3978 
3979   if (S.getLangOpts().CPlusPlus) {
3980     // C++11 [dcl.array]p3:
3981     //   If there is a preceding declaration of the entity in the same
3982     //   scope in which the bound was specified, an omitted array bound
3983     //   is taken to be the same as in that earlier declaration.
3984     return NewVD->isPreviousDeclInSameBlockScope() ||
3985            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3986             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3987   } else {
3988     // If the old declaration was function-local, don't merge with its
3989     // type unless we're in the same function.
3990     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3991            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3992   }
3993 }
3994 
3995 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3996 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3997 /// situation, merging decls or emitting diagnostics as appropriate.
3998 ///
3999 /// Tentative definition rules (C99 6.9.2p2) are checked by
4000 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4001 /// definitions here, since the initializer hasn't been attached.
4002 ///
4003 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4004   // If the new decl is already invalid, don't do any other checking.
4005   if (New->isInvalidDecl())
4006     return;
4007 
4008   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4009     return;
4010 
4011   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4012 
4013   // Verify the old decl was also a variable or variable template.
4014   VarDecl *Old = nullptr;
4015   VarTemplateDecl *OldTemplate = nullptr;
4016   if (Previous.isSingleResult()) {
4017     if (NewTemplate) {
4018       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4019       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4020 
4021       if (auto *Shadow =
4022               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4023         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4024           return New->setInvalidDecl();
4025     } else {
4026       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4027 
4028       if (auto *Shadow =
4029               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4030         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4031           return New->setInvalidDecl();
4032     }
4033   }
4034   if (!Old) {
4035     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4036         << New->getDeclName();
4037     notePreviousDefinition(Previous.getRepresentativeDecl(),
4038                            New->getLocation());
4039     return New->setInvalidDecl();
4040   }
4041 
4042   // Ensure the template parameters are compatible.
4043   if (NewTemplate &&
4044       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4045                                       OldTemplate->getTemplateParameters(),
4046                                       /*Complain=*/true, TPL_TemplateMatch))
4047     return New->setInvalidDecl();
4048 
4049   // C++ [class.mem]p1:
4050   //   A member shall not be declared twice in the member-specification [...]
4051   //
4052   // Here, we need only consider static data members.
4053   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4054     Diag(New->getLocation(), diag::err_duplicate_member)
4055       << New->getIdentifier();
4056     Diag(Old->getLocation(), diag::note_previous_declaration);
4057     New->setInvalidDecl();
4058   }
4059 
4060   mergeDeclAttributes(New, Old);
4061   // Warn if an already-declared variable is made a weak_import in a subsequent
4062   // declaration
4063   if (New->hasAttr<WeakImportAttr>() &&
4064       Old->getStorageClass() == SC_None &&
4065       !Old->hasAttr<WeakImportAttr>()) {
4066     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4067     notePreviousDefinition(Old, New->getLocation());
4068     // Remove weak_import attribute on new declaration.
4069     New->dropAttr<WeakImportAttr>();
4070   }
4071 
4072   if (New->hasAttr<InternalLinkageAttr>() &&
4073       !Old->hasAttr<InternalLinkageAttr>()) {
4074     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4075         << New->getDeclName();
4076     notePreviousDefinition(Old, New->getLocation());
4077     New->dropAttr<InternalLinkageAttr>();
4078   }
4079 
4080   // Merge the types.
4081   VarDecl *MostRecent = Old->getMostRecentDecl();
4082   if (MostRecent != Old) {
4083     MergeVarDeclTypes(New, MostRecent,
4084                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4085     if (New->isInvalidDecl())
4086       return;
4087   }
4088 
4089   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4090   if (New->isInvalidDecl())
4091     return;
4092 
4093   diag::kind PrevDiag;
4094   SourceLocation OldLocation;
4095   std::tie(PrevDiag, OldLocation) =
4096       getNoteDiagForInvalidRedeclaration(Old, New);
4097 
4098   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4099   if (New->getStorageClass() == SC_Static &&
4100       !New->isStaticDataMember() &&
4101       Old->hasExternalFormalLinkage()) {
4102     if (getLangOpts().MicrosoftExt) {
4103       Diag(New->getLocation(), diag::ext_static_non_static)
4104           << New->getDeclName();
4105       Diag(OldLocation, PrevDiag);
4106     } else {
4107       Diag(New->getLocation(), diag::err_static_non_static)
4108           << New->getDeclName();
4109       Diag(OldLocation, PrevDiag);
4110       return New->setInvalidDecl();
4111     }
4112   }
4113   // C99 6.2.2p4:
4114   //   For an identifier declared with the storage-class specifier
4115   //   extern in a scope in which a prior declaration of that
4116   //   identifier is visible,23) if the prior declaration specifies
4117   //   internal or external linkage, the linkage of the identifier at
4118   //   the later declaration is the same as the linkage specified at
4119   //   the prior declaration. If no prior declaration is visible, or
4120   //   if the prior declaration specifies no linkage, then the
4121   //   identifier has external linkage.
4122   if (New->hasExternalStorage() && Old->hasLinkage())
4123     /* Okay */;
4124   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4125            !New->isStaticDataMember() &&
4126            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4127     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4128     Diag(OldLocation, PrevDiag);
4129     return New->setInvalidDecl();
4130   }
4131 
4132   // Check if extern is followed by non-extern and vice-versa.
4133   if (New->hasExternalStorage() &&
4134       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4135     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4136     Diag(OldLocation, PrevDiag);
4137     return New->setInvalidDecl();
4138   }
4139   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4140       !New->hasExternalStorage()) {
4141     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4142     Diag(OldLocation, PrevDiag);
4143     return New->setInvalidDecl();
4144   }
4145 
4146   if (CheckRedeclarationModuleOwnership(New, Old))
4147     return;
4148 
4149   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4150 
4151   // FIXME: The test for external storage here seems wrong? We still
4152   // need to check for mismatches.
4153   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4154       // Don't complain about out-of-line definitions of static members.
4155       !(Old->getLexicalDeclContext()->isRecord() &&
4156         !New->getLexicalDeclContext()->isRecord())) {
4157     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4158     Diag(OldLocation, PrevDiag);
4159     return New->setInvalidDecl();
4160   }
4161 
4162   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4163     if (VarDecl *Def = Old->getDefinition()) {
4164       // C++1z [dcl.fcn.spec]p4:
4165       //   If the definition of a variable appears in a translation unit before
4166       //   its first declaration as inline, the program is ill-formed.
4167       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4168       Diag(Def->getLocation(), diag::note_previous_definition);
4169     }
4170   }
4171 
4172   // If this redeclaration makes the variable inline, we may need to add it to
4173   // UndefinedButUsed.
4174   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4175       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4176     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4177                                            SourceLocation()));
4178 
4179   if (New->getTLSKind() != Old->getTLSKind()) {
4180     if (!Old->getTLSKind()) {
4181       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4182       Diag(OldLocation, PrevDiag);
4183     } else if (!New->getTLSKind()) {
4184       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4185       Diag(OldLocation, PrevDiag);
4186     } else {
4187       // Do not allow redeclaration to change the variable between requiring
4188       // static and dynamic initialization.
4189       // FIXME: GCC allows this, but uses the TLS keyword on the first
4190       // declaration to determine the kind. Do we need to be compatible here?
4191       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4192         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4193       Diag(OldLocation, PrevDiag);
4194     }
4195   }
4196 
4197   // C++ doesn't have tentative definitions, so go right ahead and check here.
4198   if (getLangOpts().CPlusPlus &&
4199       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4200     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4201         Old->getCanonicalDecl()->isConstexpr()) {
4202       // This definition won't be a definition any more once it's been merged.
4203       Diag(New->getLocation(),
4204            diag::warn_deprecated_redundant_constexpr_static_def);
4205     } else if (VarDecl *Def = Old->getDefinition()) {
4206       if (checkVarDeclRedefinition(Def, New))
4207         return;
4208     }
4209   }
4210 
4211   if (haveIncompatibleLanguageLinkages(Old, New)) {
4212     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4213     Diag(OldLocation, PrevDiag);
4214     New->setInvalidDecl();
4215     return;
4216   }
4217 
4218   // Merge "used" flag.
4219   if (Old->getMostRecentDecl()->isUsed(false))
4220     New->setIsUsed();
4221 
4222   // Keep a chain of previous declarations.
4223   New->setPreviousDecl(Old);
4224   if (NewTemplate)
4225     NewTemplate->setPreviousDecl(OldTemplate);
4226   adjustDeclContextForDeclaratorDecl(New, Old);
4227 
4228   // Inherit access appropriately.
4229   New->setAccess(Old->getAccess());
4230   if (NewTemplate)
4231     NewTemplate->setAccess(New->getAccess());
4232 
4233   if (Old->isInline())
4234     New->setImplicitlyInline();
4235 }
4236 
4237 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4238   SourceManager &SrcMgr = getSourceManager();
4239   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4240   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4241   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4242   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4243   auto &HSI = PP.getHeaderSearchInfo();
4244   StringRef HdrFilename =
4245       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4246 
4247   auto noteFromModuleOrInclude = [&](Module *Mod,
4248                                      SourceLocation IncLoc) -> bool {
4249     // Redefinition errors with modules are common with non modular mapped
4250     // headers, example: a non-modular header H in module A that also gets
4251     // included directly in a TU. Pointing twice to the same header/definition
4252     // is confusing, try to get better diagnostics when modules is on.
4253     if (IncLoc.isValid()) {
4254       if (Mod) {
4255         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4256             << HdrFilename.str() << Mod->getFullModuleName();
4257         if (!Mod->DefinitionLoc.isInvalid())
4258           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4259               << Mod->getFullModuleName();
4260       } else {
4261         Diag(IncLoc, diag::note_redefinition_include_same_file)
4262             << HdrFilename.str();
4263       }
4264       return true;
4265     }
4266 
4267     return false;
4268   };
4269 
4270   // Is it the same file and same offset? Provide more information on why
4271   // this leads to a redefinition error.
4272   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4273     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4274     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4275     bool EmittedDiag =
4276         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4277     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4278 
4279     // If the header has no guards, emit a note suggesting one.
4280     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4281       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4282 
4283     if (EmittedDiag)
4284       return;
4285   }
4286 
4287   // Redefinition coming from different files or couldn't do better above.
4288   if (Old->getLocation().isValid())
4289     Diag(Old->getLocation(), diag::note_previous_definition);
4290 }
4291 
4292 /// We've just determined that \p Old and \p New both appear to be definitions
4293 /// of the same variable. Either diagnose or fix the problem.
4294 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4295   if (!hasVisibleDefinition(Old) &&
4296       (New->getFormalLinkage() == InternalLinkage ||
4297        New->isInline() ||
4298        New->getDescribedVarTemplate() ||
4299        New->getNumTemplateParameterLists() ||
4300        New->getDeclContext()->isDependentContext())) {
4301     // The previous definition is hidden, and multiple definitions are
4302     // permitted (in separate TUs). Demote this to a declaration.
4303     New->demoteThisDefinitionToDeclaration();
4304 
4305     // Make the canonical definition visible.
4306     if (auto *OldTD = Old->getDescribedVarTemplate())
4307       makeMergedDefinitionVisible(OldTD);
4308     makeMergedDefinitionVisible(Old);
4309     return false;
4310   } else {
4311     Diag(New->getLocation(), diag::err_redefinition) << New;
4312     notePreviousDefinition(Old, New->getLocation());
4313     New->setInvalidDecl();
4314     return true;
4315   }
4316 }
4317 
4318 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4319 /// no declarator (e.g. "struct foo;") is parsed.
4320 Decl *
4321 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4322                                  RecordDecl *&AnonRecord) {
4323   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4324                                     AnonRecord);
4325 }
4326 
4327 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4328 // disambiguate entities defined in different scopes.
4329 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4330 // compatibility.
4331 // We will pick our mangling number depending on which version of MSVC is being
4332 // targeted.
4333 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4334   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4335              ? S->getMSCurManglingNumber()
4336              : S->getMSLastManglingNumber();
4337 }
4338 
4339 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4340   if (!Context.getLangOpts().CPlusPlus)
4341     return;
4342 
4343   if (isa<CXXRecordDecl>(Tag->getParent())) {
4344     // If this tag is the direct child of a class, number it if
4345     // it is anonymous.
4346     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4347       return;
4348     MangleNumberingContext &MCtx =
4349         Context.getManglingNumberContext(Tag->getParent());
4350     Context.setManglingNumber(
4351         Tag, MCtx.getManglingNumber(
4352                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4353     return;
4354   }
4355 
4356   // If this tag isn't a direct child of a class, number it if it is local.
4357   MangleNumberingContext *MCtx;
4358   Decl *ManglingContextDecl;
4359   std::tie(MCtx, ManglingContextDecl) =
4360       getCurrentMangleNumberContext(Tag->getDeclContext());
4361   if (MCtx) {
4362     Context.setManglingNumber(
4363         Tag, MCtx->getManglingNumber(
4364                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4365   }
4366 }
4367 
4368 namespace {
4369 struct NonCLikeKind {
4370   enum {
4371     None,
4372     BaseClass,
4373     DefaultMemberInit,
4374     Lambda,
4375     Friend,
4376     OtherMember,
4377     Invalid,
4378   } Kind = None;
4379   SourceRange Range;
4380 
4381   explicit operator bool() { return Kind != None; }
4382 };
4383 }
4384 
4385 /// Determine whether a class is C-like, according to the rules of C++
4386 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4387 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4388   if (RD->isInvalidDecl())
4389     return {NonCLikeKind::Invalid, {}};
4390 
4391   // C++ [dcl.typedef]p9: [P1766R1]
4392   //   An unnamed class with a typedef name for linkage purposes shall not
4393   //
4394   //    -- have any base classes
4395   if (RD->getNumBases())
4396     return {NonCLikeKind::BaseClass,
4397             SourceRange(RD->bases_begin()->getBeginLoc(),
4398                         RD->bases_end()[-1].getEndLoc())};
4399   bool Invalid = false;
4400   for (Decl *D : RD->decls()) {
4401     // Don't complain about things we already diagnosed.
4402     if (D->isInvalidDecl()) {
4403       Invalid = true;
4404       continue;
4405     }
4406 
4407     //  -- have any [...] default member initializers
4408     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4409       if (FD->hasInClassInitializer()) {
4410         auto *Init = FD->getInClassInitializer();
4411         return {NonCLikeKind::DefaultMemberInit,
4412                 Init ? Init->getSourceRange() : D->getSourceRange()};
4413       }
4414       continue;
4415     }
4416 
4417     // FIXME: We don't allow friend declarations. This violates the wording of
4418     // P1766, but not the intent.
4419     if (isa<FriendDecl>(D))
4420       return {NonCLikeKind::Friend, D->getSourceRange()};
4421 
4422     //  -- declare any members other than non-static data members, member
4423     //     enumerations, or member classes,
4424     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4425         isa<EnumDecl>(D))
4426       continue;
4427     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4428     if (!MemberRD)
4429       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4430 
4431     //  -- contain a lambda-expression,
4432     if (MemberRD->isLambda())
4433       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4434 
4435     //  and all member classes shall also satisfy these requirements
4436     //  (recursively).
4437     if (MemberRD->isThisDeclarationADefinition()) {
4438       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4439         return Kind;
4440     }
4441   }
4442 
4443   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4444 }
4445 
4446 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4447                                         TypedefNameDecl *NewTD) {
4448   if (TagFromDeclSpec->isInvalidDecl())
4449     return;
4450 
4451   // Do nothing if the tag already has a name for linkage purposes.
4452   if (TagFromDeclSpec->hasNameForLinkage())
4453     return;
4454 
4455   // A well-formed anonymous tag must always be a TUK_Definition.
4456   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4457 
4458   // The type must match the tag exactly;  no qualifiers allowed.
4459   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4460                            Context.getTagDeclType(TagFromDeclSpec))) {
4461     if (getLangOpts().CPlusPlus)
4462       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4463     return;
4464   }
4465 
4466   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4467   //   An unnamed class with a typedef name for linkage purposes shall [be
4468   //   C-like].
4469   //
4470   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4471   // shouldn't happen, but there are constructs that the language rule doesn't
4472   // disallow for which we can't reasonably avoid computing linkage early.
4473   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4474   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4475                              : NonCLikeKind();
4476   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4477   if (NonCLike || ChangesLinkage) {
4478     if (NonCLike.Kind == NonCLikeKind::Invalid)
4479       return;
4480 
4481     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4482     if (ChangesLinkage) {
4483       // If the linkage changes, we can't accept this as an extension.
4484       if (NonCLike.Kind == NonCLikeKind::None)
4485         DiagID = diag::err_typedef_changes_linkage;
4486       else
4487         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4488     }
4489 
4490     SourceLocation FixitLoc =
4491         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4492     llvm::SmallString<40> TextToInsert;
4493     TextToInsert += ' ';
4494     TextToInsert += NewTD->getIdentifier()->getName();
4495 
4496     Diag(FixitLoc, DiagID)
4497       << isa<TypeAliasDecl>(NewTD)
4498       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4499     if (NonCLike.Kind != NonCLikeKind::None) {
4500       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4501         << NonCLike.Kind - 1 << NonCLike.Range;
4502     }
4503     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4504       << NewTD << isa<TypeAliasDecl>(NewTD);
4505 
4506     if (ChangesLinkage)
4507       return;
4508   }
4509 
4510   // Otherwise, set this as the anon-decl typedef for the tag.
4511   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4512 }
4513 
4514 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4515   switch (T) {
4516   case DeclSpec::TST_class:
4517     return 0;
4518   case DeclSpec::TST_struct:
4519     return 1;
4520   case DeclSpec::TST_interface:
4521     return 2;
4522   case DeclSpec::TST_union:
4523     return 3;
4524   case DeclSpec::TST_enum:
4525     return 4;
4526   default:
4527     llvm_unreachable("unexpected type specifier");
4528   }
4529 }
4530 
4531 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4532 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4533 /// parameters to cope with template friend declarations.
4534 Decl *
4535 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4536                                  MultiTemplateParamsArg TemplateParams,
4537                                  bool IsExplicitInstantiation,
4538                                  RecordDecl *&AnonRecord) {
4539   Decl *TagD = nullptr;
4540   TagDecl *Tag = nullptr;
4541   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4542       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4543       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4544       DS.getTypeSpecType() == DeclSpec::TST_union ||
4545       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4546     TagD = DS.getRepAsDecl();
4547 
4548     if (!TagD) // We probably had an error
4549       return nullptr;
4550 
4551     // Note that the above type specs guarantee that the
4552     // type rep is a Decl, whereas in many of the others
4553     // it's a Type.
4554     if (isa<TagDecl>(TagD))
4555       Tag = cast<TagDecl>(TagD);
4556     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4557       Tag = CTD->getTemplatedDecl();
4558   }
4559 
4560   if (Tag) {
4561     handleTagNumbering(Tag, S);
4562     Tag->setFreeStanding();
4563     if (Tag->isInvalidDecl())
4564       return Tag;
4565   }
4566 
4567   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4568     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4569     // or incomplete types shall not be restrict-qualified."
4570     if (TypeQuals & DeclSpec::TQ_restrict)
4571       Diag(DS.getRestrictSpecLoc(),
4572            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4573            << DS.getSourceRange();
4574   }
4575 
4576   if (DS.isInlineSpecified())
4577     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4578         << getLangOpts().CPlusPlus17;
4579 
4580   if (DS.hasConstexprSpecifier()) {
4581     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4582     // and definitions of functions and variables.
4583     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4584     // the declaration of a function or function template
4585     if (Tag)
4586       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4587           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4588           << DS.getConstexprSpecifier();
4589     else
4590       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4591           << DS.getConstexprSpecifier();
4592     // Don't emit warnings after this error.
4593     return TagD;
4594   }
4595 
4596   DiagnoseFunctionSpecifiers(DS);
4597 
4598   if (DS.isFriendSpecified()) {
4599     // If we're dealing with a decl but not a TagDecl, assume that
4600     // whatever routines created it handled the friendship aspect.
4601     if (TagD && !Tag)
4602       return nullptr;
4603     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4604   }
4605 
4606   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4607   bool IsExplicitSpecialization =
4608     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4609   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4610       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4611       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4612     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4613     // nested-name-specifier unless it is an explicit instantiation
4614     // or an explicit specialization.
4615     //
4616     // FIXME: We allow class template partial specializations here too, per the
4617     // obvious intent of DR1819.
4618     //
4619     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4620     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4621         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4622     return nullptr;
4623   }
4624 
4625   // Track whether this decl-specifier declares anything.
4626   bool DeclaresAnything = true;
4627 
4628   // Handle anonymous struct definitions.
4629   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4630     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4631         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4632       if (getLangOpts().CPlusPlus ||
4633           Record->getDeclContext()->isRecord()) {
4634         // If CurContext is a DeclContext that can contain statements,
4635         // RecursiveASTVisitor won't visit the decls that
4636         // BuildAnonymousStructOrUnion() will put into CurContext.
4637         // Also store them here so that they can be part of the
4638         // DeclStmt that gets created in this case.
4639         // FIXME: Also return the IndirectFieldDecls created by
4640         // BuildAnonymousStructOr union, for the same reason?
4641         if (CurContext->isFunctionOrMethod())
4642           AnonRecord = Record;
4643         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4644                                            Context.getPrintingPolicy());
4645       }
4646 
4647       DeclaresAnything = false;
4648     }
4649   }
4650 
4651   // C11 6.7.2.1p2:
4652   //   A struct-declaration that does not declare an anonymous structure or
4653   //   anonymous union shall contain a struct-declarator-list.
4654   //
4655   // This rule also existed in C89 and C99; the grammar for struct-declaration
4656   // did not permit a struct-declaration without a struct-declarator-list.
4657   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4658       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4659     // Check for Microsoft C extension: anonymous struct/union member.
4660     // Handle 2 kinds of anonymous struct/union:
4661     //   struct STRUCT;
4662     //   union UNION;
4663     // and
4664     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4665     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4666     if ((Tag && Tag->getDeclName()) ||
4667         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4668       RecordDecl *Record = nullptr;
4669       if (Tag)
4670         Record = dyn_cast<RecordDecl>(Tag);
4671       else if (const RecordType *RT =
4672                    DS.getRepAsType().get()->getAsStructureType())
4673         Record = RT->getDecl();
4674       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4675         Record = UT->getDecl();
4676 
4677       if (Record && getLangOpts().MicrosoftExt) {
4678         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4679             << Record->isUnion() << DS.getSourceRange();
4680         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4681       }
4682 
4683       DeclaresAnything = false;
4684     }
4685   }
4686 
4687   // Skip all the checks below if we have a type error.
4688   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4689       (TagD && TagD->isInvalidDecl()))
4690     return TagD;
4691 
4692   if (getLangOpts().CPlusPlus &&
4693       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4694     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4695       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4696           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4697         DeclaresAnything = false;
4698 
4699   if (!DS.isMissingDeclaratorOk()) {
4700     // Customize diagnostic for a typedef missing a name.
4701     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4702       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4703           << DS.getSourceRange();
4704     else
4705       DeclaresAnything = false;
4706   }
4707 
4708   if (DS.isModulePrivateSpecified() &&
4709       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4710     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4711       << Tag->getTagKind()
4712       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4713 
4714   ActOnDocumentableDecl(TagD);
4715 
4716   // C 6.7/2:
4717   //   A declaration [...] shall declare at least a declarator [...], a tag,
4718   //   or the members of an enumeration.
4719   // C++ [dcl.dcl]p3:
4720   //   [If there are no declarators], and except for the declaration of an
4721   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4722   //   names into the program, or shall redeclare a name introduced by a
4723   //   previous declaration.
4724   if (!DeclaresAnything) {
4725     // In C, we allow this as a (popular) extension / bug. Don't bother
4726     // producing further diagnostics for redundant qualifiers after this.
4727     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4728     return TagD;
4729   }
4730 
4731   // C++ [dcl.stc]p1:
4732   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4733   //   init-declarator-list of the declaration shall not be empty.
4734   // C++ [dcl.fct.spec]p1:
4735   //   If a cv-qualifier appears in a decl-specifier-seq, the
4736   //   init-declarator-list of the declaration shall not be empty.
4737   //
4738   // Spurious qualifiers here appear to be valid in C.
4739   unsigned DiagID = diag::warn_standalone_specifier;
4740   if (getLangOpts().CPlusPlus)
4741     DiagID = diag::ext_standalone_specifier;
4742 
4743   // Note that a linkage-specification sets a storage class, but
4744   // 'extern "C" struct foo;' is actually valid and not theoretically
4745   // useless.
4746   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4747     if (SCS == DeclSpec::SCS_mutable)
4748       // Since mutable is not a viable storage class specifier in C, there is
4749       // no reason to treat it as an extension. Instead, diagnose as an error.
4750       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4751     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4752       Diag(DS.getStorageClassSpecLoc(), DiagID)
4753         << DeclSpec::getSpecifierName(SCS);
4754   }
4755 
4756   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4757     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4758       << DeclSpec::getSpecifierName(TSCS);
4759   if (DS.getTypeQualifiers()) {
4760     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4761       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4762     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4763       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4764     // Restrict is covered above.
4765     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4766       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4767     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4768       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4769   }
4770 
4771   // Warn about ignored type attributes, for example:
4772   // __attribute__((aligned)) struct A;
4773   // Attributes should be placed after tag to apply to type declaration.
4774   if (!DS.getAttributes().empty()) {
4775     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4776     if (TypeSpecType == DeclSpec::TST_class ||
4777         TypeSpecType == DeclSpec::TST_struct ||
4778         TypeSpecType == DeclSpec::TST_interface ||
4779         TypeSpecType == DeclSpec::TST_union ||
4780         TypeSpecType == DeclSpec::TST_enum) {
4781       for (const ParsedAttr &AL : DS.getAttributes())
4782         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4783             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4784     }
4785   }
4786 
4787   return TagD;
4788 }
4789 
4790 /// We are trying to inject an anonymous member into the given scope;
4791 /// check if there's an existing declaration that can't be overloaded.
4792 ///
4793 /// \return true if this is a forbidden redeclaration
4794 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4795                                          Scope *S,
4796                                          DeclContext *Owner,
4797                                          DeclarationName Name,
4798                                          SourceLocation NameLoc,
4799                                          bool IsUnion) {
4800   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4801                  Sema::ForVisibleRedeclaration);
4802   if (!SemaRef.LookupName(R, S)) return false;
4803 
4804   // Pick a representative declaration.
4805   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4806   assert(PrevDecl && "Expected a non-null Decl");
4807 
4808   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4809     return false;
4810 
4811   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4812     << IsUnion << Name;
4813   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4814 
4815   return true;
4816 }
4817 
4818 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4819 /// anonymous struct or union AnonRecord into the owning context Owner
4820 /// and scope S. This routine will be invoked just after we realize
4821 /// that an unnamed union or struct is actually an anonymous union or
4822 /// struct, e.g.,
4823 ///
4824 /// @code
4825 /// union {
4826 ///   int i;
4827 ///   float f;
4828 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4829 ///    // f into the surrounding scope.x
4830 /// @endcode
4831 ///
4832 /// This routine is recursive, injecting the names of nested anonymous
4833 /// structs/unions into the owning context and scope as well.
4834 static bool
4835 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4836                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4837                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4838   bool Invalid = false;
4839 
4840   // Look every FieldDecl and IndirectFieldDecl with a name.
4841   for (auto *D : AnonRecord->decls()) {
4842     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4843         cast<NamedDecl>(D)->getDeclName()) {
4844       ValueDecl *VD = cast<ValueDecl>(D);
4845       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4846                                        VD->getLocation(),
4847                                        AnonRecord->isUnion())) {
4848         // C++ [class.union]p2:
4849         //   The names of the members of an anonymous union shall be
4850         //   distinct from the names of any other entity in the
4851         //   scope in which the anonymous union is declared.
4852         Invalid = true;
4853       } else {
4854         // C++ [class.union]p2:
4855         //   For the purpose of name lookup, after the anonymous union
4856         //   definition, the members of the anonymous union are
4857         //   considered to have been defined in the scope in which the
4858         //   anonymous union is declared.
4859         unsigned OldChainingSize = Chaining.size();
4860         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4861           Chaining.append(IF->chain_begin(), IF->chain_end());
4862         else
4863           Chaining.push_back(VD);
4864 
4865         assert(Chaining.size() >= 2);
4866         NamedDecl **NamedChain =
4867           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4868         for (unsigned i = 0; i < Chaining.size(); i++)
4869           NamedChain[i] = Chaining[i];
4870 
4871         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4872             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4873             VD->getType(), {NamedChain, Chaining.size()});
4874 
4875         for (const auto *Attr : VD->attrs())
4876           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4877 
4878         IndirectField->setAccess(AS);
4879         IndirectField->setImplicit();
4880         SemaRef.PushOnScopeChains(IndirectField, S);
4881 
4882         // That includes picking up the appropriate access specifier.
4883         if (AS != AS_none) IndirectField->setAccess(AS);
4884 
4885         Chaining.resize(OldChainingSize);
4886       }
4887     }
4888   }
4889 
4890   return Invalid;
4891 }
4892 
4893 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4894 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4895 /// illegal input values are mapped to SC_None.
4896 static StorageClass
4897 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4898   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4899   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4900          "Parser allowed 'typedef' as storage class VarDecl.");
4901   switch (StorageClassSpec) {
4902   case DeclSpec::SCS_unspecified:    return SC_None;
4903   case DeclSpec::SCS_extern:
4904     if (DS.isExternInLinkageSpec())
4905       return SC_None;
4906     return SC_Extern;
4907   case DeclSpec::SCS_static:         return SC_Static;
4908   case DeclSpec::SCS_auto:           return SC_Auto;
4909   case DeclSpec::SCS_register:       return SC_Register;
4910   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4911     // Illegal SCSs map to None: error reporting is up to the caller.
4912   case DeclSpec::SCS_mutable:        // Fall through.
4913   case DeclSpec::SCS_typedef:        return SC_None;
4914   }
4915   llvm_unreachable("unknown storage class specifier");
4916 }
4917 
4918 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4919   assert(Record->hasInClassInitializer());
4920 
4921   for (const auto *I : Record->decls()) {
4922     const auto *FD = dyn_cast<FieldDecl>(I);
4923     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4924       FD = IFD->getAnonField();
4925     if (FD && FD->hasInClassInitializer())
4926       return FD->getLocation();
4927   }
4928 
4929   llvm_unreachable("couldn't find in-class initializer");
4930 }
4931 
4932 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4933                                       SourceLocation DefaultInitLoc) {
4934   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4935     return;
4936 
4937   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4938   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4939 }
4940 
4941 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4942                                       CXXRecordDecl *AnonUnion) {
4943   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4944     return;
4945 
4946   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4947 }
4948 
4949 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4950 /// anonymous structure or union. Anonymous unions are a C++ feature
4951 /// (C++ [class.union]) and a C11 feature; anonymous structures
4952 /// are a C11 feature and GNU C++ extension.
4953 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4954                                         AccessSpecifier AS,
4955                                         RecordDecl *Record,
4956                                         const PrintingPolicy &Policy) {
4957   DeclContext *Owner = Record->getDeclContext();
4958 
4959   // Diagnose whether this anonymous struct/union is an extension.
4960   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4961     Diag(Record->getLocation(), diag::ext_anonymous_union);
4962   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4963     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4964   else if (!Record->isUnion() && !getLangOpts().C11)
4965     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4966 
4967   // C and C++ require different kinds of checks for anonymous
4968   // structs/unions.
4969   bool Invalid = false;
4970   if (getLangOpts().CPlusPlus) {
4971     const char *PrevSpec = nullptr;
4972     if (Record->isUnion()) {
4973       // C++ [class.union]p6:
4974       // C++17 [class.union.anon]p2:
4975       //   Anonymous unions declared in a named namespace or in the
4976       //   global namespace shall be declared static.
4977       unsigned DiagID;
4978       DeclContext *OwnerScope = Owner->getRedeclContext();
4979       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4980           (OwnerScope->isTranslationUnit() ||
4981            (OwnerScope->isNamespace() &&
4982             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4983         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4984           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4985 
4986         // Recover by adding 'static'.
4987         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4988                                PrevSpec, DiagID, Policy);
4989       }
4990       // C++ [class.union]p6:
4991       //   A storage class is not allowed in a declaration of an
4992       //   anonymous union in a class scope.
4993       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4994                isa<RecordDecl>(Owner)) {
4995         Diag(DS.getStorageClassSpecLoc(),
4996              diag::err_anonymous_union_with_storage_spec)
4997           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4998 
4999         // Recover by removing the storage specifier.
5000         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5001                                SourceLocation(),
5002                                PrevSpec, DiagID, Context.getPrintingPolicy());
5003       }
5004     }
5005 
5006     // Ignore const/volatile/restrict qualifiers.
5007     if (DS.getTypeQualifiers()) {
5008       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5009         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5010           << Record->isUnion() << "const"
5011           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5012       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5013         Diag(DS.getVolatileSpecLoc(),
5014              diag::ext_anonymous_struct_union_qualified)
5015           << Record->isUnion() << "volatile"
5016           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5017       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5018         Diag(DS.getRestrictSpecLoc(),
5019              diag::ext_anonymous_struct_union_qualified)
5020           << Record->isUnion() << "restrict"
5021           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5022       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5023         Diag(DS.getAtomicSpecLoc(),
5024              diag::ext_anonymous_struct_union_qualified)
5025           << Record->isUnion() << "_Atomic"
5026           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5027       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5028         Diag(DS.getUnalignedSpecLoc(),
5029              diag::ext_anonymous_struct_union_qualified)
5030           << Record->isUnion() << "__unaligned"
5031           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5032 
5033       DS.ClearTypeQualifiers();
5034     }
5035 
5036     // C++ [class.union]p2:
5037     //   The member-specification of an anonymous union shall only
5038     //   define non-static data members. [Note: nested types and
5039     //   functions cannot be declared within an anonymous union. ]
5040     for (auto *Mem : Record->decls()) {
5041       // Ignore invalid declarations; we already diagnosed them.
5042       if (Mem->isInvalidDecl())
5043         continue;
5044 
5045       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5046         // C++ [class.union]p3:
5047         //   An anonymous union shall not have private or protected
5048         //   members (clause 11).
5049         assert(FD->getAccess() != AS_none);
5050         if (FD->getAccess() != AS_public) {
5051           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5052             << Record->isUnion() << (FD->getAccess() == AS_protected);
5053           Invalid = true;
5054         }
5055 
5056         // C++ [class.union]p1
5057         //   An object of a class with a non-trivial constructor, a non-trivial
5058         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5059         //   assignment operator cannot be a member of a union, nor can an
5060         //   array of such objects.
5061         if (CheckNontrivialField(FD))
5062           Invalid = true;
5063       } else if (Mem->isImplicit()) {
5064         // Any implicit members are fine.
5065       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5066         // This is a type that showed up in an
5067         // elaborated-type-specifier inside the anonymous struct or
5068         // union, but which actually declares a type outside of the
5069         // anonymous struct or union. It's okay.
5070       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5071         if (!MemRecord->isAnonymousStructOrUnion() &&
5072             MemRecord->getDeclName()) {
5073           // Visual C++ allows type definition in anonymous struct or union.
5074           if (getLangOpts().MicrosoftExt)
5075             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5076               << Record->isUnion();
5077           else {
5078             // This is a nested type declaration.
5079             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5080               << Record->isUnion();
5081             Invalid = true;
5082           }
5083         } else {
5084           // This is an anonymous type definition within another anonymous type.
5085           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5086           // not part of standard C++.
5087           Diag(MemRecord->getLocation(),
5088                diag::ext_anonymous_record_with_anonymous_type)
5089             << Record->isUnion();
5090         }
5091       } else if (isa<AccessSpecDecl>(Mem)) {
5092         // Any access specifier is fine.
5093       } else if (isa<StaticAssertDecl>(Mem)) {
5094         // In C++1z, static_assert declarations are also fine.
5095       } else {
5096         // We have something that isn't a non-static data
5097         // member. Complain about it.
5098         unsigned DK = diag::err_anonymous_record_bad_member;
5099         if (isa<TypeDecl>(Mem))
5100           DK = diag::err_anonymous_record_with_type;
5101         else if (isa<FunctionDecl>(Mem))
5102           DK = diag::err_anonymous_record_with_function;
5103         else if (isa<VarDecl>(Mem))
5104           DK = diag::err_anonymous_record_with_static;
5105 
5106         // Visual C++ allows type definition in anonymous struct or union.
5107         if (getLangOpts().MicrosoftExt &&
5108             DK == diag::err_anonymous_record_with_type)
5109           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5110             << Record->isUnion();
5111         else {
5112           Diag(Mem->getLocation(), DK) << Record->isUnion();
5113           Invalid = true;
5114         }
5115       }
5116     }
5117 
5118     // C++11 [class.union]p8 (DR1460):
5119     //   At most one variant member of a union may have a
5120     //   brace-or-equal-initializer.
5121     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5122         Owner->isRecord())
5123       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5124                                 cast<CXXRecordDecl>(Record));
5125   }
5126 
5127   if (!Record->isUnion() && !Owner->isRecord()) {
5128     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5129       << getLangOpts().CPlusPlus;
5130     Invalid = true;
5131   }
5132 
5133   // C++ [dcl.dcl]p3:
5134   //   [If there are no declarators], and except for the declaration of an
5135   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5136   //   names into the program
5137   // C++ [class.mem]p2:
5138   //   each such member-declaration shall either declare at least one member
5139   //   name of the class or declare at least one unnamed bit-field
5140   //
5141   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5142   if (getLangOpts().CPlusPlus && Record->field_empty())
5143     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5144 
5145   // Mock up a declarator.
5146   Declarator Dc(DS, DeclaratorContext::MemberContext);
5147   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5148   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5149 
5150   // Create a declaration for this anonymous struct/union.
5151   NamedDecl *Anon = nullptr;
5152   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5153     Anon = FieldDecl::Create(
5154         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5155         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5156         /*BitWidth=*/nullptr, /*Mutable=*/false,
5157         /*InitStyle=*/ICIS_NoInit);
5158     Anon->setAccess(AS);
5159     ProcessDeclAttributes(S, Anon, Dc);
5160 
5161     if (getLangOpts().CPlusPlus)
5162       FieldCollector->Add(cast<FieldDecl>(Anon));
5163   } else {
5164     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5165     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5166     if (SCSpec == DeclSpec::SCS_mutable) {
5167       // mutable can only appear on non-static class members, so it's always
5168       // an error here
5169       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5170       Invalid = true;
5171       SC = SC_None;
5172     }
5173 
5174     assert(DS.getAttributes().empty() && "No attribute expected");
5175     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5176                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5177                            Context.getTypeDeclType(Record), TInfo, SC);
5178 
5179     // Default-initialize the implicit variable. This initialization will be
5180     // trivial in almost all cases, except if a union member has an in-class
5181     // initializer:
5182     //   union { int n = 0; };
5183     ActOnUninitializedDecl(Anon);
5184   }
5185   Anon->setImplicit();
5186 
5187   // Mark this as an anonymous struct/union type.
5188   Record->setAnonymousStructOrUnion(true);
5189 
5190   // Add the anonymous struct/union object to the current
5191   // context. We'll be referencing this object when we refer to one of
5192   // its members.
5193   Owner->addDecl(Anon);
5194 
5195   // Inject the members of the anonymous struct/union into the owning
5196   // context and into the identifier resolver chain for name lookup
5197   // purposes.
5198   SmallVector<NamedDecl*, 2> Chain;
5199   Chain.push_back(Anon);
5200 
5201   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5202     Invalid = true;
5203 
5204   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5205     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5206       MangleNumberingContext *MCtx;
5207       Decl *ManglingContextDecl;
5208       std::tie(MCtx, ManglingContextDecl) =
5209           getCurrentMangleNumberContext(NewVD->getDeclContext());
5210       if (MCtx) {
5211         Context.setManglingNumber(
5212             NewVD, MCtx->getManglingNumber(
5213                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5214         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5215       }
5216     }
5217   }
5218 
5219   if (Invalid)
5220     Anon->setInvalidDecl();
5221 
5222   return Anon;
5223 }
5224 
5225 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5226 /// Microsoft C anonymous structure.
5227 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5228 /// Example:
5229 ///
5230 /// struct A { int a; };
5231 /// struct B { struct A; int b; };
5232 ///
5233 /// void foo() {
5234 ///   B var;
5235 ///   var.a = 3;
5236 /// }
5237 ///
5238 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5239                                            RecordDecl *Record) {
5240   assert(Record && "expected a record!");
5241 
5242   // Mock up a declarator.
5243   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5244   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5245   assert(TInfo && "couldn't build declarator info for anonymous struct");
5246 
5247   auto *ParentDecl = cast<RecordDecl>(CurContext);
5248   QualType RecTy = Context.getTypeDeclType(Record);
5249 
5250   // Create a declaration for this anonymous struct.
5251   NamedDecl *Anon =
5252       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5253                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5254                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5255                         /*InitStyle=*/ICIS_NoInit);
5256   Anon->setImplicit();
5257 
5258   // Add the anonymous struct object to the current context.
5259   CurContext->addDecl(Anon);
5260 
5261   // Inject the members of the anonymous struct into the current
5262   // context and into the identifier resolver chain for name lookup
5263   // purposes.
5264   SmallVector<NamedDecl*, 2> Chain;
5265   Chain.push_back(Anon);
5266 
5267   RecordDecl *RecordDef = Record->getDefinition();
5268   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5269                                diag::err_field_incomplete_or_sizeless) ||
5270       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5271                                           AS_none, Chain)) {
5272     Anon->setInvalidDecl();
5273     ParentDecl->setInvalidDecl();
5274   }
5275 
5276   return Anon;
5277 }
5278 
5279 /// GetNameForDeclarator - Determine the full declaration name for the
5280 /// given Declarator.
5281 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5282   return GetNameFromUnqualifiedId(D.getName());
5283 }
5284 
5285 /// Retrieves the declaration name from a parsed unqualified-id.
5286 DeclarationNameInfo
5287 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5288   DeclarationNameInfo NameInfo;
5289   NameInfo.setLoc(Name.StartLocation);
5290 
5291   switch (Name.getKind()) {
5292 
5293   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5294   case UnqualifiedIdKind::IK_Identifier:
5295     NameInfo.setName(Name.Identifier);
5296     return NameInfo;
5297 
5298   case UnqualifiedIdKind::IK_DeductionGuideName: {
5299     // C++ [temp.deduct.guide]p3:
5300     //   The simple-template-id shall name a class template specialization.
5301     //   The template-name shall be the same identifier as the template-name
5302     //   of the simple-template-id.
5303     // These together intend to imply that the template-name shall name a
5304     // class template.
5305     // FIXME: template<typename T> struct X {};
5306     //        template<typename T> using Y = X<T>;
5307     //        Y(int) -> Y<int>;
5308     //   satisfies these rules but does not name a class template.
5309     TemplateName TN = Name.TemplateName.get().get();
5310     auto *Template = TN.getAsTemplateDecl();
5311     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5312       Diag(Name.StartLocation,
5313            diag::err_deduction_guide_name_not_class_template)
5314         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5315       if (Template)
5316         Diag(Template->getLocation(), diag::note_template_decl_here);
5317       return DeclarationNameInfo();
5318     }
5319 
5320     NameInfo.setName(
5321         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5322     return NameInfo;
5323   }
5324 
5325   case UnqualifiedIdKind::IK_OperatorFunctionId:
5326     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5327                                            Name.OperatorFunctionId.Operator));
5328     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5329       = Name.OperatorFunctionId.SymbolLocations[0];
5330     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5331       = Name.EndLocation.getRawEncoding();
5332     return NameInfo;
5333 
5334   case UnqualifiedIdKind::IK_LiteralOperatorId:
5335     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5336                                                            Name.Identifier));
5337     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5338     return NameInfo;
5339 
5340   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5341     TypeSourceInfo *TInfo;
5342     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5343     if (Ty.isNull())
5344       return DeclarationNameInfo();
5345     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5346                                                Context.getCanonicalType(Ty)));
5347     NameInfo.setNamedTypeInfo(TInfo);
5348     return NameInfo;
5349   }
5350 
5351   case UnqualifiedIdKind::IK_ConstructorName: {
5352     TypeSourceInfo *TInfo;
5353     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5354     if (Ty.isNull())
5355       return DeclarationNameInfo();
5356     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5357                                               Context.getCanonicalType(Ty)));
5358     NameInfo.setNamedTypeInfo(TInfo);
5359     return NameInfo;
5360   }
5361 
5362   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5363     // In well-formed code, we can only have a constructor
5364     // template-id that refers to the current context, so go there
5365     // to find the actual type being constructed.
5366     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5367     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5368       return DeclarationNameInfo();
5369 
5370     // Determine the type of the class being constructed.
5371     QualType CurClassType = Context.getTypeDeclType(CurClass);
5372 
5373     // FIXME: Check two things: that the template-id names the same type as
5374     // CurClassType, and that the template-id does not occur when the name
5375     // was qualified.
5376 
5377     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5378                                     Context.getCanonicalType(CurClassType)));
5379     // FIXME: should we retrieve TypeSourceInfo?
5380     NameInfo.setNamedTypeInfo(nullptr);
5381     return NameInfo;
5382   }
5383 
5384   case UnqualifiedIdKind::IK_DestructorName: {
5385     TypeSourceInfo *TInfo;
5386     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5387     if (Ty.isNull())
5388       return DeclarationNameInfo();
5389     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5390                                               Context.getCanonicalType(Ty)));
5391     NameInfo.setNamedTypeInfo(TInfo);
5392     return NameInfo;
5393   }
5394 
5395   case UnqualifiedIdKind::IK_TemplateId: {
5396     TemplateName TName = Name.TemplateId->Template.get();
5397     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5398     return Context.getNameForTemplate(TName, TNameLoc);
5399   }
5400 
5401   } // switch (Name.getKind())
5402 
5403   llvm_unreachable("Unknown name kind");
5404 }
5405 
5406 static QualType getCoreType(QualType Ty) {
5407   do {
5408     if (Ty->isPointerType() || Ty->isReferenceType())
5409       Ty = Ty->getPointeeType();
5410     else if (Ty->isArrayType())
5411       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5412     else
5413       return Ty.withoutLocalFastQualifiers();
5414   } while (true);
5415 }
5416 
5417 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5418 /// and Definition have "nearly" matching parameters. This heuristic is
5419 /// used to improve diagnostics in the case where an out-of-line function
5420 /// definition doesn't match any declaration within the class or namespace.
5421 /// Also sets Params to the list of indices to the parameters that differ
5422 /// between the declaration and the definition. If hasSimilarParameters
5423 /// returns true and Params is empty, then all of the parameters match.
5424 static bool hasSimilarParameters(ASTContext &Context,
5425                                      FunctionDecl *Declaration,
5426                                      FunctionDecl *Definition,
5427                                      SmallVectorImpl<unsigned> &Params) {
5428   Params.clear();
5429   if (Declaration->param_size() != Definition->param_size())
5430     return false;
5431   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5432     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5433     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5434 
5435     // The parameter types are identical
5436     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5437       continue;
5438 
5439     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5440     QualType DefParamBaseTy = getCoreType(DefParamTy);
5441     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5442     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5443 
5444     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5445         (DeclTyName && DeclTyName == DefTyName))
5446       Params.push_back(Idx);
5447     else  // The two parameters aren't even close
5448       return false;
5449   }
5450 
5451   return true;
5452 }
5453 
5454 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5455 /// declarator needs to be rebuilt in the current instantiation.
5456 /// Any bits of declarator which appear before the name are valid for
5457 /// consideration here.  That's specifically the type in the decl spec
5458 /// and the base type in any member-pointer chunks.
5459 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5460                                                     DeclarationName Name) {
5461   // The types we specifically need to rebuild are:
5462   //   - typenames, typeofs, and decltypes
5463   //   - types which will become injected class names
5464   // Of course, we also need to rebuild any type referencing such a
5465   // type.  It's safest to just say "dependent", but we call out a
5466   // few cases here.
5467 
5468   DeclSpec &DS = D.getMutableDeclSpec();
5469   switch (DS.getTypeSpecType()) {
5470   case DeclSpec::TST_typename:
5471   case DeclSpec::TST_typeofType:
5472   case DeclSpec::TST_underlyingType:
5473   case DeclSpec::TST_atomic: {
5474     // Grab the type from the parser.
5475     TypeSourceInfo *TSI = nullptr;
5476     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5477     if (T.isNull() || !T->isDependentType()) break;
5478 
5479     // Make sure there's a type source info.  This isn't really much
5480     // of a waste; most dependent types should have type source info
5481     // attached already.
5482     if (!TSI)
5483       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5484 
5485     // Rebuild the type in the current instantiation.
5486     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5487     if (!TSI) return true;
5488 
5489     // Store the new type back in the decl spec.
5490     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5491     DS.UpdateTypeRep(LocType);
5492     break;
5493   }
5494 
5495   case DeclSpec::TST_decltype:
5496   case DeclSpec::TST_typeofExpr: {
5497     Expr *E = DS.getRepAsExpr();
5498     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5499     if (Result.isInvalid()) return true;
5500     DS.UpdateExprRep(Result.get());
5501     break;
5502   }
5503 
5504   default:
5505     // Nothing to do for these decl specs.
5506     break;
5507   }
5508 
5509   // It doesn't matter what order we do this in.
5510   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5511     DeclaratorChunk &Chunk = D.getTypeObject(I);
5512 
5513     // The only type information in the declarator which can come
5514     // before the declaration name is the base type of a member
5515     // pointer.
5516     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5517       continue;
5518 
5519     // Rebuild the scope specifier in-place.
5520     CXXScopeSpec &SS = Chunk.Mem.Scope();
5521     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5522       return true;
5523   }
5524 
5525   return false;
5526 }
5527 
5528 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5529   D.setFunctionDefinitionKind(FDK_Declaration);
5530   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5531 
5532   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5533       Dcl && Dcl->getDeclContext()->isFileContext())
5534     Dcl->setTopLevelDeclInObjCContainer();
5535 
5536   if (getLangOpts().OpenCL)
5537     setCurrentOpenCLExtensionForDecl(Dcl);
5538 
5539   return Dcl;
5540 }
5541 
5542 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5543 ///   If T is the name of a class, then each of the following shall have a
5544 ///   name different from T:
5545 ///     - every static data member of class T;
5546 ///     - every member function of class T
5547 ///     - every member of class T that is itself a type;
5548 /// \returns true if the declaration name violates these rules.
5549 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5550                                    DeclarationNameInfo NameInfo) {
5551   DeclarationName Name = NameInfo.getName();
5552 
5553   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5554   while (Record && Record->isAnonymousStructOrUnion())
5555     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5556   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5557     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5558     return true;
5559   }
5560 
5561   return false;
5562 }
5563 
5564 /// Diagnose a declaration whose declarator-id has the given
5565 /// nested-name-specifier.
5566 ///
5567 /// \param SS The nested-name-specifier of the declarator-id.
5568 ///
5569 /// \param DC The declaration context to which the nested-name-specifier
5570 /// resolves.
5571 ///
5572 /// \param Name The name of the entity being declared.
5573 ///
5574 /// \param Loc The location of the name of the entity being declared.
5575 ///
5576 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5577 /// we're declaring an explicit / partial specialization / instantiation.
5578 ///
5579 /// \returns true if we cannot safely recover from this error, false otherwise.
5580 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5581                                         DeclarationName Name,
5582                                         SourceLocation Loc, bool IsTemplateId) {
5583   DeclContext *Cur = CurContext;
5584   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5585     Cur = Cur->getParent();
5586 
5587   // If the user provided a superfluous scope specifier that refers back to the
5588   // class in which the entity is already declared, diagnose and ignore it.
5589   //
5590   // class X {
5591   //   void X::f();
5592   // };
5593   //
5594   // Note, it was once ill-formed to give redundant qualification in all
5595   // contexts, but that rule was removed by DR482.
5596   if (Cur->Equals(DC)) {
5597     if (Cur->isRecord()) {
5598       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5599                                       : diag::err_member_extra_qualification)
5600         << Name << FixItHint::CreateRemoval(SS.getRange());
5601       SS.clear();
5602     } else {
5603       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5604     }
5605     return false;
5606   }
5607 
5608   // Check whether the qualifying scope encloses the scope of the original
5609   // declaration. For a template-id, we perform the checks in
5610   // CheckTemplateSpecializationScope.
5611   if (!Cur->Encloses(DC) && !IsTemplateId) {
5612     if (Cur->isRecord())
5613       Diag(Loc, diag::err_member_qualification)
5614         << Name << SS.getRange();
5615     else if (isa<TranslationUnitDecl>(DC))
5616       Diag(Loc, diag::err_invalid_declarator_global_scope)
5617         << Name << SS.getRange();
5618     else if (isa<FunctionDecl>(Cur))
5619       Diag(Loc, diag::err_invalid_declarator_in_function)
5620         << Name << SS.getRange();
5621     else if (isa<BlockDecl>(Cur))
5622       Diag(Loc, diag::err_invalid_declarator_in_block)
5623         << Name << SS.getRange();
5624     else
5625       Diag(Loc, diag::err_invalid_declarator_scope)
5626       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5627 
5628     return true;
5629   }
5630 
5631   if (Cur->isRecord()) {
5632     // Cannot qualify members within a class.
5633     Diag(Loc, diag::err_member_qualification)
5634       << Name << SS.getRange();
5635     SS.clear();
5636 
5637     // C++ constructors and destructors with incorrect scopes can break
5638     // our AST invariants by having the wrong underlying types. If
5639     // that's the case, then drop this declaration entirely.
5640     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5641          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5642         !Context.hasSameType(Name.getCXXNameType(),
5643                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5644       return true;
5645 
5646     return false;
5647   }
5648 
5649   // C++11 [dcl.meaning]p1:
5650   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5651   //   not begin with a decltype-specifer"
5652   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5653   while (SpecLoc.getPrefix())
5654     SpecLoc = SpecLoc.getPrefix();
5655   if (dyn_cast_or_null<DecltypeType>(
5656         SpecLoc.getNestedNameSpecifier()->getAsType()))
5657     Diag(Loc, diag::err_decltype_in_declarator)
5658       << SpecLoc.getTypeLoc().getSourceRange();
5659 
5660   return false;
5661 }
5662 
5663 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5664                                   MultiTemplateParamsArg TemplateParamLists) {
5665   // TODO: consider using NameInfo for diagnostic.
5666   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5667   DeclarationName Name = NameInfo.getName();
5668 
5669   // All of these full declarators require an identifier.  If it doesn't have
5670   // one, the ParsedFreeStandingDeclSpec action should be used.
5671   if (D.isDecompositionDeclarator()) {
5672     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5673   } else if (!Name) {
5674     if (!D.isInvalidType())  // Reject this if we think it is valid.
5675       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5676           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5677     return nullptr;
5678   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5679     return nullptr;
5680 
5681   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5682   // we find one that is.
5683   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5684          (S->getFlags() & Scope::TemplateParamScope) != 0)
5685     S = S->getParent();
5686 
5687   DeclContext *DC = CurContext;
5688   if (D.getCXXScopeSpec().isInvalid())
5689     D.setInvalidType();
5690   else if (D.getCXXScopeSpec().isSet()) {
5691     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5692                                         UPPC_DeclarationQualifier))
5693       return nullptr;
5694 
5695     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5696     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5697     if (!DC || isa<EnumDecl>(DC)) {
5698       // If we could not compute the declaration context, it's because the
5699       // declaration context is dependent but does not refer to a class,
5700       // class template, or class template partial specialization. Complain
5701       // and return early, to avoid the coming semantic disaster.
5702       Diag(D.getIdentifierLoc(),
5703            diag::err_template_qualified_declarator_no_match)
5704         << D.getCXXScopeSpec().getScopeRep()
5705         << D.getCXXScopeSpec().getRange();
5706       return nullptr;
5707     }
5708     bool IsDependentContext = DC->isDependentContext();
5709 
5710     if (!IsDependentContext &&
5711         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5712       return nullptr;
5713 
5714     // If a class is incomplete, do not parse entities inside it.
5715     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5716       Diag(D.getIdentifierLoc(),
5717            diag::err_member_def_undefined_record)
5718         << Name << DC << D.getCXXScopeSpec().getRange();
5719       return nullptr;
5720     }
5721     if (!D.getDeclSpec().isFriendSpecified()) {
5722       if (diagnoseQualifiedDeclaration(
5723               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5724               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5725         if (DC->isRecord())
5726           return nullptr;
5727 
5728         D.setInvalidType();
5729       }
5730     }
5731 
5732     // Check whether we need to rebuild the type of the given
5733     // declaration in the current instantiation.
5734     if (EnteringContext && IsDependentContext &&
5735         TemplateParamLists.size() != 0) {
5736       ContextRAII SavedContext(*this, DC);
5737       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5738         D.setInvalidType();
5739     }
5740   }
5741 
5742   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5743   QualType R = TInfo->getType();
5744 
5745   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5746                                       UPPC_DeclarationType))
5747     D.setInvalidType();
5748 
5749   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5750                         forRedeclarationInCurContext());
5751 
5752   // See if this is a redefinition of a variable in the same scope.
5753   if (!D.getCXXScopeSpec().isSet()) {
5754     bool IsLinkageLookup = false;
5755     bool CreateBuiltins = false;
5756 
5757     // If the declaration we're planning to build will be a function
5758     // or object with linkage, then look for another declaration with
5759     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5760     //
5761     // If the declaration we're planning to build will be declared with
5762     // external linkage in the translation unit, create any builtin with
5763     // the same name.
5764     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5765       /* Do nothing*/;
5766     else if (CurContext->isFunctionOrMethod() &&
5767              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5768               R->isFunctionType())) {
5769       IsLinkageLookup = true;
5770       CreateBuiltins =
5771           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5772     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5773                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5774       CreateBuiltins = true;
5775 
5776     if (IsLinkageLookup) {
5777       Previous.clear(LookupRedeclarationWithLinkage);
5778       Previous.setRedeclarationKind(ForExternalRedeclaration);
5779     }
5780 
5781     LookupName(Previous, S, CreateBuiltins);
5782   } else { // Something like "int foo::x;"
5783     LookupQualifiedName(Previous, DC);
5784 
5785     // C++ [dcl.meaning]p1:
5786     //   When the declarator-id is qualified, the declaration shall refer to a
5787     //  previously declared member of the class or namespace to which the
5788     //  qualifier refers (or, in the case of a namespace, of an element of the
5789     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5790     //  thereof; [...]
5791     //
5792     // Note that we already checked the context above, and that we do not have
5793     // enough information to make sure that Previous contains the declaration
5794     // we want to match. For example, given:
5795     //
5796     //   class X {
5797     //     void f();
5798     //     void f(float);
5799     //   };
5800     //
5801     //   void X::f(int) { } // ill-formed
5802     //
5803     // In this case, Previous will point to the overload set
5804     // containing the two f's declared in X, but neither of them
5805     // matches.
5806 
5807     // C++ [dcl.meaning]p1:
5808     //   [...] the member shall not merely have been introduced by a
5809     //   using-declaration in the scope of the class or namespace nominated by
5810     //   the nested-name-specifier of the declarator-id.
5811     RemoveUsingDecls(Previous);
5812   }
5813 
5814   if (Previous.isSingleResult() &&
5815       Previous.getFoundDecl()->isTemplateParameter()) {
5816     // Maybe we will complain about the shadowed template parameter.
5817     if (!D.isInvalidType())
5818       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5819                                       Previous.getFoundDecl());
5820 
5821     // Just pretend that we didn't see the previous declaration.
5822     Previous.clear();
5823   }
5824 
5825   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5826     // Forget that the previous declaration is the injected-class-name.
5827     Previous.clear();
5828 
5829   // In C++, the previous declaration we find might be a tag type
5830   // (class or enum). In this case, the new declaration will hide the
5831   // tag type. Note that this applies to functions, function templates, and
5832   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5833   if (Previous.isSingleTagDecl() &&
5834       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5835       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5836     Previous.clear();
5837 
5838   // Check that there are no default arguments other than in the parameters
5839   // of a function declaration (C++ only).
5840   if (getLangOpts().CPlusPlus)
5841     CheckExtraCXXDefaultArguments(D);
5842 
5843   NamedDecl *New;
5844 
5845   bool AddToScope = true;
5846   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5847     if (TemplateParamLists.size()) {
5848       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5849       return nullptr;
5850     }
5851 
5852     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5853   } else if (R->isFunctionType()) {
5854     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5855                                   TemplateParamLists,
5856                                   AddToScope);
5857   } else {
5858     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5859                                   AddToScope);
5860   }
5861 
5862   if (!New)
5863     return nullptr;
5864 
5865   // If this has an identifier and is not a function template specialization,
5866   // add it to the scope stack.
5867   if (New->getDeclName() && AddToScope)
5868     PushOnScopeChains(New, S);
5869 
5870   if (isInOpenMPDeclareTargetContext())
5871     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5872 
5873   return New;
5874 }
5875 
5876 /// Helper method to turn variable array types into constant array
5877 /// types in certain situations which would otherwise be errors (for
5878 /// GCC compatibility).
5879 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5880                                                     ASTContext &Context,
5881                                                     bool &SizeIsNegative,
5882                                                     llvm::APSInt &Oversized) {
5883   // This method tries to turn a variable array into a constant
5884   // array even when the size isn't an ICE.  This is necessary
5885   // for compatibility with code that depends on gcc's buggy
5886   // constant expression folding, like struct {char x[(int)(char*)2];}
5887   SizeIsNegative = false;
5888   Oversized = 0;
5889 
5890   if (T->isDependentType())
5891     return QualType();
5892 
5893   QualifierCollector Qs;
5894   const Type *Ty = Qs.strip(T);
5895 
5896   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5897     QualType Pointee = PTy->getPointeeType();
5898     QualType FixedType =
5899         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5900                                             Oversized);
5901     if (FixedType.isNull()) return FixedType;
5902     FixedType = Context.getPointerType(FixedType);
5903     return Qs.apply(Context, FixedType);
5904   }
5905   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5906     QualType Inner = PTy->getInnerType();
5907     QualType FixedType =
5908         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5909                                             Oversized);
5910     if (FixedType.isNull()) return FixedType;
5911     FixedType = Context.getParenType(FixedType);
5912     return Qs.apply(Context, FixedType);
5913   }
5914 
5915   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5916   if (!VLATy)
5917     return QualType();
5918   // FIXME: We should probably handle this case
5919   if (VLATy->getElementType()->isVariablyModifiedType())
5920     return QualType();
5921 
5922   Expr::EvalResult Result;
5923   if (!VLATy->getSizeExpr() ||
5924       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5925     return QualType();
5926 
5927   llvm::APSInt Res = Result.Val.getInt();
5928 
5929   // Check whether the array size is negative.
5930   if (Res.isSigned() && Res.isNegative()) {
5931     SizeIsNegative = true;
5932     return QualType();
5933   }
5934 
5935   // Check whether the array is too large to be addressed.
5936   unsigned ActiveSizeBits
5937     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5938                                               Res);
5939   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5940     Oversized = Res;
5941     return QualType();
5942   }
5943 
5944   return Context.getConstantArrayType(
5945       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5946 }
5947 
5948 static void
5949 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5950   SrcTL = SrcTL.getUnqualifiedLoc();
5951   DstTL = DstTL.getUnqualifiedLoc();
5952   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5953     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5954     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5955                                       DstPTL.getPointeeLoc());
5956     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5957     return;
5958   }
5959   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5960     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5961     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5962                                       DstPTL.getInnerLoc());
5963     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5964     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5965     return;
5966   }
5967   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5968   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5969   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5970   TypeLoc DstElemTL = DstATL.getElementLoc();
5971   DstElemTL.initializeFullCopy(SrcElemTL);
5972   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5973   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5974   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5975 }
5976 
5977 /// Helper method to turn variable array types into constant array
5978 /// types in certain situations which would otherwise be errors (for
5979 /// GCC compatibility).
5980 static TypeSourceInfo*
5981 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5982                                               ASTContext &Context,
5983                                               bool &SizeIsNegative,
5984                                               llvm::APSInt &Oversized) {
5985   QualType FixedTy
5986     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5987                                           SizeIsNegative, Oversized);
5988   if (FixedTy.isNull())
5989     return nullptr;
5990   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5991   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5992                                     FixedTInfo->getTypeLoc());
5993   return FixedTInfo;
5994 }
5995 
5996 /// Register the given locally-scoped extern "C" declaration so
5997 /// that it can be found later for redeclarations. We include any extern "C"
5998 /// declaration that is not visible in the translation unit here, not just
5999 /// function-scope declarations.
6000 void
6001 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6002   if (!getLangOpts().CPlusPlus &&
6003       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6004     // Don't need to track declarations in the TU in C.
6005     return;
6006 
6007   // Note that we have a locally-scoped external with this name.
6008   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6009 }
6010 
6011 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6012   // FIXME: We can have multiple results via __attribute__((overloadable)).
6013   auto Result = Context.getExternCContextDecl()->lookup(Name);
6014   return Result.empty() ? nullptr : *Result.begin();
6015 }
6016 
6017 /// Diagnose function specifiers on a declaration of an identifier that
6018 /// does not identify a function.
6019 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6020   // FIXME: We should probably indicate the identifier in question to avoid
6021   // confusion for constructs like "virtual int a(), b;"
6022   if (DS.isVirtualSpecified())
6023     Diag(DS.getVirtualSpecLoc(),
6024          diag::err_virtual_non_function);
6025 
6026   if (DS.hasExplicitSpecifier())
6027     Diag(DS.getExplicitSpecLoc(),
6028          diag::err_explicit_non_function);
6029 
6030   if (DS.isNoreturnSpecified())
6031     Diag(DS.getNoreturnSpecLoc(),
6032          diag::err_noreturn_non_function);
6033 }
6034 
6035 NamedDecl*
6036 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6037                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6038   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6039   if (D.getCXXScopeSpec().isSet()) {
6040     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6041       << D.getCXXScopeSpec().getRange();
6042     D.setInvalidType();
6043     // Pretend we didn't see the scope specifier.
6044     DC = CurContext;
6045     Previous.clear();
6046   }
6047 
6048   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6049 
6050   if (D.getDeclSpec().isInlineSpecified())
6051     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6052         << getLangOpts().CPlusPlus17;
6053   if (D.getDeclSpec().hasConstexprSpecifier())
6054     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6055         << 1 << D.getDeclSpec().getConstexprSpecifier();
6056 
6057   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6058     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6059       Diag(D.getName().StartLocation,
6060            diag::err_deduction_guide_invalid_specifier)
6061           << "typedef";
6062     else
6063       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6064           << D.getName().getSourceRange();
6065     return nullptr;
6066   }
6067 
6068   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6069   if (!NewTD) return nullptr;
6070 
6071   // Handle attributes prior to checking for duplicates in MergeVarDecl
6072   ProcessDeclAttributes(S, NewTD, D);
6073 
6074   CheckTypedefForVariablyModifiedType(S, NewTD);
6075 
6076   bool Redeclaration = D.isRedeclaration();
6077   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6078   D.setRedeclaration(Redeclaration);
6079   return ND;
6080 }
6081 
6082 void
6083 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6084   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6085   // then it shall have block scope.
6086   // Note that variably modified types must be fixed before merging the decl so
6087   // that redeclarations will match.
6088   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6089   QualType T = TInfo->getType();
6090   if (T->isVariablyModifiedType()) {
6091     setFunctionHasBranchProtectedScope();
6092 
6093     if (S->getFnParent() == nullptr) {
6094       bool SizeIsNegative;
6095       llvm::APSInt Oversized;
6096       TypeSourceInfo *FixedTInfo =
6097         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6098                                                       SizeIsNegative,
6099                                                       Oversized);
6100       if (FixedTInfo) {
6101         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6102         NewTD->setTypeSourceInfo(FixedTInfo);
6103       } else {
6104         if (SizeIsNegative)
6105           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6106         else if (T->isVariableArrayType())
6107           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6108         else if (Oversized.getBoolValue())
6109           Diag(NewTD->getLocation(), diag::err_array_too_large)
6110             << Oversized.toString(10);
6111         else
6112           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6113         NewTD->setInvalidDecl();
6114       }
6115     }
6116   }
6117 }
6118 
6119 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6120 /// declares a typedef-name, either using the 'typedef' type specifier or via
6121 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6122 NamedDecl*
6123 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6124                            LookupResult &Previous, bool &Redeclaration) {
6125 
6126   // Find the shadowed declaration before filtering for scope.
6127   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6128 
6129   // Merge the decl with the existing one if appropriate. If the decl is
6130   // in an outer scope, it isn't the same thing.
6131   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6132                        /*AllowInlineNamespace*/false);
6133   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6134   if (!Previous.empty()) {
6135     Redeclaration = true;
6136     MergeTypedefNameDecl(S, NewTD, Previous);
6137   } else {
6138     inferGslPointerAttribute(NewTD);
6139   }
6140 
6141   if (ShadowedDecl && !Redeclaration)
6142     CheckShadow(NewTD, ShadowedDecl, Previous);
6143 
6144   // If this is the C FILE type, notify the AST context.
6145   if (IdentifierInfo *II = NewTD->getIdentifier())
6146     if (!NewTD->isInvalidDecl() &&
6147         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6148       if (II->isStr("FILE"))
6149         Context.setFILEDecl(NewTD);
6150       else if (II->isStr("jmp_buf"))
6151         Context.setjmp_bufDecl(NewTD);
6152       else if (II->isStr("sigjmp_buf"))
6153         Context.setsigjmp_bufDecl(NewTD);
6154       else if (II->isStr("ucontext_t"))
6155         Context.setucontext_tDecl(NewTD);
6156     }
6157 
6158   return NewTD;
6159 }
6160 
6161 /// Determines whether the given declaration is an out-of-scope
6162 /// previous declaration.
6163 ///
6164 /// This routine should be invoked when name lookup has found a
6165 /// previous declaration (PrevDecl) that is not in the scope where a
6166 /// new declaration by the same name is being introduced. If the new
6167 /// declaration occurs in a local scope, previous declarations with
6168 /// linkage may still be considered previous declarations (C99
6169 /// 6.2.2p4-5, C++ [basic.link]p6).
6170 ///
6171 /// \param PrevDecl the previous declaration found by name
6172 /// lookup
6173 ///
6174 /// \param DC the context in which the new declaration is being
6175 /// declared.
6176 ///
6177 /// \returns true if PrevDecl is an out-of-scope previous declaration
6178 /// for a new delcaration with the same name.
6179 static bool
6180 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6181                                 ASTContext &Context) {
6182   if (!PrevDecl)
6183     return false;
6184 
6185   if (!PrevDecl->hasLinkage())
6186     return false;
6187 
6188   if (Context.getLangOpts().CPlusPlus) {
6189     // C++ [basic.link]p6:
6190     //   If there is a visible declaration of an entity with linkage
6191     //   having the same name and type, ignoring entities declared
6192     //   outside the innermost enclosing namespace scope, the block
6193     //   scope declaration declares that same entity and receives the
6194     //   linkage of the previous declaration.
6195     DeclContext *OuterContext = DC->getRedeclContext();
6196     if (!OuterContext->isFunctionOrMethod())
6197       // This rule only applies to block-scope declarations.
6198       return false;
6199 
6200     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6201     if (PrevOuterContext->isRecord())
6202       // We found a member function: ignore it.
6203       return false;
6204 
6205     // Find the innermost enclosing namespace for the new and
6206     // previous declarations.
6207     OuterContext = OuterContext->getEnclosingNamespaceContext();
6208     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6209 
6210     // The previous declaration is in a different namespace, so it
6211     // isn't the same function.
6212     if (!OuterContext->Equals(PrevOuterContext))
6213       return false;
6214   }
6215 
6216   return true;
6217 }
6218 
6219 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6220   CXXScopeSpec &SS = D.getCXXScopeSpec();
6221   if (!SS.isSet()) return;
6222   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6223 }
6224 
6225 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6226   QualType type = decl->getType();
6227   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6228   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6229     // Various kinds of declaration aren't allowed to be __autoreleasing.
6230     unsigned kind = -1U;
6231     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6232       if (var->hasAttr<BlocksAttr>())
6233         kind = 0; // __block
6234       else if (!var->hasLocalStorage())
6235         kind = 1; // global
6236     } else if (isa<ObjCIvarDecl>(decl)) {
6237       kind = 3; // ivar
6238     } else if (isa<FieldDecl>(decl)) {
6239       kind = 2; // field
6240     }
6241 
6242     if (kind != -1U) {
6243       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6244         << kind;
6245     }
6246   } else if (lifetime == Qualifiers::OCL_None) {
6247     // Try to infer lifetime.
6248     if (!type->isObjCLifetimeType())
6249       return false;
6250 
6251     lifetime = type->getObjCARCImplicitLifetime();
6252     type = Context.getLifetimeQualifiedType(type, lifetime);
6253     decl->setType(type);
6254   }
6255 
6256   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6257     // Thread-local variables cannot have lifetime.
6258     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6259         var->getTLSKind()) {
6260       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6261         << var->getType();
6262       return true;
6263     }
6264   }
6265 
6266   return false;
6267 }
6268 
6269 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6270   if (Decl->getType().hasAddressSpace())
6271     return;
6272   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6273     QualType Type = Var->getType();
6274     if (Type->isSamplerT() || Type->isVoidType())
6275       return;
6276     LangAS ImplAS = LangAS::opencl_private;
6277     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6278         Var->hasGlobalStorage())
6279       ImplAS = LangAS::opencl_global;
6280     // If the original type from a decayed type is an array type and that array
6281     // type has no address space yet, deduce it now.
6282     if (auto DT = dyn_cast<DecayedType>(Type)) {
6283       auto OrigTy = DT->getOriginalType();
6284       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6285         // Add the address space to the original array type and then propagate
6286         // that to the element type through `getAsArrayType`.
6287         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6288         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6289         // Re-generate the decayed type.
6290         Type = Context.getDecayedType(OrigTy);
6291       }
6292     }
6293     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6294     // Apply any qualifiers (including address space) from the array type to
6295     // the element type. This implements C99 6.7.3p8: "If the specification of
6296     // an array type includes any type qualifiers, the element type is so
6297     // qualified, not the array type."
6298     if (Type->isArrayType())
6299       Type = QualType(Context.getAsArrayType(Type), 0);
6300     Decl->setType(Type);
6301   }
6302 }
6303 
6304 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6305   // Ensure that an auto decl is deduced otherwise the checks below might cache
6306   // the wrong linkage.
6307   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6308 
6309   // 'weak' only applies to declarations with external linkage.
6310   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6311     if (!ND.isExternallyVisible()) {
6312       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6313       ND.dropAttr<WeakAttr>();
6314     }
6315   }
6316   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6317     if (ND.isExternallyVisible()) {
6318       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6319       ND.dropAttr<WeakRefAttr>();
6320       ND.dropAttr<AliasAttr>();
6321     }
6322   }
6323 
6324   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6325     if (VD->hasInit()) {
6326       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6327         assert(VD->isThisDeclarationADefinition() &&
6328                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6329         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6330         VD->dropAttr<AliasAttr>();
6331       }
6332     }
6333   }
6334 
6335   // 'selectany' only applies to externally visible variable declarations.
6336   // It does not apply to functions.
6337   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6338     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6339       S.Diag(Attr->getLocation(),
6340              diag::err_attribute_selectany_non_extern_data);
6341       ND.dropAttr<SelectAnyAttr>();
6342     }
6343   }
6344 
6345   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6346     auto *VD = dyn_cast<VarDecl>(&ND);
6347     bool IsAnonymousNS = false;
6348     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6349     if (VD) {
6350       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6351       while (NS && !IsAnonymousNS) {
6352         IsAnonymousNS = NS->isAnonymousNamespace();
6353         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6354       }
6355     }
6356     // dll attributes require external linkage. Static locals may have external
6357     // linkage but still cannot be explicitly imported or exported.
6358     // In Microsoft mode, a variable defined in anonymous namespace must have
6359     // external linkage in order to be exported.
6360     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6361     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6362         (!AnonNSInMicrosoftMode &&
6363          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6364       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6365         << &ND << Attr;
6366       ND.setInvalidDecl();
6367     }
6368   }
6369 
6370   // Virtual functions cannot be marked as 'notail'.
6371   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6372     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6373       if (MD->isVirtual()) {
6374         S.Diag(ND.getLocation(),
6375                diag::err_invalid_attribute_on_virtual_function)
6376             << Attr;
6377         ND.dropAttr<NotTailCalledAttr>();
6378       }
6379 
6380   // Check the attributes on the function type, if any.
6381   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6382     // Don't declare this variable in the second operand of the for-statement;
6383     // GCC miscompiles that by ending its lifetime before evaluating the
6384     // third operand. See gcc.gnu.org/PR86769.
6385     AttributedTypeLoc ATL;
6386     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6387          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6388          TL = ATL.getModifiedLoc()) {
6389       // The [[lifetimebound]] attribute can be applied to the implicit object
6390       // parameter of a non-static member function (other than a ctor or dtor)
6391       // by applying it to the function type.
6392       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6393         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6394         if (!MD || MD->isStatic()) {
6395           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6396               << !MD << A->getRange();
6397         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6398           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6399               << isa<CXXDestructorDecl>(MD) << A->getRange();
6400         }
6401       }
6402     }
6403   }
6404 }
6405 
6406 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6407                                            NamedDecl *NewDecl,
6408                                            bool IsSpecialization,
6409                                            bool IsDefinition) {
6410   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6411     return;
6412 
6413   bool IsTemplate = false;
6414   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6415     OldDecl = OldTD->getTemplatedDecl();
6416     IsTemplate = true;
6417     if (!IsSpecialization)
6418       IsDefinition = false;
6419   }
6420   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6421     NewDecl = NewTD->getTemplatedDecl();
6422     IsTemplate = true;
6423   }
6424 
6425   if (!OldDecl || !NewDecl)
6426     return;
6427 
6428   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6429   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6430   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6431   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6432 
6433   // dllimport and dllexport are inheritable attributes so we have to exclude
6434   // inherited attribute instances.
6435   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6436                     (NewExportAttr && !NewExportAttr->isInherited());
6437 
6438   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6439   // the only exception being explicit specializations.
6440   // Implicitly generated declarations are also excluded for now because there
6441   // is no other way to switch these to use dllimport or dllexport.
6442   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6443 
6444   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6445     // Allow with a warning for free functions and global variables.
6446     bool JustWarn = false;
6447     if (!OldDecl->isCXXClassMember()) {
6448       auto *VD = dyn_cast<VarDecl>(OldDecl);
6449       if (VD && !VD->getDescribedVarTemplate())
6450         JustWarn = true;
6451       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6452       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6453         JustWarn = true;
6454     }
6455 
6456     // We cannot change a declaration that's been used because IR has already
6457     // been emitted. Dllimported functions will still work though (modulo
6458     // address equality) as they can use the thunk.
6459     if (OldDecl->isUsed())
6460       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6461         JustWarn = false;
6462 
6463     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6464                                : diag::err_attribute_dll_redeclaration;
6465     S.Diag(NewDecl->getLocation(), DiagID)
6466         << NewDecl
6467         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6468     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6469     if (!JustWarn) {
6470       NewDecl->setInvalidDecl();
6471       return;
6472     }
6473   }
6474 
6475   // A redeclaration is not allowed to drop a dllimport attribute, the only
6476   // exceptions being inline function definitions (except for function
6477   // templates), local extern declarations, qualified friend declarations or
6478   // special MSVC extension: in the last case, the declaration is treated as if
6479   // it were marked dllexport.
6480   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6481   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6482   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6483     // Ignore static data because out-of-line definitions are diagnosed
6484     // separately.
6485     IsStaticDataMember = VD->isStaticDataMember();
6486     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6487                    VarDecl::DeclarationOnly;
6488   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6489     IsInline = FD->isInlined();
6490     IsQualifiedFriend = FD->getQualifier() &&
6491                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6492   }
6493 
6494   if (OldImportAttr && !HasNewAttr &&
6495       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6496       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6497     if (IsMicrosoft && IsDefinition) {
6498       S.Diag(NewDecl->getLocation(),
6499              diag::warn_redeclaration_without_import_attribute)
6500           << NewDecl;
6501       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6502       NewDecl->dropAttr<DLLImportAttr>();
6503       NewDecl->addAttr(
6504           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6505     } else {
6506       S.Diag(NewDecl->getLocation(),
6507              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6508           << NewDecl << OldImportAttr;
6509       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6510       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6511       OldDecl->dropAttr<DLLImportAttr>();
6512       NewDecl->dropAttr<DLLImportAttr>();
6513     }
6514   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6515     // In MinGW, seeing a function declared inline drops the dllimport
6516     // attribute.
6517     OldDecl->dropAttr<DLLImportAttr>();
6518     NewDecl->dropAttr<DLLImportAttr>();
6519     S.Diag(NewDecl->getLocation(),
6520            diag::warn_dllimport_dropped_from_inline_function)
6521         << NewDecl << OldImportAttr;
6522   }
6523 
6524   // A specialization of a class template member function is processed here
6525   // since it's a redeclaration. If the parent class is dllexport, the
6526   // specialization inherits that attribute. This doesn't happen automatically
6527   // since the parent class isn't instantiated until later.
6528   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6529     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6530         !NewImportAttr && !NewExportAttr) {
6531       if (const DLLExportAttr *ParentExportAttr =
6532               MD->getParent()->getAttr<DLLExportAttr>()) {
6533         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6534         NewAttr->setInherited(true);
6535         NewDecl->addAttr(NewAttr);
6536       }
6537     }
6538   }
6539 }
6540 
6541 /// Given that we are within the definition of the given function,
6542 /// will that definition behave like C99's 'inline', where the
6543 /// definition is discarded except for optimization purposes?
6544 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6545   // Try to avoid calling GetGVALinkageForFunction.
6546 
6547   // All cases of this require the 'inline' keyword.
6548   if (!FD->isInlined()) return false;
6549 
6550   // This is only possible in C++ with the gnu_inline attribute.
6551   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6552     return false;
6553 
6554   // Okay, go ahead and call the relatively-more-expensive function.
6555   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6556 }
6557 
6558 /// Determine whether a variable is extern "C" prior to attaching
6559 /// an initializer. We can't just call isExternC() here, because that
6560 /// will also compute and cache whether the declaration is externally
6561 /// visible, which might change when we attach the initializer.
6562 ///
6563 /// This can only be used if the declaration is known to not be a
6564 /// redeclaration of an internal linkage declaration.
6565 ///
6566 /// For instance:
6567 ///
6568 ///   auto x = []{};
6569 ///
6570 /// Attaching the initializer here makes this declaration not externally
6571 /// visible, because its type has internal linkage.
6572 ///
6573 /// FIXME: This is a hack.
6574 template<typename T>
6575 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6576   if (S.getLangOpts().CPlusPlus) {
6577     // In C++, the overloadable attribute negates the effects of extern "C".
6578     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6579       return false;
6580 
6581     // So do CUDA's host/device attributes.
6582     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6583                                  D->template hasAttr<CUDAHostAttr>()))
6584       return false;
6585   }
6586   return D->isExternC();
6587 }
6588 
6589 static bool shouldConsiderLinkage(const VarDecl *VD) {
6590   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6591   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6592       isa<OMPDeclareMapperDecl>(DC))
6593     return VD->hasExternalStorage();
6594   if (DC->isFileContext())
6595     return true;
6596   if (DC->isRecord())
6597     return false;
6598   if (isa<RequiresExprBodyDecl>(DC))
6599     return false;
6600   llvm_unreachable("Unexpected context");
6601 }
6602 
6603 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6604   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6605   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6606       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6607     return true;
6608   if (DC->isRecord())
6609     return false;
6610   llvm_unreachable("Unexpected context");
6611 }
6612 
6613 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6614                           ParsedAttr::Kind Kind) {
6615   // Check decl attributes on the DeclSpec.
6616   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6617     return true;
6618 
6619   // Walk the declarator structure, checking decl attributes that were in a type
6620   // position to the decl itself.
6621   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6622     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6623       return true;
6624   }
6625 
6626   // Finally, check attributes on the decl itself.
6627   return PD.getAttributes().hasAttribute(Kind);
6628 }
6629 
6630 /// Adjust the \c DeclContext for a function or variable that might be a
6631 /// function-local external declaration.
6632 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6633   if (!DC->isFunctionOrMethod())
6634     return false;
6635 
6636   // If this is a local extern function or variable declared within a function
6637   // template, don't add it into the enclosing namespace scope until it is
6638   // instantiated; it might have a dependent type right now.
6639   if (DC->isDependentContext())
6640     return true;
6641 
6642   // C++11 [basic.link]p7:
6643   //   When a block scope declaration of an entity with linkage is not found to
6644   //   refer to some other declaration, then that entity is a member of the
6645   //   innermost enclosing namespace.
6646   //
6647   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6648   // semantically-enclosing namespace, not a lexically-enclosing one.
6649   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6650     DC = DC->getParent();
6651   return true;
6652 }
6653 
6654 /// Returns true if given declaration has external C language linkage.
6655 static bool isDeclExternC(const Decl *D) {
6656   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6657     return FD->isExternC();
6658   if (const auto *VD = dyn_cast<VarDecl>(D))
6659     return VD->isExternC();
6660 
6661   llvm_unreachable("Unknown type of decl!");
6662 }
6663 /// Returns true if there hasn't been any invalid type diagnosed.
6664 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6665                                 DeclContext *DC, QualType R) {
6666   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6667   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6668   // argument.
6669   if (R->isImageType() || R->isPipeType()) {
6670     Se.Diag(D.getIdentifierLoc(),
6671             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6672         << R;
6673     D.setInvalidType();
6674     return false;
6675   }
6676 
6677   // OpenCL v1.2 s6.9.r:
6678   // The event type cannot be used to declare a program scope variable.
6679   // OpenCL v2.0 s6.9.q:
6680   // The clk_event_t and reserve_id_t types cannot be declared in program
6681   // scope.
6682   if (NULL == S->getParent()) {
6683     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6684       Se.Diag(D.getIdentifierLoc(),
6685               diag::err_invalid_type_for_program_scope_var)
6686           << R;
6687       D.setInvalidType();
6688       return false;
6689     }
6690   }
6691 
6692   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6693   QualType NR = R;
6694   while (NR->isPointerType()) {
6695     if (NR->isFunctionPointerType()) {
6696       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6697       D.setInvalidType();
6698       return false;
6699     }
6700     NR = NR->getPointeeType();
6701   }
6702 
6703   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6704     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6705     // half array type (unless the cl_khr_fp16 extension is enabled).
6706     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6707       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6708       D.setInvalidType();
6709       return false;
6710     }
6711   }
6712 
6713   // OpenCL v1.2 s6.9.r:
6714   // The event type cannot be used with the __local, __constant and __global
6715   // address space qualifiers.
6716   if (R->isEventT()) {
6717     if (R.getAddressSpace() != LangAS::opencl_private) {
6718       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6719       D.setInvalidType();
6720       return false;
6721     }
6722   }
6723 
6724   // C++ for OpenCL does not allow the thread_local storage qualifier.
6725   // OpenCL C does not support thread_local either, and
6726   // also reject all other thread storage class specifiers.
6727   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6728   if (TSC != TSCS_unspecified) {
6729     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6730     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6731             diag::err_opencl_unknown_type_specifier)
6732         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6733         << DeclSpec::getSpecifierName(TSC) << 1;
6734     D.setInvalidType();
6735     return false;
6736   }
6737 
6738   if (R->isSamplerT()) {
6739     // OpenCL v1.2 s6.9.b p4:
6740     // The sampler type cannot be used with the __local and __global address
6741     // space qualifiers.
6742     if (R.getAddressSpace() == LangAS::opencl_local ||
6743         R.getAddressSpace() == LangAS::opencl_global) {
6744       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6745       D.setInvalidType();
6746     }
6747 
6748     // OpenCL v1.2 s6.12.14.1:
6749     // A global sampler must be declared with either the constant address
6750     // space qualifier or with the const qualifier.
6751     if (DC->isTranslationUnit() &&
6752         !(R.getAddressSpace() == LangAS::opencl_constant ||
6753           R.isConstQualified())) {
6754       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6755       D.setInvalidType();
6756     }
6757     if (D.isInvalidType())
6758       return false;
6759   }
6760   return true;
6761 }
6762 
6763 NamedDecl *Sema::ActOnVariableDeclarator(
6764     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6765     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6766     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6767   QualType R = TInfo->getType();
6768   DeclarationName Name = GetNameForDeclarator(D).getName();
6769 
6770   IdentifierInfo *II = Name.getAsIdentifierInfo();
6771 
6772   if (D.isDecompositionDeclarator()) {
6773     // Take the name of the first declarator as our name for diagnostic
6774     // purposes.
6775     auto &Decomp = D.getDecompositionDeclarator();
6776     if (!Decomp.bindings().empty()) {
6777       II = Decomp.bindings()[0].Name;
6778       Name = II;
6779     }
6780   } else if (!II) {
6781     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6782     return nullptr;
6783   }
6784 
6785 
6786   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6787   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6788 
6789   // dllimport globals without explicit storage class are treated as extern. We
6790   // have to change the storage class this early to get the right DeclContext.
6791   if (SC == SC_None && !DC->isRecord() &&
6792       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6793       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6794     SC = SC_Extern;
6795 
6796   DeclContext *OriginalDC = DC;
6797   bool IsLocalExternDecl = SC == SC_Extern &&
6798                            adjustContextForLocalExternDecl(DC);
6799 
6800   if (SCSpec == DeclSpec::SCS_mutable) {
6801     // mutable can only appear on non-static class members, so it's always
6802     // an error here
6803     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6804     D.setInvalidType();
6805     SC = SC_None;
6806   }
6807 
6808   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6809       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6810                               D.getDeclSpec().getStorageClassSpecLoc())) {
6811     // In C++11, the 'register' storage class specifier is deprecated.
6812     // Suppress the warning in system macros, it's used in macros in some
6813     // popular C system headers, such as in glibc's htonl() macro.
6814     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6815          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6816                                    : diag::warn_deprecated_register)
6817       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6818   }
6819 
6820   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6821 
6822   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6823     // C99 6.9p2: The storage-class specifiers auto and register shall not
6824     // appear in the declaration specifiers in an external declaration.
6825     // Global Register+Asm is a GNU extension we support.
6826     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6827       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6828       D.setInvalidType();
6829     }
6830   }
6831 
6832   bool IsMemberSpecialization = false;
6833   bool IsVariableTemplateSpecialization = false;
6834   bool IsPartialSpecialization = false;
6835   bool IsVariableTemplate = false;
6836   VarDecl *NewVD = nullptr;
6837   VarTemplateDecl *NewTemplate = nullptr;
6838   TemplateParameterList *TemplateParams = nullptr;
6839   if (!getLangOpts().CPlusPlus) {
6840     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6841                             II, R, TInfo, SC);
6842 
6843     if (R->getContainedDeducedType())
6844       ParsingInitForAutoVars.insert(NewVD);
6845 
6846     if (D.isInvalidType())
6847       NewVD->setInvalidDecl();
6848 
6849     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6850         NewVD->hasLocalStorage())
6851       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6852                             NTCUC_AutoVar, NTCUK_Destruct);
6853   } else {
6854     bool Invalid = false;
6855 
6856     if (DC->isRecord() && !CurContext->isRecord()) {
6857       // This is an out-of-line definition of a static data member.
6858       switch (SC) {
6859       case SC_None:
6860         break;
6861       case SC_Static:
6862         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6863              diag::err_static_out_of_line)
6864           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6865         break;
6866       case SC_Auto:
6867       case SC_Register:
6868       case SC_Extern:
6869         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6870         // to names of variables declared in a block or to function parameters.
6871         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6872         // of class members
6873 
6874         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6875              diag::err_storage_class_for_static_member)
6876           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6877         break;
6878       case SC_PrivateExtern:
6879         llvm_unreachable("C storage class in c++!");
6880       }
6881     }
6882 
6883     if (SC == SC_Static && CurContext->isRecord()) {
6884       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6885         // C++ [class.static.data]p2:
6886         //   A static data member shall not be a direct member of an unnamed
6887         //   or local class
6888         // FIXME: or of a (possibly indirectly) nested class thereof.
6889         if (RD->isLocalClass()) {
6890           Diag(D.getIdentifierLoc(),
6891                diag::err_static_data_member_not_allowed_in_local_class)
6892             << Name << RD->getDeclName() << RD->getTagKind();
6893         } else if (!RD->getDeclName()) {
6894           Diag(D.getIdentifierLoc(),
6895                diag::err_static_data_member_not_allowed_in_anon_struct)
6896             << Name << RD->getTagKind();
6897           Invalid = true;
6898         } else if (RD->isUnion()) {
6899           // C++98 [class.union]p1: If a union contains a static data member,
6900           // the program is ill-formed. C++11 drops this restriction.
6901           Diag(D.getIdentifierLoc(),
6902                getLangOpts().CPlusPlus11
6903                  ? diag::warn_cxx98_compat_static_data_member_in_union
6904                  : diag::ext_static_data_member_in_union) << Name;
6905         }
6906       }
6907     }
6908 
6909     // Match up the template parameter lists with the scope specifier, then
6910     // determine whether we have a template or a template specialization.
6911     bool InvalidScope = false;
6912     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6913         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6914         D.getCXXScopeSpec(),
6915         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6916             ? D.getName().TemplateId
6917             : nullptr,
6918         TemplateParamLists,
6919         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6920     Invalid |= InvalidScope;
6921 
6922     if (TemplateParams) {
6923       if (!TemplateParams->size() &&
6924           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6925         // There is an extraneous 'template<>' for this variable. Complain
6926         // about it, but allow the declaration of the variable.
6927         Diag(TemplateParams->getTemplateLoc(),
6928              diag::err_template_variable_noparams)
6929           << II
6930           << SourceRange(TemplateParams->getTemplateLoc(),
6931                          TemplateParams->getRAngleLoc());
6932         TemplateParams = nullptr;
6933       } else {
6934         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6935           // This is an explicit specialization or a partial specialization.
6936           // FIXME: Check that we can declare a specialization here.
6937           IsVariableTemplateSpecialization = true;
6938           IsPartialSpecialization = TemplateParams->size() > 0;
6939         } else { // if (TemplateParams->size() > 0)
6940           // This is a template declaration.
6941           IsVariableTemplate = true;
6942 
6943           // Check that we can declare a template here.
6944           if (CheckTemplateDeclScope(S, TemplateParams))
6945             return nullptr;
6946 
6947           // Only C++1y supports variable templates (N3651).
6948           Diag(D.getIdentifierLoc(),
6949                getLangOpts().CPlusPlus14
6950                    ? diag::warn_cxx11_compat_variable_template
6951                    : diag::ext_variable_template);
6952         }
6953       }
6954     } else {
6955       assert((Invalid ||
6956               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6957              "should have a 'template<>' for this decl");
6958     }
6959 
6960     if (IsVariableTemplateSpecialization) {
6961       SourceLocation TemplateKWLoc =
6962           TemplateParamLists.size() > 0
6963               ? TemplateParamLists[0]->getTemplateLoc()
6964               : SourceLocation();
6965       DeclResult Res = ActOnVarTemplateSpecialization(
6966           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6967           IsPartialSpecialization);
6968       if (Res.isInvalid())
6969         return nullptr;
6970       NewVD = cast<VarDecl>(Res.get());
6971       AddToScope = false;
6972     } else if (D.isDecompositionDeclarator()) {
6973       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6974                                         D.getIdentifierLoc(), R, TInfo, SC,
6975                                         Bindings);
6976     } else
6977       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6978                               D.getIdentifierLoc(), II, R, TInfo, SC);
6979 
6980     // If this is supposed to be a variable template, create it as such.
6981     if (IsVariableTemplate) {
6982       NewTemplate =
6983           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6984                                   TemplateParams, NewVD);
6985       NewVD->setDescribedVarTemplate(NewTemplate);
6986     }
6987 
6988     // If this decl has an auto type in need of deduction, make a note of the
6989     // Decl so we can diagnose uses of it in its own initializer.
6990     if (R->getContainedDeducedType())
6991       ParsingInitForAutoVars.insert(NewVD);
6992 
6993     if (D.isInvalidType() || Invalid) {
6994       NewVD->setInvalidDecl();
6995       if (NewTemplate)
6996         NewTemplate->setInvalidDecl();
6997     }
6998 
6999     SetNestedNameSpecifier(*this, NewVD, D);
7000 
7001     // If we have any template parameter lists that don't directly belong to
7002     // the variable (matching the scope specifier), store them.
7003     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7004     if (TemplateParamLists.size() > VDTemplateParamLists)
7005       NewVD->setTemplateParameterListsInfo(
7006           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7007   }
7008 
7009   if (D.getDeclSpec().isInlineSpecified()) {
7010     if (!getLangOpts().CPlusPlus) {
7011       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7012           << 0;
7013     } else if (CurContext->isFunctionOrMethod()) {
7014       // 'inline' is not allowed on block scope variable declaration.
7015       Diag(D.getDeclSpec().getInlineSpecLoc(),
7016            diag::err_inline_declaration_block_scope) << Name
7017         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7018     } else {
7019       Diag(D.getDeclSpec().getInlineSpecLoc(),
7020            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7021                                      : diag::ext_inline_variable);
7022       NewVD->setInlineSpecified();
7023     }
7024   }
7025 
7026   // Set the lexical context. If the declarator has a C++ scope specifier, the
7027   // lexical context will be different from the semantic context.
7028   NewVD->setLexicalDeclContext(CurContext);
7029   if (NewTemplate)
7030     NewTemplate->setLexicalDeclContext(CurContext);
7031 
7032   if (IsLocalExternDecl) {
7033     if (D.isDecompositionDeclarator())
7034       for (auto *B : Bindings)
7035         B->setLocalExternDecl();
7036     else
7037       NewVD->setLocalExternDecl();
7038   }
7039 
7040   bool EmitTLSUnsupportedError = false;
7041   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7042     // C++11 [dcl.stc]p4:
7043     //   When thread_local is applied to a variable of block scope the
7044     //   storage-class-specifier static is implied if it does not appear
7045     //   explicitly.
7046     // Core issue: 'static' is not implied if the variable is declared
7047     //   'extern'.
7048     if (NewVD->hasLocalStorage() &&
7049         (SCSpec != DeclSpec::SCS_unspecified ||
7050          TSCS != DeclSpec::TSCS_thread_local ||
7051          !DC->isFunctionOrMethod()))
7052       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7053            diag::err_thread_non_global)
7054         << DeclSpec::getSpecifierName(TSCS);
7055     else if (!Context.getTargetInfo().isTLSSupported()) {
7056       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7057         // Postpone error emission until we've collected attributes required to
7058         // figure out whether it's a host or device variable and whether the
7059         // error should be ignored.
7060         EmitTLSUnsupportedError = true;
7061         // We still need to mark the variable as TLS so it shows up in AST with
7062         // proper storage class for other tools to use even if we're not going
7063         // to emit any code for it.
7064         NewVD->setTSCSpec(TSCS);
7065       } else
7066         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7067              diag::err_thread_unsupported);
7068     } else
7069       NewVD->setTSCSpec(TSCS);
7070   }
7071 
7072   switch (D.getDeclSpec().getConstexprSpecifier()) {
7073   case CSK_unspecified:
7074     break;
7075 
7076   case CSK_consteval:
7077     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7078         diag::err_constexpr_wrong_decl_kind)
7079       << D.getDeclSpec().getConstexprSpecifier();
7080     LLVM_FALLTHROUGH;
7081 
7082   case CSK_constexpr:
7083     NewVD->setConstexpr(true);
7084     // C++1z [dcl.spec.constexpr]p1:
7085     //   A static data member declared with the constexpr specifier is
7086     //   implicitly an inline variable.
7087     if (NewVD->isStaticDataMember() &&
7088         (getLangOpts().CPlusPlus17 ||
7089          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7090       NewVD->setImplicitlyInline();
7091     break;
7092 
7093   case CSK_constinit:
7094     if (!NewVD->hasGlobalStorage())
7095       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7096            diag::err_constinit_local_variable);
7097     else
7098       NewVD->addAttr(ConstInitAttr::Create(
7099           Context, D.getDeclSpec().getConstexprSpecLoc(),
7100           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7101     break;
7102   }
7103 
7104   // C99 6.7.4p3
7105   //   An inline definition of a function with external linkage shall
7106   //   not contain a definition of a modifiable object with static or
7107   //   thread storage duration...
7108   // We only apply this when the function is required to be defined
7109   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7110   // that a local variable with thread storage duration still has to
7111   // be marked 'static'.  Also note that it's possible to get these
7112   // semantics in C++ using __attribute__((gnu_inline)).
7113   if (SC == SC_Static && S->getFnParent() != nullptr &&
7114       !NewVD->getType().isConstQualified()) {
7115     FunctionDecl *CurFD = getCurFunctionDecl();
7116     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7117       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7118            diag::warn_static_local_in_extern_inline);
7119       MaybeSuggestAddingStaticToDecl(CurFD);
7120     }
7121   }
7122 
7123   if (D.getDeclSpec().isModulePrivateSpecified()) {
7124     if (IsVariableTemplateSpecialization)
7125       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7126           << (IsPartialSpecialization ? 1 : 0)
7127           << FixItHint::CreateRemoval(
7128                  D.getDeclSpec().getModulePrivateSpecLoc());
7129     else if (IsMemberSpecialization)
7130       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7131         << 2
7132         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7133     else if (NewVD->hasLocalStorage())
7134       Diag(NewVD->getLocation(), diag::err_module_private_local)
7135         << 0 << NewVD->getDeclName()
7136         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7137         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7138     else {
7139       NewVD->setModulePrivate();
7140       if (NewTemplate)
7141         NewTemplate->setModulePrivate();
7142       for (auto *B : Bindings)
7143         B->setModulePrivate();
7144     }
7145   }
7146 
7147   if (getLangOpts().OpenCL) {
7148 
7149     deduceOpenCLAddressSpace(NewVD);
7150 
7151     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7152   }
7153 
7154   // Handle attributes prior to checking for duplicates in MergeVarDecl
7155   ProcessDeclAttributes(S, NewVD, D);
7156 
7157   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7158     if (EmitTLSUnsupportedError &&
7159         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7160          (getLangOpts().OpenMPIsDevice &&
7161           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7162       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7163            diag::err_thread_unsupported);
7164     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7165     // storage [duration]."
7166     if (SC == SC_None && S->getFnParent() != nullptr &&
7167         (NewVD->hasAttr<CUDASharedAttr>() ||
7168          NewVD->hasAttr<CUDAConstantAttr>())) {
7169       NewVD->setStorageClass(SC_Static);
7170     }
7171   }
7172 
7173   // Ensure that dllimport globals without explicit storage class are treated as
7174   // extern. The storage class is set above using parsed attributes. Now we can
7175   // check the VarDecl itself.
7176   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7177          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7178          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7179 
7180   // In auto-retain/release, infer strong retension for variables of
7181   // retainable type.
7182   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7183     NewVD->setInvalidDecl();
7184 
7185   // Handle GNU asm-label extension (encoded as an attribute).
7186   if (Expr *E = (Expr*)D.getAsmLabel()) {
7187     // The parser guarantees this is a string.
7188     StringLiteral *SE = cast<StringLiteral>(E);
7189     StringRef Label = SE->getString();
7190     if (S->getFnParent() != nullptr) {
7191       switch (SC) {
7192       case SC_None:
7193       case SC_Auto:
7194         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7195         break;
7196       case SC_Register:
7197         // Local Named register
7198         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7199             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7200           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7201         break;
7202       case SC_Static:
7203       case SC_Extern:
7204       case SC_PrivateExtern:
7205         break;
7206       }
7207     } else if (SC == SC_Register) {
7208       // Global Named register
7209       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7210         const auto &TI = Context.getTargetInfo();
7211         bool HasSizeMismatch;
7212 
7213         if (!TI.isValidGCCRegisterName(Label))
7214           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7215         else if (!TI.validateGlobalRegisterVariable(Label,
7216                                                     Context.getTypeSize(R),
7217                                                     HasSizeMismatch))
7218           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7219         else if (HasSizeMismatch)
7220           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7221       }
7222 
7223       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7224         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7225         NewVD->setInvalidDecl(true);
7226       }
7227     }
7228 
7229     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7230                                         /*IsLiteralLabel=*/true,
7231                                         SE->getStrTokenLoc(0)));
7232   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7233     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7234       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7235     if (I != ExtnameUndeclaredIdentifiers.end()) {
7236       if (isDeclExternC(NewVD)) {
7237         NewVD->addAttr(I->second);
7238         ExtnameUndeclaredIdentifiers.erase(I);
7239       } else
7240         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7241             << /*Variable*/1 << NewVD;
7242     }
7243   }
7244 
7245   // Find the shadowed declaration before filtering for scope.
7246   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7247                                 ? getShadowedDeclaration(NewVD, Previous)
7248                                 : nullptr;
7249 
7250   // Don't consider existing declarations that are in a different
7251   // scope and are out-of-semantic-context declarations (if the new
7252   // declaration has linkage).
7253   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7254                        D.getCXXScopeSpec().isNotEmpty() ||
7255                        IsMemberSpecialization ||
7256                        IsVariableTemplateSpecialization);
7257 
7258   // Check whether the previous declaration is in the same block scope. This
7259   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7260   if (getLangOpts().CPlusPlus &&
7261       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7262     NewVD->setPreviousDeclInSameBlockScope(
7263         Previous.isSingleResult() && !Previous.isShadowed() &&
7264         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7265 
7266   if (!getLangOpts().CPlusPlus) {
7267     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7268   } else {
7269     // If this is an explicit specialization of a static data member, check it.
7270     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7271         CheckMemberSpecialization(NewVD, Previous))
7272       NewVD->setInvalidDecl();
7273 
7274     // Merge the decl with the existing one if appropriate.
7275     if (!Previous.empty()) {
7276       if (Previous.isSingleResult() &&
7277           isa<FieldDecl>(Previous.getFoundDecl()) &&
7278           D.getCXXScopeSpec().isSet()) {
7279         // The user tried to define a non-static data member
7280         // out-of-line (C++ [dcl.meaning]p1).
7281         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7282           << D.getCXXScopeSpec().getRange();
7283         Previous.clear();
7284         NewVD->setInvalidDecl();
7285       }
7286     } else if (D.getCXXScopeSpec().isSet()) {
7287       // No previous declaration in the qualifying scope.
7288       Diag(D.getIdentifierLoc(), diag::err_no_member)
7289         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7290         << D.getCXXScopeSpec().getRange();
7291       NewVD->setInvalidDecl();
7292     }
7293 
7294     if (!IsVariableTemplateSpecialization)
7295       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7296 
7297     if (NewTemplate) {
7298       VarTemplateDecl *PrevVarTemplate =
7299           NewVD->getPreviousDecl()
7300               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7301               : nullptr;
7302 
7303       // Check the template parameter list of this declaration, possibly
7304       // merging in the template parameter list from the previous variable
7305       // template declaration.
7306       if (CheckTemplateParameterList(
7307               TemplateParams,
7308               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7309                               : nullptr,
7310               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7311                DC->isDependentContext())
7312                   ? TPC_ClassTemplateMember
7313                   : TPC_VarTemplate))
7314         NewVD->setInvalidDecl();
7315 
7316       // If we are providing an explicit specialization of a static variable
7317       // template, make a note of that.
7318       if (PrevVarTemplate &&
7319           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7320         PrevVarTemplate->setMemberSpecialization();
7321     }
7322   }
7323 
7324   // Diagnose shadowed variables iff this isn't a redeclaration.
7325   if (ShadowedDecl && !D.isRedeclaration())
7326     CheckShadow(NewVD, ShadowedDecl, Previous);
7327 
7328   ProcessPragmaWeak(S, NewVD);
7329 
7330   // If this is the first declaration of an extern C variable, update
7331   // the map of such variables.
7332   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7333       isIncompleteDeclExternC(*this, NewVD))
7334     RegisterLocallyScopedExternCDecl(NewVD, S);
7335 
7336   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7337     MangleNumberingContext *MCtx;
7338     Decl *ManglingContextDecl;
7339     std::tie(MCtx, ManglingContextDecl) =
7340         getCurrentMangleNumberContext(NewVD->getDeclContext());
7341     if (MCtx) {
7342       Context.setManglingNumber(
7343           NewVD, MCtx->getManglingNumber(
7344                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7345       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7346     }
7347   }
7348 
7349   // Special handling of variable named 'main'.
7350   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7351       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7352       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7353 
7354     // C++ [basic.start.main]p3
7355     // A program that declares a variable main at global scope is ill-formed.
7356     if (getLangOpts().CPlusPlus)
7357       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7358 
7359     // In C, and external-linkage variable named main results in undefined
7360     // behavior.
7361     else if (NewVD->hasExternalFormalLinkage())
7362       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7363   }
7364 
7365   if (D.isRedeclaration() && !Previous.empty()) {
7366     NamedDecl *Prev = Previous.getRepresentativeDecl();
7367     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7368                                    D.isFunctionDefinition());
7369   }
7370 
7371   if (NewTemplate) {
7372     if (NewVD->isInvalidDecl())
7373       NewTemplate->setInvalidDecl();
7374     ActOnDocumentableDecl(NewTemplate);
7375     return NewTemplate;
7376   }
7377 
7378   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7379     CompleteMemberSpecialization(NewVD, Previous);
7380 
7381   return NewVD;
7382 }
7383 
7384 /// Enum describing the %select options in diag::warn_decl_shadow.
7385 enum ShadowedDeclKind {
7386   SDK_Local,
7387   SDK_Global,
7388   SDK_StaticMember,
7389   SDK_Field,
7390   SDK_Typedef,
7391   SDK_Using
7392 };
7393 
7394 /// Determine what kind of declaration we're shadowing.
7395 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7396                                                 const DeclContext *OldDC) {
7397   if (isa<TypeAliasDecl>(ShadowedDecl))
7398     return SDK_Using;
7399   else if (isa<TypedefDecl>(ShadowedDecl))
7400     return SDK_Typedef;
7401   else if (isa<RecordDecl>(OldDC))
7402     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7403 
7404   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7405 }
7406 
7407 /// Return the location of the capture if the given lambda captures the given
7408 /// variable \p VD, or an invalid source location otherwise.
7409 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7410                                          const VarDecl *VD) {
7411   for (const Capture &Capture : LSI->Captures) {
7412     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7413       return Capture.getLocation();
7414   }
7415   return SourceLocation();
7416 }
7417 
7418 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7419                                      const LookupResult &R) {
7420   // Only diagnose if we're shadowing an unambiguous field or variable.
7421   if (R.getResultKind() != LookupResult::Found)
7422     return false;
7423 
7424   // Return false if warning is ignored.
7425   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7426 }
7427 
7428 /// Return the declaration shadowed by the given variable \p D, or null
7429 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7430 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7431                                         const LookupResult &R) {
7432   if (!shouldWarnIfShadowedDecl(Diags, R))
7433     return nullptr;
7434 
7435   // Don't diagnose declarations at file scope.
7436   if (D->hasGlobalStorage())
7437     return nullptr;
7438 
7439   NamedDecl *ShadowedDecl = R.getFoundDecl();
7440   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7441              ? ShadowedDecl
7442              : nullptr;
7443 }
7444 
7445 /// Return the declaration shadowed by the given typedef \p D, or null
7446 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7447 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7448                                         const LookupResult &R) {
7449   // Don't warn if typedef declaration is part of a class
7450   if (D->getDeclContext()->isRecord())
7451     return nullptr;
7452 
7453   if (!shouldWarnIfShadowedDecl(Diags, R))
7454     return nullptr;
7455 
7456   NamedDecl *ShadowedDecl = R.getFoundDecl();
7457   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7458 }
7459 
7460 /// Diagnose variable or built-in function shadowing.  Implements
7461 /// -Wshadow.
7462 ///
7463 /// This method is called whenever a VarDecl is added to a "useful"
7464 /// scope.
7465 ///
7466 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7467 /// \param R the lookup of the name
7468 ///
7469 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7470                        const LookupResult &R) {
7471   DeclContext *NewDC = D->getDeclContext();
7472 
7473   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7474     // Fields are not shadowed by variables in C++ static methods.
7475     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7476       if (MD->isStatic())
7477         return;
7478 
7479     // Fields shadowed by constructor parameters are a special case. Usually
7480     // the constructor initializes the field with the parameter.
7481     if (isa<CXXConstructorDecl>(NewDC))
7482       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7483         // Remember that this was shadowed so we can either warn about its
7484         // modification or its existence depending on warning settings.
7485         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7486         return;
7487       }
7488   }
7489 
7490   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7491     if (shadowedVar->isExternC()) {
7492       // For shadowing external vars, make sure that we point to the global
7493       // declaration, not a locally scoped extern declaration.
7494       for (auto I : shadowedVar->redecls())
7495         if (I->isFileVarDecl()) {
7496           ShadowedDecl = I;
7497           break;
7498         }
7499     }
7500 
7501   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7502 
7503   unsigned WarningDiag = diag::warn_decl_shadow;
7504   SourceLocation CaptureLoc;
7505   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7506       isa<CXXMethodDecl>(NewDC)) {
7507     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7508       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7509         if (RD->getLambdaCaptureDefault() == LCD_None) {
7510           // Try to avoid warnings for lambdas with an explicit capture list.
7511           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7512           // Warn only when the lambda captures the shadowed decl explicitly.
7513           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7514           if (CaptureLoc.isInvalid())
7515             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7516         } else {
7517           // Remember that this was shadowed so we can avoid the warning if the
7518           // shadowed decl isn't captured and the warning settings allow it.
7519           cast<LambdaScopeInfo>(getCurFunction())
7520               ->ShadowingDecls.push_back(
7521                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7522           return;
7523         }
7524       }
7525 
7526       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7527         // A variable can't shadow a local variable in an enclosing scope, if
7528         // they are separated by a non-capturing declaration context.
7529         for (DeclContext *ParentDC = NewDC;
7530              ParentDC && !ParentDC->Equals(OldDC);
7531              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7532           // Only block literals, captured statements, and lambda expressions
7533           // can capture; other scopes don't.
7534           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7535               !isLambdaCallOperator(ParentDC)) {
7536             return;
7537           }
7538         }
7539       }
7540     }
7541   }
7542 
7543   // Only warn about certain kinds of shadowing for class members.
7544   if (NewDC && NewDC->isRecord()) {
7545     // In particular, don't warn about shadowing non-class members.
7546     if (!OldDC->isRecord())
7547       return;
7548 
7549     // TODO: should we warn about static data members shadowing
7550     // static data members from base classes?
7551 
7552     // TODO: don't diagnose for inaccessible shadowed members.
7553     // This is hard to do perfectly because we might friend the
7554     // shadowing context, but that's just a false negative.
7555   }
7556 
7557 
7558   DeclarationName Name = R.getLookupName();
7559 
7560   // Emit warning and note.
7561   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7562     return;
7563   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7564   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7565   if (!CaptureLoc.isInvalid())
7566     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7567         << Name << /*explicitly*/ 1;
7568   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7569 }
7570 
7571 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7572 /// when these variables are captured by the lambda.
7573 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7574   for (const auto &Shadow : LSI->ShadowingDecls) {
7575     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7576     // Try to avoid the warning when the shadowed decl isn't captured.
7577     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7578     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7579     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7580                                        ? diag::warn_decl_shadow_uncaptured_local
7581                                        : diag::warn_decl_shadow)
7582         << Shadow.VD->getDeclName()
7583         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7584     if (!CaptureLoc.isInvalid())
7585       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7586           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7587     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7588   }
7589 }
7590 
7591 /// Check -Wshadow without the advantage of a previous lookup.
7592 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7593   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7594     return;
7595 
7596   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7597                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7598   LookupName(R, S);
7599   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7600     CheckShadow(D, ShadowedDecl, R);
7601 }
7602 
7603 /// Check if 'E', which is an expression that is about to be modified, refers
7604 /// to a constructor parameter that shadows a field.
7605 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7606   // Quickly ignore expressions that can't be shadowing ctor parameters.
7607   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7608     return;
7609   E = E->IgnoreParenImpCasts();
7610   auto *DRE = dyn_cast<DeclRefExpr>(E);
7611   if (!DRE)
7612     return;
7613   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7614   auto I = ShadowingDecls.find(D);
7615   if (I == ShadowingDecls.end())
7616     return;
7617   const NamedDecl *ShadowedDecl = I->second;
7618   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7619   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7620   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7621   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7622 
7623   // Avoid issuing multiple warnings about the same decl.
7624   ShadowingDecls.erase(I);
7625 }
7626 
7627 /// Check for conflict between this global or extern "C" declaration and
7628 /// previous global or extern "C" declarations. This is only used in C++.
7629 template<typename T>
7630 static bool checkGlobalOrExternCConflict(
7631     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7632   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7633   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7634 
7635   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7636     // The common case: this global doesn't conflict with any extern "C"
7637     // declaration.
7638     return false;
7639   }
7640 
7641   if (Prev) {
7642     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7643       // Both the old and new declarations have C language linkage. This is a
7644       // redeclaration.
7645       Previous.clear();
7646       Previous.addDecl(Prev);
7647       return true;
7648     }
7649 
7650     // This is a global, non-extern "C" declaration, and there is a previous
7651     // non-global extern "C" declaration. Diagnose if this is a variable
7652     // declaration.
7653     if (!isa<VarDecl>(ND))
7654       return false;
7655   } else {
7656     // The declaration is extern "C". Check for any declaration in the
7657     // translation unit which might conflict.
7658     if (IsGlobal) {
7659       // We have already performed the lookup into the translation unit.
7660       IsGlobal = false;
7661       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7662            I != E; ++I) {
7663         if (isa<VarDecl>(*I)) {
7664           Prev = *I;
7665           break;
7666         }
7667       }
7668     } else {
7669       DeclContext::lookup_result R =
7670           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7671       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7672            I != E; ++I) {
7673         if (isa<VarDecl>(*I)) {
7674           Prev = *I;
7675           break;
7676         }
7677         // FIXME: If we have any other entity with this name in global scope,
7678         // the declaration is ill-formed, but that is a defect: it breaks the
7679         // 'stat' hack, for instance. Only variables can have mangled name
7680         // clashes with extern "C" declarations, so only they deserve a
7681         // diagnostic.
7682       }
7683     }
7684 
7685     if (!Prev)
7686       return false;
7687   }
7688 
7689   // Use the first declaration's location to ensure we point at something which
7690   // is lexically inside an extern "C" linkage-spec.
7691   assert(Prev && "should have found a previous declaration to diagnose");
7692   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7693     Prev = FD->getFirstDecl();
7694   else
7695     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7696 
7697   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7698     << IsGlobal << ND;
7699   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7700     << IsGlobal;
7701   return false;
7702 }
7703 
7704 /// Apply special rules for handling extern "C" declarations. Returns \c true
7705 /// if we have found that this is a redeclaration of some prior entity.
7706 ///
7707 /// Per C++ [dcl.link]p6:
7708 ///   Two declarations [for a function or variable] with C language linkage
7709 ///   with the same name that appear in different scopes refer to the same
7710 ///   [entity]. An entity with C language linkage shall not be declared with
7711 ///   the same name as an entity in global scope.
7712 template<typename T>
7713 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7714                                                   LookupResult &Previous) {
7715   if (!S.getLangOpts().CPlusPlus) {
7716     // In C, when declaring a global variable, look for a corresponding 'extern'
7717     // variable declared in function scope. We don't need this in C++, because
7718     // we find local extern decls in the surrounding file-scope DeclContext.
7719     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7720       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7721         Previous.clear();
7722         Previous.addDecl(Prev);
7723         return true;
7724       }
7725     }
7726     return false;
7727   }
7728 
7729   // A declaration in the translation unit can conflict with an extern "C"
7730   // declaration.
7731   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7732     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7733 
7734   // An extern "C" declaration can conflict with a declaration in the
7735   // translation unit or can be a redeclaration of an extern "C" declaration
7736   // in another scope.
7737   if (isIncompleteDeclExternC(S,ND))
7738     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7739 
7740   // Neither global nor extern "C": nothing to do.
7741   return false;
7742 }
7743 
7744 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7745   // If the decl is already known invalid, don't check it.
7746   if (NewVD->isInvalidDecl())
7747     return;
7748 
7749   QualType T = NewVD->getType();
7750 
7751   // Defer checking an 'auto' type until its initializer is attached.
7752   if (T->isUndeducedType())
7753     return;
7754 
7755   if (NewVD->hasAttrs())
7756     CheckAlignasUnderalignment(NewVD);
7757 
7758   if (T->isObjCObjectType()) {
7759     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7760       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7761     T = Context.getObjCObjectPointerType(T);
7762     NewVD->setType(T);
7763   }
7764 
7765   // Emit an error if an address space was applied to decl with local storage.
7766   // This includes arrays of objects with address space qualifiers, but not
7767   // automatic variables that point to other address spaces.
7768   // ISO/IEC TR 18037 S5.1.2
7769   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7770       T.getAddressSpace() != LangAS::Default) {
7771     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7772     NewVD->setInvalidDecl();
7773     return;
7774   }
7775 
7776   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7777   // scope.
7778   if (getLangOpts().OpenCLVersion == 120 &&
7779       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7780       NewVD->isStaticLocal()) {
7781     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7782     NewVD->setInvalidDecl();
7783     return;
7784   }
7785 
7786   if (getLangOpts().OpenCL) {
7787     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7788     if (NewVD->hasAttr<BlocksAttr>()) {
7789       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7790       return;
7791     }
7792 
7793     if (T->isBlockPointerType()) {
7794       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7795       // can't use 'extern' storage class.
7796       if (!T.isConstQualified()) {
7797         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7798             << 0 /*const*/;
7799         NewVD->setInvalidDecl();
7800         return;
7801       }
7802       if (NewVD->hasExternalStorage()) {
7803         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7804         NewVD->setInvalidDecl();
7805         return;
7806       }
7807     }
7808     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7809     // __constant address space.
7810     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7811     // variables inside a function can also be declared in the global
7812     // address space.
7813     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7814     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7815     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7816         NewVD->hasExternalStorage()) {
7817       if (!T->isSamplerT() &&
7818           !(T.getAddressSpace() == LangAS::opencl_constant ||
7819             (T.getAddressSpace() == LangAS::opencl_global &&
7820              (getLangOpts().OpenCLVersion == 200 ||
7821               getLangOpts().OpenCLCPlusPlus)))) {
7822         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7823         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7824           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7825               << Scope << "global or constant";
7826         else
7827           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7828               << Scope << "constant";
7829         NewVD->setInvalidDecl();
7830         return;
7831       }
7832     } else {
7833       if (T.getAddressSpace() == LangAS::opencl_global) {
7834         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7835             << 1 /*is any function*/ << "global";
7836         NewVD->setInvalidDecl();
7837         return;
7838       }
7839       if (T.getAddressSpace() == LangAS::opencl_constant ||
7840           T.getAddressSpace() == LangAS::opencl_local) {
7841         FunctionDecl *FD = getCurFunctionDecl();
7842         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7843         // in functions.
7844         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7845           if (T.getAddressSpace() == LangAS::opencl_constant)
7846             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7847                 << 0 /*non-kernel only*/ << "constant";
7848           else
7849             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7850                 << 0 /*non-kernel only*/ << "local";
7851           NewVD->setInvalidDecl();
7852           return;
7853         }
7854         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7855         // in the outermost scope of a kernel function.
7856         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7857           if (!getCurScope()->isFunctionScope()) {
7858             if (T.getAddressSpace() == LangAS::opencl_constant)
7859               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7860                   << "constant";
7861             else
7862               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7863                   << "local";
7864             NewVD->setInvalidDecl();
7865             return;
7866           }
7867         }
7868       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7869                  // If we are parsing a template we didn't deduce an addr
7870                  // space yet.
7871                  T.getAddressSpace() != LangAS::Default) {
7872         // Do not allow other address spaces on automatic variable.
7873         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7874         NewVD->setInvalidDecl();
7875         return;
7876       }
7877     }
7878   }
7879 
7880   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7881       && !NewVD->hasAttr<BlocksAttr>()) {
7882     if (getLangOpts().getGC() != LangOptions::NonGC)
7883       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7884     else {
7885       assert(!getLangOpts().ObjCAutoRefCount);
7886       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7887     }
7888   }
7889 
7890   bool isVM = T->isVariablyModifiedType();
7891   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7892       NewVD->hasAttr<BlocksAttr>())
7893     setFunctionHasBranchProtectedScope();
7894 
7895   if ((isVM && NewVD->hasLinkage()) ||
7896       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7897     bool SizeIsNegative;
7898     llvm::APSInt Oversized;
7899     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7900         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7901     QualType FixedT;
7902     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7903       FixedT = FixedTInfo->getType();
7904     else if (FixedTInfo) {
7905       // Type and type-as-written are canonically different. We need to fix up
7906       // both types separately.
7907       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7908                                                    Oversized);
7909     }
7910     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7911       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7912       // FIXME: This won't give the correct result for
7913       // int a[10][n];
7914       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7915 
7916       if (NewVD->isFileVarDecl())
7917         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7918         << SizeRange;
7919       else if (NewVD->isStaticLocal())
7920         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7921         << SizeRange;
7922       else
7923         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7924         << SizeRange;
7925       NewVD->setInvalidDecl();
7926       return;
7927     }
7928 
7929     if (!FixedTInfo) {
7930       if (NewVD->isFileVarDecl())
7931         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7932       else
7933         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7934       NewVD->setInvalidDecl();
7935       return;
7936     }
7937 
7938     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7939     NewVD->setType(FixedT);
7940     NewVD->setTypeSourceInfo(FixedTInfo);
7941   }
7942 
7943   if (T->isVoidType()) {
7944     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7945     //                    of objects and functions.
7946     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7947       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7948         << T;
7949       NewVD->setInvalidDecl();
7950       return;
7951     }
7952   }
7953 
7954   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7955     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7956     NewVD->setInvalidDecl();
7957     return;
7958   }
7959 
7960   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
7961     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
7962     NewVD->setInvalidDecl();
7963     return;
7964   }
7965 
7966   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7967     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7968     NewVD->setInvalidDecl();
7969     return;
7970   }
7971 
7972   if (NewVD->isConstexpr() && !T->isDependentType() &&
7973       RequireLiteralType(NewVD->getLocation(), T,
7974                          diag::err_constexpr_var_non_literal)) {
7975     NewVD->setInvalidDecl();
7976     return;
7977   }
7978 }
7979 
7980 /// Perform semantic checking on a newly-created variable
7981 /// declaration.
7982 ///
7983 /// This routine performs all of the type-checking required for a
7984 /// variable declaration once it has been built. It is used both to
7985 /// check variables after they have been parsed and their declarators
7986 /// have been translated into a declaration, and to check variables
7987 /// that have been instantiated from a template.
7988 ///
7989 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7990 ///
7991 /// Returns true if the variable declaration is a redeclaration.
7992 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7993   CheckVariableDeclarationType(NewVD);
7994 
7995   // If the decl is already known invalid, don't check it.
7996   if (NewVD->isInvalidDecl())
7997     return false;
7998 
7999   // If we did not find anything by this name, look for a non-visible
8000   // extern "C" declaration with the same name.
8001   if (Previous.empty() &&
8002       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8003     Previous.setShadowed();
8004 
8005   if (!Previous.empty()) {
8006     MergeVarDecl(NewVD, Previous);
8007     return true;
8008   }
8009   return false;
8010 }
8011 
8012 namespace {
8013 struct FindOverriddenMethod {
8014   Sema *S;
8015   CXXMethodDecl *Method;
8016 
8017   /// Member lookup function that determines whether a given C++
8018   /// method overrides a method in a base class, to be used with
8019   /// CXXRecordDecl::lookupInBases().
8020   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8021     RecordDecl *BaseRecord =
8022         Specifier->getType()->castAs<RecordType>()->getDecl();
8023 
8024     DeclarationName Name = Method->getDeclName();
8025 
8026     // FIXME: Do we care about other names here too?
8027     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8028       // We really want to find the base class destructor here.
8029       QualType T = S->Context.getTypeDeclType(BaseRecord);
8030       CanQualType CT = S->Context.getCanonicalType(T);
8031 
8032       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8033     }
8034 
8035     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8036          Path.Decls = Path.Decls.slice(1)) {
8037       NamedDecl *D = Path.Decls.front();
8038       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8039         if (MD->isVirtual() &&
8040             !S->IsOverload(
8041                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8042                 /*ConsiderCudaAttrs=*/true,
8043                 // C++2a [class.virtual]p2 does not consider requires clauses
8044                 // when overriding.
8045                 /*ConsiderRequiresClauses=*/false))
8046           return true;
8047       }
8048     }
8049 
8050     return false;
8051   }
8052 };
8053 } // end anonymous namespace
8054 
8055 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8056 /// and if so, check that it's a valid override and remember it.
8057 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8058   // Look for methods in base classes that this method might override.
8059   CXXBasePaths Paths;
8060   FindOverriddenMethod FOM;
8061   FOM.Method = MD;
8062   FOM.S = this;
8063   bool AddedAny = false;
8064   if (DC->lookupInBases(FOM, Paths)) {
8065     for (auto *I : Paths.found_decls()) {
8066       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8067         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8068         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8069             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8070             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8071             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8072           AddedAny = true;
8073         }
8074       }
8075     }
8076   }
8077 
8078   return AddedAny;
8079 }
8080 
8081 namespace {
8082   // Struct for holding all of the extra arguments needed by
8083   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8084   struct ActOnFDArgs {
8085     Scope *S;
8086     Declarator &D;
8087     MultiTemplateParamsArg TemplateParamLists;
8088     bool AddToScope;
8089   };
8090 } // end anonymous namespace
8091 
8092 namespace {
8093 
8094 // Callback to only accept typo corrections that have a non-zero edit distance.
8095 // Also only accept corrections that have the same parent decl.
8096 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8097  public:
8098   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8099                             CXXRecordDecl *Parent)
8100       : Context(Context), OriginalFD(TypoFD),
8101         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8102 
8103   bool ValidateCandidate(const TypoCorrection &candidate) override {
8104     if (candidate.getEditDistance() == 0)
8105       return false;
8106 
8107     SmallVector<unsigned, 1> MismatchedParams;
8108     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8109                                           CDeclEnd = candidate.end();
8110          CDecl != CDeclEnd; ++CDecl) {
8111       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8112 
8113       if (FD && !FD->hasBody() &&
8114           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8115         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8116           CXXRecordDecl *Parent = MD->getParent();
8117           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8118             return true;
8119         } else if (!ExpectedParent) {
8120           return true;
8121         }
8122       }
8123     }
8124 
8125     return false;
8126   }
8127 
8128   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8129     return std::make_unique<DifferentNameValidatorCCC>(*this);
8130   }
8131 
8132  private:
8133   ASTContext &Context;
8134   FunctionDecl *OriginalFD;
8135   CXXRecordDecl *ExpectedParent;
8136 };
8137 
8138 } // end anonymous namespace
8139 
8140 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8141   TypoCorrectedFunctionDefinitions.insert(F);
8142 }
8143 
8144 /// Generate diagnostics for an invalid function redeclaration.
8145 ///
8146 /// This routine handles generating the diagnostic messages for an invalid
8147 /// function redeclaration, including finding possible similar declarations
8148 /// or performing typo correction if there are no previous declarations with
8149 /// the same name.
8150 ///
8151 /// Returns a NamedDecl iff typo correction was performed and substituting in
8152 /// the new declaration name does not cause new errors.
8153 static NamedDecl *DiagnoseInvalidRedeclaration(
8154     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8155     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8156   DeclarationName Name = NewFD->getDeclName();
8157   DeclContext *NewDC = NewFD->getDeclContext();
8158   SmallVector<unsigned, 1> MismatchedParams;
8159   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8160   TypoCorrection Correction;
8161   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8162   unsigned DiagMsg =
8163     IsLocalFriend ? diag::err_no_matching_local_friend :
8164     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8165     diag::err_member_decl_does_not_match;
8166   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8167                     IsLocalFriend ? Sema::LookupLocalFriendName
8168                                   : Sema::LookupOrdinaryName,
8169                     Sema::ForVisibleRedeclaration);
8170 
8171   NewFD->setInvalidDecl();
8172   if (IsLocalFriend)
8173     SemaRef.LookupName(Prev, S);
8174   else
8175     SemaRef.LookupQualifiedName(Prev, NewDC);
8176   assert(!Prev.isAmbiguous() &&
8177          "Cannot have an ambiguity in previous-declaration lookup");
8178   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8179   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8180                                 MD ? MD->getParent() : nullptr);
8181   if (!Prev.empty()) {
8182     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8183          Func != FuncEnd; ++Func) {
8184       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8185       if (FD &&
8186           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8187         // Add 1 to the index so that 0 can mean the mismatch didn't
8188         // involve a parameter
8189         unsigned ParamNum =
8190             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8191         NearMatches.push_back(std::make_pair(FD, ParamNum));
8192       }
8193     }
8194   // If the qualified name lookup yielded nothing, try typo correction
8195   } else if ((Correction = SemaRef.CorrectTypo(
8196                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8197                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8198                   IsLocalFriend ? nullptr : NewDC))) {
8199     // Set up everything for the call to ActOnFunctionDeclarator
8200     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8201                               ExtraArgs.D.getIdentifierLoc());
8202     Previous.clear();
8203     Previous.setLookupName(Correction.getCorrection());
8204     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8205                                     CDeclEnd = Correction.end();
8206          CDecl != CDeclEnd; ++CDecl) {
8207       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8208       if (FD && !FD->hasBody() &&
8209           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8210         Previous.addDecl(FD);
8211       }
8212     }
8213     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8214 
8215     NamedDecl *Result;
8216     // Retry building the function declaration with the new previous
8217     // declarations, and with errors suppressed.
8218     {
8219       // Trap errors.
8220       Sema::SFINAETrap Trap(SemaRef);
8221 
8222       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8223       // pieces need to verify the typo-corrected C++ declaration and hopefully
8224       // eliminate the need for the parameter pack ExtraArgs.
8225       Result = SemaRef.ActOnFunctionDeclarator(
8226           ExtraArgs.S, ExtraArgs.D,
8227           Correction.getCorrectionDecl()->getDeclContext(),
8228           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8229           ExtraArgs.AddToScope);
8230 
8231       if (Trap.hasErrorOccurred())
8232         Result = nullptr;
8233     }
8234 
8235     if (Result) {
8236       // Determine which correction we picked.
8237       Decl *Canonical = Result->getCanonicalDecl();
8238       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8239            I != E; ++I)
8240         if ((*I)->getCanonicalDecl() == Canonical)
8241           Correction.setCorrectionDecl(*I);
8242 
8243       // Let Sema know about the correction.
8244       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8245       SemaRef.diagnoseTypo(
8246           Correction,
8247           SemaRef.PDiag(IsLocalFriend
8248                           ? diag::err_no_matching_local_friend_suggest
8249                           : diag::err_member_decl_does_not_match_suggest)
8250             << Name << NewDC << IsDefinition);
8251       return Result;
8252     }
8253 
8254     // Pretend the typo correction never occurred
8255     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8256                               ExtraArgs.D.getIdentifierLoc());
8257     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8258     Previous.clear();
8259     Previous.setLookupName(Name);
8260   }
8261 
8262   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8263       << Name << NewDC << IsDefinition << NewFD->getLocation();
8264 
8265   bool NewFDisConst = false;
8266   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8267     NewFDisConst = NewMD->isConst();
8268 
8269   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8270        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8271        NearMatch != NearMatchEnd; ++NearMatch) {
8272     FunctionDecl *FD = NearMatch->first;
8273     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8274     bool FDisConst = MD && MD->isConst();
8275     bool IsMember = MD || !IsLocalFriend;
8276 
8277     // FIXME: These notes are poorly worded for the local friend case.
8278     if (unsigned Idx = NearMatch->second) {
8279       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8280       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8281       if (Loc.isInvalid()) Loc = FD->getLocation();
8282       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8283                                  : diag::note_local_decl_close_param_match)
8284         << Idx << FDParam->getType()
8285         << NewFD->getParamDecl(Idx - 1)->getType();
8286     } else if (FDisConst != NewFDisConst) {
8287       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8288           << NewFDisConst << FD->getSourceRange().getEnd();
8289     } else
8290       SemaRef.Diag(FD->getLocation(),
8291                    IsMember ? diag::note_member_def_close_match
8292                             : diag::note_local_decl_close_match);
8293   }
8294   return nullptr;
8295 }
8296 
8297 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8298   switch (D.getDeclSpec().getStorageClassSpec()) {
8299   default: llvm_unreachable("Unknown storage class!");
8300   case DeclSpec::SCS_auto:
8301   case DeclSpec::SCS_register:
8302   case DeclSpec::SCS_mutable:
8303     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8304                  diag::err_typecheck_sclass_func);
8305     D.getMutableDeclSpec().ClearStorageClassSpecs();
8306     D.setInvalidType();
8307     break;
8308   case DeclSpec::SCS_unspecified: break;
8309   case DeclSpec::SCS_extern:
8310     if (D.getDeclSpec().isExternInLinkageSpec())
8311       return SC_None;
8312     return SC_Extern;
8313   case DeclSpec::SCS_static: {
8314     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8315       // C99 6.7.1p5:
8316       //   The declaration of an identifier for a function that has
8317       //   block scope shall have no explicit storage-class specifier
8318       //   other than extern
8319       // See also (C++ [dcl.stc]p4).
8320       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8321                    diag::err_static_block_func);
8322       break;
8323     } else
8324       return SC_Static;
8325   }
8326   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8327   }
8328 
8329   // No explicit storage class has already been returned
8330   return SC_None;
8331 }
8332 
8333 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8334                                            DeclContext *DC, QualType &R,
8335                                            TypeSourceInfo *TInfo,
8336                                            StorageClass SC,
8337                                            bool &IsVirtualOkay) {
8338   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8339   DeclarationName Name = NameInfo.getName();
8340 
8341   FunctionDecl *NewFD = nullptr;
8342   bool isInline = D.getDeclSpec().isInlineSpecified();
8343 
8344   if (!SemaRef.getLangOpts().CPlusPlus) {
8345     // Determine whether the function was written with a
8346     // prototype. This true when:
8347     //   - there is a prototype in the declarator, or
8348     //   - the type R of the function is some kind of typedef or other non-
8349     //     attributed reference to a type name (which eventually refers to a
8350     //     function type).
8351     bool HasPrototype =
8352       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8353       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8354 
8355     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8356                                  R, TInfo, SC, isInline, HasPrototype,
8357                                  CSK_unspecified,
8358                                  /*TrailingRequiresClause=*/nullptr);
8359     if (D.isInvalidType())
8360       NewFD->setInvalidDecl();
8361 
8362     return NewFD;
8363   }
8364 
8365   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8366 
8367   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8368   if (ConstexprKind == CSK_constinit) {
8369     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8370                  diag::err_constexpr_wrong_decl_kind)
8371         << ConstexprKind;
8372     ConstexprKind = CSK_unspecified;
8373     D.getMutableDeclSpec().ClearConstexprSpec();
8374   }
8375   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8376 
8377   // Check that the return type is not an abstract class type.
8378   // For record types, this is done by the AbstractClassUsageDiagnoser once
8379   // the class has been completely parsed.
8380   if (!DC->isRecord() &&
8381       SemaRef.RequireNonAbstractType(
8382           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8383           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8384     D.setInvalidType();
8385 
8386   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8387     // This is a C++ constructor declaration.
8388     assert(DC->isRecord() &&
8389            "Constructors can only be declared in a member context");
8390 
8391     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8392     return CXXConstructorDecl::Create(
8393         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8394         TInfo, ExplicitSpecifier, isInline,
8395         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8396         TrailingRequiresClause);
8397 
8398   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8399     // This is a C++ destructor declaration.
8400     if (DC->isRecord()) {
8401       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8402       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8403       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8404           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8405           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8406           TrailingRequiresClause);
8407 
8408       // If the destructor needs an implicit exception specification, set it
8409       // now. FIXME: It'd be nice to be able to create the right type to start
8410       // with, but the type needs to reference the destructor declaration.
8411       if (SemaRef.getLangOpts().CPlusPlus11)
8412         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8413 
8414       IsVirtualOkay = true;
8415       return NewDD;
8416 
8417     } else {
8418       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8419       D.setInvalidType();
8420 
8421       // Create a FunctionDecl to satisfy the function definition parsing
8422       // code path.
8423       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8424                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8425                                   isInline,
8426                                   /*hasPrototype=*/true, ConstexprKind,
8427                                   TrailingRequiresClause);
8428     }
8429 
8430   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8431     if (!DC->isRecord()) {
8432       SemaRef.Diag(D.getIdentifierLoc(),
8433            diag::err_conv_function_not_member);
8434       return nullptr;
8435     }
8436 
8437     SemaRef.CheckConversionDeclarator(D, R, SC);
8438     if (D.isInvalidType())
8439       return nullptr;
8440 
8441     IsVirtualOkay = true;
8442     return CXXConversionDecl::Create(
8443         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8444         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8445         TrailingRequiresClause);
8446 
8447   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8448     if (TrailingRequiresClause)
8449       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8450                    diag::err_trailing_requires_clause_on_deduction_guide)
8451           << TrailingRequiresClause->getSourceRange();
8452     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8453 
8454     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8455                                          ExplicitSpecifier, NameInfo, R, TInfo,
8456                                          D.getEndLoc());
8457   } else if (DC->isRecord()) {
8458     // If the name of the function is the same as the name of the record,
8459     // then this must be an invalid constructor that has a return type.
8460     // (The parser checks for a return type and makes the declarator a
8461     // constructor if it has no return type).
8462     if (Name.getAsIdentifierInfo() &&
8463         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8464       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8465         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8466         << SourceRange(D.getIdentifierLoc());
8467       return nullptr;
8468     }
8469 
8470     // This is a C++ method declaration.
8471     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8472         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8473         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8474         TrailingRequiresClause);
8475     IsVirtualOkay = !Ret->isStatic();
8476     return Ret;
8477   } else {
8478     bool isFriend =
8479         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8480     if (!isFriend && SemaRef.CurContext->isRecord())
8481       return nullptr;
8482 
8483     // Determine whether the function was written with a
8484     // prototype. This true when:
8485     //   - we're in C++ (where every function has a prototype),
8486     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8487                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8488                                 ConstexprKind, TrailingRequiresClause);
8489   }
8490 }
8491 
8492 enum OpenCLParamType {
8493   ValidKernelParam,
8494   PtrPtrKernelParam,
8495   PtrKernelParam,
8496   InvalidAddrSpacePtrKernelParam,
8497   InvalidKernelParam,
8498   RecordKernelParam
8499 };
8500 
8501 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8502   // Size dependent types are just typedefs to normal integer types
8503   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8504   // integers other than by their names.
8505   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8506 
8507   // Remove typedefs one by one until we reach a typedef
8508   // for a size dependent type.
8509   QualType DesugaredTy = Ty;
8510   do {
8511     ArrayRef<StringRef> Names(SizeTypeNames);
8512     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8513     if (Names.end() != Match)
8514       return true;
8515 
8516     Ty = DesugaredTy;
8517     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8518   } while (DesugaredTy != Ty);
8519 
8520   return false;
8521 }
8522 
8523 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8524   if (PT->isPointerType()) {
8525     QualType PointeeType = PT->getPointeeType();
8526     if (PointeeType->isPointerType())
8527       return PtrPtrKernelParam;
8528     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8529         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8530         PointeeType.getAddressSpace() == LangAS::Default)
8531       return InvalidAddrSpacePtrKernelParam;
8532     return PtrKernelParam;
8533   }
8534 
8535   // OpenCL v1.2 s6.9.k:
8536   // Arguments to kernel functions in a program cannot be declared with the
8537   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8538   // uintptr_t or a struct and/or union that contain fields declared to be one
8539   // of these built-in scalar types.
8540   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8541     return InvalidKernelParam;
8542 
8543   if (PT->isImageType())
8544     return PtrKernelParam;
8545 
8546   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8547     return InvalidKernelParam;
8548 
8549   // OpenCL extension spec v1.2 s9.5:
8550   // This extension adds support for half scalar and vector types as built-in
8551   // types that can be used for arithmetic operations, conversions etc.
8552   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8553     return InvalidKernelParam;
8554 
8555   if (PT->isRecordType())
8556     return RecordKernelParam;
8557 
8558   // Look into an array argument to check if it has a forbidden type.
8559   if (PT->isArrayType()) {
8560     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8561     // Call ourself to check an underlying type of an array. Since the
8562     // getPointeeOrArrayElementType returns an innermost type which is not an
8563     // array, this recursive call only happens once.
8564     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8565   }
8566 
8567   return ValidKernelParam;
8568 }
8569 
8570 static void checkIsValidOpenCLKernelParameter(
8571   Sema &S,
8572   Declarator &D,
8573   ParmVarDecl *Param,
8574   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8575   QualType PT = Param->getType();
8576 
8577   // Cache the valid types we encounter to avoid rechecking structs that are
8578   // used again
8579   if (ValidTypes.count(PT.getTypePtr()))
8580     return;
8581 
8582   switch (getOpenCLKernelParameterType(S, PT)) {
8583   case PtrPtrKernelParam:
8584     // OpenCL v1.2 s6.9.a:
8585     // A kernel function argument cannot be declared as a
8586     // pointer to a pointer type.
8587     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8588     D.setInvalidType();
8589     return;
8590 
8591   case InvalidAddrSpacePtrKernelParam:
8592     // OpenCL v1.0 s6.5:
8593     // __kernel function arguments declared to be a pointer of a type can point
8594     // to one of the following address spaces only : __global, __local or
8595     // __constant.
8596     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8597     D.setInvalidType();
8598     return;
8599 
8600     // OpenCL v1.2 s6.9.k:
8601     // Arguments to kernel functions in a program cannot be declared with the
8602     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8603     // uintptr_t or a struct and/or union that contain fields declared to be
8604     // one of these built-in scalar types.
8605 
8606   case InvalidKernelParam:
8607     // OpenCL v1.2 s6.8 n:
8608     // A kernel function argument cannot be declared
8609     // of event_t type.
8610     // Do not diagnose half type since it is diagnosed as invalid argument
8611     // type for any function elsewhere.
8612     if (!PT->isHalfType()) {
8613       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8614 
8615       // Explain what typedefs are involved.
8616       const TypedefType *Typedef = nullptr;
8617       while ((Typedef = PT->getAs<TypedefType>())) {
8618         SourceLocation Loc = Typedef->getDecl()->getLocation();
8619         // SourceLocation may be invalid for a built-in type.
8620         if (Loc.isValid())
8621           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8622         PT = Typedef->desugar();
8623       }
8624     }
8625 
8626     D.setInvalidType();
8627     return;
8628 
8629   case PtrKernelParam:
8630   case ValidKernelParam:
8631     ValidTypes.insert(PT.getTypePtr());
8632     return;
8633 
8634   case RecordKernelParam:
8635     break;
8636   }
8637 
8638   // Track nested structs we will inspect
8639   SmallVector<const Decl *, 4> VisitStack;
8640 
8641   // Track where we are in the nested structs. Items will migrate from
8642   // VisitStack to HistoryStack as we do the DFS for bad field.
8643   SmallVector<const FieldDecl *, 4> HistoryStack;
8644   HistoryStack.push_back(nullptr);
8645 
8646   // At this point we already handled everything except of a RecordType or
8647   // an ArrayType of a RecordType.
8648   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8649   const RecordType *RecTy =
8650       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8651   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8652 
8653   VisitStack.push_back(RecTy->getDecl());
8654   assert(VisitStack.back() && "First decl null?");
8655 
8656   do {
8657     const Decl *Next = VisitStack.pop_back_val();
8658     if (!Next) {
8659       assert(!HistoryStack.empty());
8660       // Found a marker, we have gone up a level
8661       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8662         ValidTypes.insert(Hist->getType().getTypePtr());
8663 
8664       continue;
8665     }
8666 
8667     // Adds everything except the original parameter declaration (which is not a
8668     // field itself) to the history stack.
8669     const RecordDecl *RD;
8670     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8671       HistoryStack.push_back(Field);
8672 
8673       QualType FieldTy = Field->getType();
8674       // Other field types (known to be valid or invalid) are handled while we
8675       // walk around RecordDecl::fields().
8676       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8677              "Unexpected type.");
8678       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8679 
8680       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8681     } else {
8682       RD = cast<RecordDecl>(Next);
8683     }
8684 
8685     // Add a null marker so we know when we've gone back up a level
8686     VisitStack.push_back(nullptr);
8687 
8688     for (const auto *FD : RD->fields()) {
8689       QualType QT = FD->getType();
8690 
8691       if (ValidTypes.count(QT.getTypePtr()))
8692         continue;
8693 
8694       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8695       if (ParamType == ValidKernelParam)
8696         continue;
8697 
8698       if (ParamType == RecordKernelParam) {
8699         VisitStack.push_back(FD);
8700         continue;
8701       }
8702 
8703       // OpenCL v1.2 s6.9.p:
8704       // Arguments to kernel functions that are declared to be a struct or union
8705       // do not allow OpenCL objects to be passed as elements of the struct or
8706       // union.
8707       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8708           ParamType == InvalidAddrSpacePtrKernelParam) {
8709         S.Diag(Param->getLocation(),
8710                diag::err_record_with_pointers_kernel_param)
8711           << PT->isUnionType()
8712           << PT;
8713       } else {
8714         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8715       }
8716 
8717       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8718           << OrigRecDecl->getDeclName();
8719 
8720       // We have an error, now let's go back up through history and show where
8721       // the offending field came from
8722       for (ArrayRef<const FieldDecl *>::const_iterator
8723                I = HistoryStack.begin() + 1,
8724                E = HistoryStack.end();
8725            I != E; ++I) {
8726         const FieldDecl *OuterField = *I;
8727         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8728           << OuterField->getType();
8729       }
8730 
8731       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8732         << QT->isPointerType()
8733         << QT;
8734       D.setInvalidType();
8735       return;
8736     }
8737   } while (!VisitStack.empty());
8738 }
8739 
8740 /// Find the DeclContext in which a tag is implicitly declared if we see an
8741 /// elaborated type specifier in the specified context, and lookup finds
8742 /// nothing.
8743 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8744   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8745     DC = DC->getParent();
8746   return DC;
8747 }
8748 
8749 /// Find the Scope in which a tag is implicitly declared if we see an
8750 /// elaborated type specifier in the specified context, and lookup finds
8751 /// nothing.
8752 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8753   while (S->isClassScope() ||
8754          (LangOpts.CPlusPlus &&
8755           S->isFunctionPrototypeScope()) ||
8756          ((S->getFlags() & Scope::DeclScope) == 0) ||
8757          (S->getEntity() && S->getEntity()->isTransparentContext()))
8758     S = S->getParent();
8759   return S;
8760 }
8761 
8762 NamedDecl*
8763 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8764                               TypeSourceInfo *TInfo, LookupResult &Previous,
8765                               MultiTemplateParamsArg TemplateParamListsRef,
8766                               bool &AddToScope) {
8767   QualType R = TInfo->getType();
8768 
8769   assert(R->isFunctionType());
8770   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8771     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8772 
8773   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8774   for (TemplateParameterList *TPL : TemplateParamListsRef)
8775     TemplateParamLists.push_back(TPL);
8776   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8777     if (!TemplateParamLists.empty() &&
8778         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8779       TemplateParamLists.back() = Invented;
8780     else
8781       TemplateParamLists.push_back(Invented);
8782   }
8783 
8784   // TODO: consider using NameInfo for diagnostic.
8785   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8786   DeclarationName Name = NameInfo.getName();
8787   StorageClass SC = getFunctionStorageClass(*this, D);
8788 
8789   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8790     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8791          diag::err_invalid_thread)
8792       << DeclSpec::getSpecifierName(TSCS);
8793 
8794   if (D.isFirstDeclarationOfMember())
8795     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8796                            D.getIdentifierLoc());
8797 
8798   bool isFriend = false;
8799   FunctionTemplateDecl *FunctionTemplate = nullptr;
8800   bool isMemberSpecialization = false;
8801   bool isFunctionTemplateSpecialization = false;
8802 
8803   bool isDependentClassScopeExplicitSpecialization = false;
8804   bool HasExplicitTemplateArgs = false;
8805   TemplateArgumentListInfo TemplateArgs;
8806 
8807   bool isVirtualOkay = false;
8808 
8809   DeclContext *OriginalDC = DC;
8810   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8811 
8812   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8813                                               isVirtualOkay);
8814   if (!NewFD) return nullptr;
8815 
8816   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8817     NewFD->setTopLevelDeclInObjCContainer();
8818 
8819   // Set the lexical context. If this is a function-scope declaration, or has a
8820   // C++ scope specifier, or is the object of a friend declaration, the lexical
8821   // context will be different from the semantic context.
8822   NewFD->setLexicalDeclContext(CurContext);
8823 
8824   if (IsLocalExternDecl)
8825     NewFD->setLocalExternDecl();
8826 
8827   if (getLangOpts().CPlusPlus) {
8828     bool isInline = D.getDeclSpec().isInlineSpecified();
8829     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8830     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8831     isFriend = D.getDeclSpec().isFriendSpecified();
8832     if (isFriend && !isInline && D.isFunctionDefinition()) {
8833       // C++ [class.friend]p5
8834       //   A function can be defined in a friend declaration of a
8835       //   class . . . . Such a function is implicitly inline.
8836       NewFD->setImplicitlyInline();
8837     }
8838 
8839     // If this is a method defined in an __interface, and is not a constructor
8840     // or an overloaded operator, then set the pure flag (isVirtual will already
8841     // return true).
8842     if (const CXXRecordDecl *Parent =
8843           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8844       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8845         NewFD->setPure(true);
8846 
8847       // C++ [class.union]p2
8848       //   A union can have member functions, but not virtual functions.
8849       if (isVirtual && Parent->isUnion())
8850         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8851     }
8852 
8853     SetNestedNameSpecifier(*this, NewFD, D);
8854     isMemberSpecialization = false;
8855     isFunctionTemplateSpecialization = false;
8856     if (D.isInvalidType())
8857       NewFD->setInvalidDecl();
8858 
8859     // Match up the template parameter lists with the scope specifier, then
8860     // determine whether we have a template or a template specialization.
8861     bool Invalid = false;
8862     TemplateParameterList *TemplateParams =
8863         MatchTemplateParametersToScopeSpecifier(
8864             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8865             D.getCXXScopeSpec(),
8866             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8867                 ? D.getName().TemplateId
8868                 : nullptr,
8869             TemplateParamLists, isFriend, isMemberSpecialization,
8870             Invalid);
8871     if (TemplateParams) {
8872       if (TemplateParams->size() > 0) {
8873         // This is a function template
8874 
8875         // Check that we can declare a template here.
8876         if (CheckTemplateDeclScope(S, TemplateParams))
8877           NewFD->setInvalidDecl();
8878 
8879         // A destructor cannot be a template.
8880         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8881           Diag(NewFD->getLocation(), diag::err_destructor_template);
8882           NewFD->setInvalidDecl();
8883         }
8884 
8885         // If we're adding a template to a dependent context, we may need to
8886         // rebuilding some of the types used within the template parameter list,
8887         // now that we know what the current instantiation is.
8888         if (DC->isDependentContext()) {
8889           ContextRAII SavedContext(*this, DC);
8890           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8891             Invalid = true;
8892         }
8893 
8894         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8895                                                         NewFD->getLocation(),
8896                                                         Name, TemplateParams,
8897                                                         NewFD);
8898         FunctionTemplate->setLexicalDeclContext(CurContext);
8899         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8900 
8901         // For source fidelity, store the other template param lists.
8902         if (TemplateParamLists.size() > 1) {
8903           NewFD->setTemplateParameterListsInfo(Context,
8904               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8905                   .drop_back(1));
8906         }
8907       } else {
8908         // This is a function template specialization.
8909         isFunctionTemplateSpecialization = true;
8910         // For source fidelity, store all the template param lists.
8911         if (TemplateParamLists.size() > 0)
8912           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8913 
8914         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8915         if (isFriend) {
8916           // We want to remove the "template<>", found here.
8917           SourceRange RemoveRange = TemplateParams->getSourceRange();
8918 
8919           // If we remove the template<> and the name is not a
8920           // template-id, we're actually silently creating a problem:
8921           // the friend declaration will refer to an untemplated decl,
8922           // and clearly the user wants a template specialization.  So
8923           // we need to insert '<>' after the name.
8924           SourceLocation InsertLoc;
8925           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8926             InsertLoc = D.getName().getSourceRange().getEnd();
8927             InsertLoc = getLocForEndOfToken(InsertLoc);
8928           }
8929 
8930           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8931             << Name << RemoveRange
8932             << FixItHint::CreateRemoval(RemoveRange)
8933             << FixItHint::CreateInsertion(InsertLoc, "<>");
8934         }
8935       }
8936     } else {
8937       // All template param lists were matched against the scope specifier:
8938       // this is NOT (an explicit specialization of) a template.
8939       if (TemplateParamLists.size() > 0)
8940         // For source fidelity, store all the template param lists.
8941         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8942     }
8943 
8944     if (Invalid) {
8945       NewFD->setInvalidDecl();
8946       if (FunctionTemplate)
8947         FunctionTemplate->setInvalidDecl();
8948     }
8949 
8950     // C++ [dcl.fct.spec]p5:
8951     //   The virtual specifier shall only be used in declarations of
8952     //   nonstatic class member functions that appear within a
8953     //   member-specification of a class declaration; see 10.3.
8954     //
8955     if (isVirtual && !NewFD->isInvalidDecl()) {
8956       if (!isVirtualOkay) {
8957         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8958              diag::err_virtual_non_function);
8959       } else if (!CurContext->isRecord()) {
8960         // 'virtual' was specified outside of the class.
8961         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8962              diag::err_virtual_out_of_class)
8963           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8964       } else if (NewFD->getDescribedFunctionTemplate()) {
8965         // C++ [temp.mem]p3:
8966         //  A member function template shall not be virtual.
8967         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8968              diag::err_virtual_member_function_template)
8969           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8970       } else {
8971         // Okay: Add virtual to the method.
8972         NewFD->setVirtualAsWritten(true);
8973       }
8974 
8975       if (getLangOpts().CPlusPlus14 &&
8976           NewFD->getReturnType()->isUndeducedType())
8977         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8978     }
8979 
8980     if (getLangOpts().CPlusPlus14 &&
8981         (NewFD->isDependentContext() ||
8982          (isFriend && CurContext->isDependentContext())) &&
8983         NewFD->getReturnType()->isUndeducedType()) {
8984       // If the function template is referenced directly (for instance, as a
8985       // member of the current instantiation), pretend it has a dependent type.
8986       // This is not really justified by the standard, but is the only sane
8987       // thing to do.
8988       // FIXME: For a friend function, we have not marked the function as being
8989       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8990       const FunctionProtoType *FPT =
8991           NewFD->getType()->castAs<FunctionProtoType>();
8992       QualType Result =
8993           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8994       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8995                                              FPT->getExtProtoInfo()));
8996     }
8997 
8998     // C++ [dcl.fct.spec]p3:
8999     //  The inline specifier shall not appear on a block scope function
9000     //  declaration.
9001     if (isInline && !NewFD->isInvalidDecl()) {
9002       if (CurContext->isFunctionOrMethod()) {
9003         // 'inline' is not allowed on block scope function declaration.
9004         Diag(D.getDeclSpec().getInlineSpecLoc(),
9005              diag::err_inline_declaration_block_scope) << Name
9006           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9007       }
9008     }
9009 
9010     // C++ [dcl.fct.spec]p6:
9011     //  The explicit specifier shall be used only in the declaration of a
9012     //  constructor or conversion function within its class definition;
9013     //  see 12.3.1 and 12.3.2.
9014     if (hasExplicit && !NewFD->isInvalidDecl() &&
9015         !isa<CXXDeductionGuideDecl>(NewFD)) {
9016       if (!CurContext->isRecord()) {
9017         // 'explicit' was specified outside of the class.
9018         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9019              diag::err_explicit_out_of_class)
9020             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9021       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9022                  !isa<CXXConversionDecl>(NewFD)) {
9023         // 'explicit' was specified on a function that wasn't a constructor
9024         // or conversion function.
9025         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9026              diag::err_explicit_non_ctor_or_conv_function)
9027             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9028       }
9029     }
9030 
9031     if (ConstexprSpecKind ConstexprKind =
9032             D.getDeclSpec().getConstexprSpecifier()) {
9033       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9034       // are implicitly inline.
9035       NewFD->setImplicitlyInline();
9036 
9037       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9038       // be either constructors or to return a literal type. Therefore,
9039       // destructors cannot be declared constexpr.
9040       if (isa<CXXDestructorDecl>(NewFD) &&
9041           (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) {
9042         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9043             << ConstexprKind;
9044         NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr);
9045       }
9046       // C++20 [dcl.constexpr]p2: An allocation function, or a
9047       // deallocation function shall not be declared with the consteval
9048       // specifier.
9049       if (ConstexprKind == CSK_consteval &&
9050           (NewFD->getOverloadedOperator() == OO_New ||
9051            NewFD->getOverloadedOperator() == OO_Array_New ||
9052            NewFD->getOverloadedOperator() == OO_Delete ||
9053            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9054         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9055              diag::err_invalid_consteval_decl_kind)
9056             << NewFD;
9057         NewFD->setConstexprKind(CSK_constexpr);
9058       }
9059     }
9060 
9061     // If __module_private__ was specified, mark the function accordingly.
9062     if (D.getDeclSpec().isModulePrivateSpecified()) {
9063       if (isFunctionTemplateSpecialization) {
9064         SourceLocation ModulePrivateLoc
9065           = D.getDeclSpec().getModulePrivateSpecLoc();
9066         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9067           << 0
9068           << FixItHint::CreateRemoval(ModulePrivateLoc);
9069       } else {
9070         NewFD->setModulePrivate();
9071         if (FunctionTemplate)
9072           FunctionTemplate->setModulePrivate();
9073       }
9074     }
9075 
9076     if (isFriend) {
9077       if (FunctionTemplate) {
9078         FunctionTemplate->setObjectOfFriendDecl();
9079         FunctionTemplate->setAccess(AS_public);
9080       }
9081       NewFD->setObjectOfFriendDecl();
9082       NewFD->setAccess(AS_public);
9083     }
9084 
9085     // If a function is defined as defaulted or deleted, mark it as such now.
9086     // We'll do the relevant checks on defaulted / deleted functions later.
9087     switch (D.getFunctionDefinitionKind()) {
9088       case FDK_Declaration:
9089       case FDK_Definition:
9090         break;
9091 
9092       case FDK_Defaulted:
9093         NewFD->setDefaulted();
9094         break;
9095 
9096       case FDK_Deleted:
9097         NewFD->setDeletedAsWritten();
9098         break;
9099     }
9100 
9101     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9102         D.isFunctionDefinition()) {
9103       // C++ [class.mfct]p2:
9104       //   A member function may be defined (8.4) in its class definition, in
9105       //   which case it is an inline member function (7.1.2)
9106       NewFD->setImplicitlyInline();
9107     }
9108 
9109     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9110         !CurContext->isRecord()) {
9111       // C++ [class.static]p1:
9112       //   A data or function member of a class may be declared static
9113       //   in a class definition, in which case it is a static member of
9114       //   the class.
9115 
9116       // Complain about the 'static' specifier if it's on an out-of-line
9117       // member function definition.
9118 
9119       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9120       // member function template declaration and class member template
9121       // declaration (MSVC versions before 2015), warn about this.
9122       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9123            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9124              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9125            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9126            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9127         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9128     }
9129 
9130     // C++11 [except.spec]p15:
9131     //   A deallocation function with no exception-specification is treated
9132     //   as if it were specified with noexcept(true).
9133     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9134     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9135          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9136         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9137       NewFD->setType(Context.getFunctionType(
9138           FPT->getReturnType(), FPT->getParamTypes(),
9139           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9140   }
9141 
9142   // Filter out previous declarations that don't match the scope.
9143   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9144                        D.getCXXScopeSpec().isNotEmpty() ||
9145                        isMemberSpecialization ||
9146                        isFunctionTemplateSpecialization);
9147 
9148   // Handle GNU asm-label extension (encoded as an attribute).
9149   if (Expr *E = (Expr*) D.getAsmLabel()) {
9150     // The parser guarantees this is a string.
9151     StringLiteral *SE = cast<StringLiteral>(E);
9152     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9153                                         /*IsLiteralLabel=*/true,
9154                                         SE->getStrTokenLoc(0)));
9155   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9156     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9157       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9158     if (I != ExtnameUndeclaredIdentifiers.end()) {
9159       if (isDeclExternC(NewFD)) {
9160         NewFD->addAttr(I->second);
9161         ExtnameUndeclaredIdentifiers.erase(I);
9162       } else
9163         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9164             << /*Variable*/0 << NewFD;
9165     }
9166   }
9167 
9168   // Copy the parameter declarations from the declarator D to the function
9169   // declaration NewFD, if they are available.  First scavenge them into Params.
9170   SmallVector<ParmVarDecl*, 16> Params;
9171   unsigned FTIIdx;
9172   if (D.isFunctionDeclarator(FTIIdx)) {
9173     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9174 
9175     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9176     // function that takes no arguments, not a function that takes a
9177     // single void argument.
9178     // We let through "const void" here because Sema::GetTypeForDeclarator
9179     // already checks for that case.
9180     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9181       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9182         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9183         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9184         Param->setDeclContext(NewFD);
9185         Params.push_back(Param);
9186 
9187         if (Param->isInvalidDecl())
9188           NewFD->setInvalidDecl();
9189       }
9190     }
9191 
9192     if (!getLangOpts().CPlusPlus) {
9193       // In C, find all the tag declarations from the prototype and move them
9194       // into the function DeclContext. Remove them from the surrounding tag
9195       // injection context of the function, which is typically but not always
9196       // the TU.
9197       DeclContext *PrototypeTagContext =
9198           getTagInjectionContext(NewFD->getLexicalDeclContext());
9199       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9200         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9201 
9202         // We don't want to reparent enumerators. Look at their parent enum
9203         // instead.
9204         if (!TD) {
9205           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9206             TD = cast<EnumDecl>(ECD->getDeclContext());
9207         }
9208         if (!TD)
9209           continue;
9210         DeclContext *TagDC = TD->getLexicalDeclContext();
9211         if (!TagDC->containsDecl(TD))
9212           continue;
9213         TagDC->removeDecl(TD);
9214         TD->setDeclContext(NewFD);
9215         NewFD->addDecl(TD);
9216 
9217         // Preserve the lexical DeclContext if it is not the surrounding tag
9218         // injection context of the FD. In this example, the semantic context of
9219         // E will be f and the lexical context will be S, while both the
9220         // semantic and lexical contexts of S will be f:
9221         //   void f(struct S { enum E { a } f; } s);
9222         if (TagDC != PrototypeTagContext)
9223           TD->setLexicalDeclContext(TagDC);
9224       }
9225     }
9226   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9227     // When we're declaring a function with a typedef, typeof, etc as in the
9228     // following example, we'll need to synthesize (unnamed)
9229     // parameters for use in the declaration.
9230     //
9231     // @code
9232     // typedef void fn(int);
9233     // fn f;
9234     // @endcode
9235 
9236     // Synthesize a parameter for each argument type.
9237     for (const auto &AI : FT->param_types()) {
9238       ParmVarDecl *Param =
9239           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9240       Param->setScopeInfo(0, Params.size());
9241       Params.push_back(Param);
9242     }
9243   } else {
9244     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9245            "Should not need args for typedef of non-prototype fn");
9246   }
9247 
9248   // Finally, we know we have the right number of parameters, install them.
9249   NewFD->setParams(Params);
9250 
9251   if (D.getDeclSpec().isNoreturnSpecified())
9252     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9253                                            D.getDeclSpec().getNoreturnSpecLoc(),
9254                                            AttributeCommonInfo::AS_Keyword));
9255 
9256   // Functions returning a variably modified type violate C99 6.7.5.2p2
9257   // because all functions have linkage.
9258   if (!NewFD->isInvalidDecl() &&
9259       NewFD->getReturnType()->isVariablyModifiedType()) {
9260     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9261     NewFD->setInvalidDecl();
9262   }
9263 
9264   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9265   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9266       !NewFD->hasAttr<SectionAttr>())
9267     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9268         Context, PragmaClangTextSection.SectionName,
9269         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9270 
9271   // Apply an implicit SectionAttr if #pragma code_seg is active.
9272   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9273       !NewFD->hasAttr<SectionAttr>()) {
9274     NewFD->addAttr(SectionAttr::CreateImplicit(
9275         Context, CodeSegStack.CurrentValue->getString(),
9276         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9277         SectionAttr::Declspec_allocate));
9278     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9279                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9280                          ASTContext::PSF_Read,
9281                      NewFD))
9282       NewFD->dropAttr<SectionAttr>();
9283   }
9284 
9285   // Apply an implicit CodeSegAttr from class declspec or
9286   // apply an implicit SectionAttr from #pragma code_seg if active.
9287   if (!NewFD->hasAttr<CodeSegAttr>()) {
9288     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9289                                                                  D.isFunctionDefinition())) {
9290       NewFD->addAttr(SAttr);
9291     }
9292   }
9293 
9294   // Handle attributes.
9295   ProcessDeclAttributes(S, NewFD, D);
9296 
9297   if (getLangOpts().OpenCL) {
9298     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9299     // type declaration will generate a compilation error.
9300     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9301     if (AddressSpace != LangAS::Default) {
9302       Diag(NewFD->getLocation(),
9303            diag::err_opencl_return_value_with_address_space);
9304       NewFD->setInvalidDecl();
9305     }
9306   }
9307 
9308   if (!getLangOpts().CPlusPlus) {
9309     // Perform semantic checking on the function declaration.
9310     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9311       CheckMain(NewFD, D.getDeclSpec());
9312 
9313     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9314       CheckMSVCRTEntryPoint(NewFD);
9315 
9316     if (!NewFD->isInvalidDecl())
9317       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9318                                                   isMemberSpecialization));
9319     else if (!Previous.empty())
9320       // Recover gracefully from an invalid redeclaration.
9321       D.setRedeclaration(true);
9322     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9323             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9324            "previous declaration set still overloaded");
9325 
9326     // Diagnose no-prototype function declarations with calling conventions that
9327     // don't support variadic calls. Only do this in C and do it after merging
9328     // possibly prototyped redeclarations.
9329     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9330     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9331       CallingConv CC = FT->getExtInfo().getCC();
9332       if (!supportsVariadicCall(CC)) {
9333         // Windows system headers sometimes accidentally use stdcall without
9334         // (void) parameters, so we relax this to a warning.
9335         int DiagID =
9336             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9337         Diag(NewFD->getLocation(), DiagID)
9338             << FunctionType::getNameForCallConv(CC);
9339       }
9340     }
9341 
9342    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9343        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9344      checkNonTrivialCUnion(NewFD->getReturnType(),
9345                            NewFD->getReturnTypeSourceRange().getBegin(),
9346                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9347   } else {
9348     // C++11 [replacement.functions]p3:
9349     //  The program's definitions shall not be specified as inline.
9350     //
9351     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9352     //
9353     // Suppress the diagnostic if the function is __attribute__((used)), since
9354     // that forces an external definition to be emitted.
9355     if (D.getDeclSpec().isInlineSpecified() &&
9356         NewFD->isReplaceableGlobalAllocationFunction() &&
9357         !NewFD->hasAttr<UsedAttr>())
9358       Diag(D.getDeclSpec().getInlineSpecLoc(),
9359            diag::ext_operator_new_delete_declared_inline)
9360         << NewFD->getDeclName();
9361 
9362     // If the declarator is a template-id, translate the parser's template
9363     // argument list into our AST format.
9364     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9365       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9366       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9367       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9368       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9369                                          TemplateId->NumArgs);
9370       translateTemplateArguments(TemplateArgsPtr,
9371                                  TemplateArgs);
9372 
9373       HasExplicitTemplateArgs = true;
9374 
9375       if (NewFD->isInvalidDecl()) {
9376         HasExplicitTemplateArgs = false;
9377       } else if (FunctionTemplate) {
9378         // Function template with explicit template arguments.
9379         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9380           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9381 
9382         HasExplicitTemplateArgs = false;
9383       } else {
9384         assert((isFunctionTemplateSpecialization ||
9385                 D.getDeclSpec().isFriendSpecified()) &&
9386                "should have a 'template<>' for this decl");
9387         // "friend void foo<>(int);" is an implicit specialization decl.
9388         isFunctionTemplateSpecialization = true;
9389       }
9390     } else if (isFriend && isFunctionTemplateSpecialization) {
9391       // This combination is only possible in a recovery case;  the user
9392       // wrote something like:
9393       //   template <> friend void foo(int);
9394       // which we're recovering from as if the user had written:
9395       //   friend void foo<>(int);
9396       // Go ahead and fake up a template id.
9397       HasExplicitTemplateArgs = true;
9398       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9399       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9400     }
9401 
9402     // We do not add HD attributes to specializations here because
9403     // they may have different constexpr-ness compared to their
9404     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9405     // may end up with different effective targets. Instead, a
9406     // specialization inherits its target attributes from its template
9407     // in the CheckFunctionTemplateSpecialization() call below.
9408     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9409       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9410 
9411     // If it's a friend (and only if it's a friend), it's possible
9412     // that either the specialized function type or the specialized
9413     // template is dependent, and therefore matching will fail.  In
9414     // this case, don't check the specialization yet.
9415     bool InstantiationDependent = false;
9416     if (isFunctionTemplateSpecialization && isFriend &&
9417         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9418          TemplateSpecializationType::anyDependentTemplateArguments(
9419             TemplateArgs,
9420             InstantiationDependent))) {
9421       assert(HasExplicitTemplateArgs &&
9422              "friend function specialization without template args");
9423       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9424                                                        Previous))
9425         NewFD->setInvalidDecl();
9426     } else if (isFunctionTemplateSpecialization) {
9427       if (CurContext->isDependentContext() && CurContext->isRecord()
9428           && !isFriend) {
9429         isDependentClassScopeExplicitSpecialization = true;
9430       } else if (!NewFD->isInvalidDecl() &&
9431                  CheckFunctionTemplateSpecialization(
9432                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9433                      Previous))
9434         NewFD->setInvalidDecl();
9435 
9436       // C++ [dcl.stc]p1:
9437       //   A storage-class-specifier shall not be specified in an explicit
9438       //   specialization (14.7.3)
9439       FunctionTemplateSpecializationInfo *Info =
9440           NewFD->getTemplateSpecializationInfo();
9441       if (Info && SC != SC_None) {
9442         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9443           Diag(NewFD->getLocation(),
9444                diag::err_explicit_specialization_inconsistent_storage_class)
9445             << SC
9446             << FixItHint::CreateRemoval(
9447                                       D.getDeclSpec().getStorageClassSpecLoc());
9448 
9449         else
9450           Diag(NewFD->getLocation(),
9451                diag::ext_explicit_specialization_storage_class)
9452             << FixItHint::CreateRemoval(
9453                                       D.getDeclSpec().getStorageClassSpecLoc());
9454       }
9455     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9456       if (CheckMemberSpecialization(NewFD, Previous))
9457           NewFD->setInvalidDecl();
9458     }
9459 
9460     // Perform semantic checking on the function declaration.
9461     if (!isDependentClassScopeExplicitSpecialization) {
9462       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9463         CheckMain(NewFD, D.getDeclSpec());
9464 
9465       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9466         CheckMSVCRTEntryPoint(NewFD);
9467 
9468       if (!NewFD->isInvalidDecl())
9469         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9470                                                     isMemberSpecialization));
9471       else if (!Previous.empty())
9472         // Recover gracefully from an invalid redeclaration.
9473         D.setRedeclaration(true);
9474     }
9475 
9476     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9477             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9478            "previous declaration set still overloaded");
9479 
9480     NamedDecl *PrincipalDecl = (FunctionTemplate
9481                                 ? cast<NamedDecl>(FunctionTemplate)
9482                                 : NewFD);
9483 
9484     if (isFriend && NewFD->getPreviousDecl()) {
9485       AccessSpecifier Access = AS_public;
9486       if (!NewFD->isInvalidDecl())
9487         Access = NewFD->getPreviousDecl()->getAccess();
9488 
9489       NewFD->setAccess(Access);
9490       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9491     }
9492 
9493     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9494         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9495       PrincipalDecl->setNonMemberOperator();
9496 
9497     // If we have a function template, check the template parameter
9498     // list. This will check and merge default template arguments.
9499     if (FunctionTemplate) {
9500       FunctionTemplateDecl *PrevTemplate =
9501                                      FunctionTemplate->getPreviousDecl();
9502       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9503                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9504                                     : nullptr,
9505                             D.getDeclSpec().isFriendSpecified()
9506                               ? (D.isFunctionDefinition()
9507                                    ? TPC_FriendFunctionTemplateDefinition
9508                                    : TPC_FriendFunctionTemplate)
9509                               : (D.getCXXScopeSpec().isSet() &&
9510                                  DC && DC->isRecord() &&
9511                                  DC->isDependentContext())
9512                                   ? TPC_ClassTemplateMember
9513                                   : TPC_FunctionTemplate);
9514     }
9515 
9516     if (NewFD->isInvalidDecl()) {
9517       // Ignore all the rest of this.
9518     } else if (!D.isRedeclaration()) {
9519       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9520                                        AddToScope };
9521       // Fake up an access specifier if it's supposed to be a class member.
9522       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9523         NewFD->setAccess(AS_public);
9524 
9525       // Qualified decls generally require a previous declaration.
9526       if (D.getCXXScopeSpec().isSet()) {
9527         // ...with the major exception of templated-scope or
9528         // dependent-scope friend declarations.
9529 
9530         // TODO: we currently also suppress this check in dependent
9531         // contexts because (1) the parameter depth will be off when
9532         // matching friend templates and (2) we might actually be
9533         // selecting a friend based on a dependent factor.  But there
9534         // are situations where these conditions don't apply and we
9535         // can actually do this check immediately.
9536         //
9537         // Unless the scope is dependent, it's always an error if qualified
9538         // redeclaration lookup found nothing at all. Diagnose that now;
9539         // nothing will diagnose that error later.
9540         if (isFriend &&
9541             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9542              (!Previous.empty() && CurContext->isDependentContext()))) {
9543           // ignore these
9544         } else {
9545           // The user tried to provide an out-of-line definition for a
9546           // function that is a member of a class or namespace, but there
9547           // was no such member function declared (C++ [class.mfct]p2,
9548           // C++ [namespace.memdef]p2). For example:
9549           //
9550           // class X {
9551           //   void f() const;
9552           // };
9553           //
9554           // void X::f() { } // ill-formed
9555           //
9556           // Complain about this problem, and attempt to suggest close
9557           // matches (e.g., those that differ only in cv-qualifiers and
9558           // whether the parameter types are references).
9559 
9560           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9561                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9562             AddToScope = ExtraArgs.AddToScope;
9563             return Result;
9564           }
9565         }
9566 
9567         // Unqualified local friend declarations are required to resolve
9568         // to something.
9569       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9570         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9571                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9572           AddToScope = ExtraArgs.AddToScope;
9573           return Result;
9574         }
9575       }
9576     } else if (!D.isFunctionDefinition() &&
9577                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9578                !isFriend && !isFunctionTemplateSpecialization &&
9579                !isMemberSpecialization) {
9580       // An out-of-line member function declaration must also be a
9581       // definition (C++ [class.mfct]p2).
9582       // Note that this is not the case for explicit specializations of
9583       // function templates or member functions of class templates, per
9584       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9585       // extension for compatibility with old SWIG code which likes to
9586       // generate them.
9587       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9588         << D.getCXXScopeSpec().getRange();
9589     }
9590   }
9591 
9592   ProcessPragmaWeak(S, NewFD);
9593   checkAttributesAfterMerging(*this, *NewFD);
9594 
9595   AddKnownFunctionAttributes(NewFD);
9596 
9597   if (NewFD->hasAttr<OverloadableAttr>() &&
9598       !NewFD->getType()->getAs<FunctionProtoType>()) {
9599     Diag(NewFD->getLocation(),
9600          diag::err_attribute_overloadable_no_prototype)
9601       << NewFD;
9602 
9603     // Turn this into a variadic function with no parameters.
9604     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9605     FunctionProtoType::ExtProtoInfo EPI(
9606         Context.getDefaultCallingConvention(true, false));
9607     EPI.Variadic = true;
9608     EPI.ExtInfo = FT->getExtInfo();
9609 
9610     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9611     NewFD->setType(R);
9612   }
9613 
9614   // If there's a #pragma GCC visibility in scope, and this isn't a class
9615   // member, set the visibility of this function.
9616   if (!DC->isRecord() && NewFD->isExternallyVisible())
9617     AddPushedVisibilityAttribute(NewFD);
9618 
9619   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9620   // marking the function.
9621   AddCFAuditedAttribute(NewFD);
9622 
9623   // If this is a function definition, check if we have to apply optnone due to
9624   // a pragma.
9625   if(D.isFunctionDefinition())
9626     AddRangeBasedOptnone(NewFD);
9627 
9628   // If this is the first declaration of an extern C variable, update
9629   // the map of such variables.
9630   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9631       isIncompleteDeclExternC(*this, NewFD))
9632     RegisterLocallyScopedExternCDecl(NewFD, S);
9633 
9634   // Set this FunctionDecl's range up to the right paren.
9635   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9636 
9637   if (D.isRedeclaration() && !Previous.empty()) {
9638     NamedDecl *Prev = Previous.getRepresentativeDecl();
9639     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9640                                    isMemberSpecialization ||
9641                                        isFunctionTemplateSpecialization,
9642                                    D.isFunctionDefinition());
9643   }
9644 
9645   if (getLangOpts().CUDA) {
9646     IdentifierInfo *II = NewFD->getIdentifier();
9647     if (II && II->isStr(getCudaConfigureFuncName()) &&
9648         !NewFD->isInvalidDecl() &&
9649         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9650       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9651         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9652             << getCudaConfigureFuncName();
9653       Context.setcudaConfigureCallDecl(NewFD);
9654     }
9655 
9656     // Variadic functions, other than a *declaration* of printf, are not allowed
9657     // in device-side CUDA code, unless someone passed
9658     // -fcuda-allow-variadic-functions.
9659     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9660         (NewFD->hasAttr<CUDADeviceAttr>() ||
9661          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9662         !(II && II->isStr("printf") && NewFD->isExternC() &&
9663           !D.isFunctionDefinition())) {
9664       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9665     }
9666   }
9667 
9668   MarkUnusedFileScopedDecl(NewFD);
9669 
9670 
9671 
9672   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9673     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9674     if ((getLangOpts().OpenCLVersion >= 120)
9675         && (SC == SC_Static)) {
9676       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9677       D.setInvalidType();
9678     }
9679 
9680     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9681     if (!NewFD->getReturnType()->isVoidType()) {
9682       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9683       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9684           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9685                                 : FixItHint());
9686       D.setInvalidType();
9687     }
9688 
9689     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9690     for (auto Param : NewFD->parameters())
9691       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9692 
9693     if (getLangOpts().OpenCLCPlusPlus) {
9694       if (DC->isRecord()) {
9695         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9696         D.setInvalidType();
9697       }
9698       if (FunctionTemplate) {
9699         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9700         D.setInvalidType();
9701       }
9702     }
9703   }
9704 
9705   if (getLangOpts().CPlusPlus) {
9706     if (FunctionTemplate) {
9707       if (NewFD->isInvalidDecl())
9708         FunctionTemplate->setInvalidDecl();
9709       return FunctionTemplate;
9710     }
9711 
9712     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9713       CompleteMemberSpecialization(NewFD, Previous);
9714   }
9715 
9716   for (const ParmVarDecl *Param : NewFD->parameters()) {
9717     QualType PT = Param->getType();
9718 
9719     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9720     // types.
9721     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9722       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9723         QualType ElemTy = PipeTy->getElementType();
9724           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9725             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9726             D.setInvalidType();
9727           }
9728       }
9729     }
9730   }
9731 
9732   // Here we have an function template explicit specialization at class scope.
9733   // The actual specialization will be postponed to template instatiation
9734   // time via the ClassScopeFunctionSpecializationDecl node.
9735   if (isDependentClassScopeExplicitSpecialization) {
9736     ClassScopeFunctionSpecializationDecl *NewSpec =
9737                          ClassScopeFunctionSpecializationDecl::Create(
9738                                 Context, CurContext, NewFD->getLocation(),
9739                                 cast<CXXMethodDecl>(NewFD),
9740                                 HasExplicitTemplateArgs, TemplateArgs);
9741     CurContext->addDecl(NewSpec);
9742     AddToScope = false;
9743   }
9744 
9745   // Diagnose availability attributes. Availability cannot be used on functions
9746   // that are run during load/unload.
9747   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9748     if (NewFD->hasAttr<ConstructorAttr>()) {
9749       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9750           << 1;
9751       NewFD->dropAttr<AvailabilityAttr>();
9752     }
9753     if (NewFD->hasAttr<DestructorAttr>()) {
9754       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9755           << 2;
9756       NewFD->dropAttr<AvailabilityAttr>();
9757     }
9758   }
9759 
9760   // Diagnose no_builtin attribute on function declaration that are not a
9761   // definition.
9762   // FIXME: We should really be doing this in
9763   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9764   // the FunctionDecl and at this point of the code
9765   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9766   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9767   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9768     switch (D.getFunctionDefinitionKind()) {
9769     case FDK_Defaulted:
9770     case FDK_Deleted:
9771       Diag(NBA->getLocation(),
9772            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9773           << NBA->getSpelling();
9774       break;
9775     case FDK_Declaration:
9776       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9777           << NBA->getSpelling();
9778       break;
9779     case FDK_Definition:
9780       break;
9781     }
9782 
9783   return NewFD;
9784 }
9785 
9786 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9787 /// when __declspec(code_seg) "is applied to a class, all member functions of
9788 /// the class and nested classes -- this includes compiler-generated special
9789 /// member functions -- are put in the specified segment."
9790 /// The actual behavior is a little more complicated. The Microsoft compiler
9791 /// won't check outer classes if there is an active value from #pragma code_seg.
9792 /// The CodeSeg is always applied from the direct parent but only from outer
9793 /// classes when the #pragma code_seg stack is empty. See:
9794 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9795 /// available since MS has removed the page.
9796 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9797   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9798   if (!Method)
9799     return nullptr;
9800   const CXXRecordDecl *Parent = Method->getParent();
9801   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9802     Attr *NewAttr = SAttr->clone(S.getASTContext());
9803     NewAttr->setImplicit(true);
9804     return NewAttr;
9805   }
9806 
9807   // The Microsoft compiler won't check outer classes for the CodeSeg
9808   // when the #pragma code_seg stack is active.
9809   if (S.CodeSegStack.CurrentValue)
9810    return nullptr;
9811 
9812   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9813     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9814       Attr *NewAttr = SAttr->clone(S.getASTContext());
9815       NewAttr->setImplicit(true);
9816       return NewAttr;
9817     }
9818   }
9819   return nullptr;
9820 }
9821 
9822 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9823 /// containing class. Otherwise it will return implicit SectionAttr if the
9824 /// function is a definition and there is an active value on CodeSegStack
9825 /// (from the current #pragma code-seg value).
9826 ///
9827 /// \param FD Function being declared.
9828 /// \param IsDefinition Whether it is a definition or just a declarartion.
9829 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9830 ///          nullptr if no attribute should be added.
9831 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9832                                                        bool IsDefinition) {
9833   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9834     return A;
9835   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9836       CodeSegStack.CurrentValue)
9837     return SectionAttr::CreateImplicit(
9838         getASTContext(), CodeSegStack.CurrentValue->getString(),
9839         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9840         SectionAttr::Declspec_allocate);
9841   return nullptr;
9842 }
9843 
9844 /// Determines if we can perform a correct type check for \p D as a
9845 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9846 /// best-effort check.
9847 ///
9848 /// \param NewD The new declaration.
9849 /// \param OldD The old declaration.
9850 /// \param NewT The portion of the type of the new declaration to check.
9851 /// \param OldT The portion of the type of the old declaration to check.
9852 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9853                                           QualType NewT, QualType OldT) {
9854   if (!NewD->getLexicalDeclContext()->isDependentContext())
9855     return true;
9856 
9857   // For dependently-typed local extern declarations and friends, we can't
9858   // perform a correct type check in general until instantiation:
9859   //
9860   //   int f();
9861   //   template<typename T> void g() { T f(); }
9862   //
9863   // (valid if g() is only instantiated with T = int).
9864   if (NewT->isDependentType() &&
9865       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9866     return false;
9867 
9868   // Similarly, if the previous declaration was a dependent local extern
9869   // declaration, we don't really know its type yet.
9870   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9871     return false;
9872 
9873   return true;
9874 }
9875 
9876 /// Checks if the new declaration declared in dependent context must be
9877 /// put in the same redeclaration chain as the specified declaration.
9878 ///
9879 /// \param D Declaration that is checked.
9880 /// \param PrevDecl Previous declaration found with proper lookup method for the
9881 ///                 same declaration name.
9882 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9883 ///          belongs to.
9884 ///
9885 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9886   if (!D->getLexicalDeclContext()->isDependentContext())
9887     return true;
9888 
9889   // Don't chain dependent friend function definitions until instantiation, to
9890   // permit cases like
9891   //
9892   //   void func();
9893   //   template<typename T> class C1 { friend void func() {} };
9894   //   template<typename T> class C2 { friend void func() {} };
9895   //
9896   // ... which is valid if only one of C1 and C2 is ever instantiated.
9897   //
9898   // FIXME: This need only apply to function definitions. For now, we proxy
9899   // this by checking for a file-scope function. We do not want this to apply
9900   // to friend declarations nominating member functions, because that gets in
9901   // the way of access checks.
9902   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9903     return false;
9904 
9905   auto *VD = dyn_cast<ValueDecl>(D);
9906   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9907   return !VD || !PrevVD ||
9908          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9909                                         PrevVD->getType());
9910 }
9911 
9912 /// Check the target attribute of the function for MultiVersion
9913 /// validity.
9914 ///
9915 /// Returns true if there was an error, false otherwise.
9916 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9917   const auto *TA = FD->getAttr<TargetAttr>();
9918   assert(TA && "MultiVersion Candidate requires a target attribute");
9919   ParsedTargetAttr ParseInfo = TA->parse();
9920   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9921   enum ErrType { Feature = 0, Architecture = 1 };
9922 
9923   if (!ParseInfo.Architecture.empty() &&
9924       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9925     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9926         << Architecture << ParseInfo.Architecture;
9927     return true;
9928   }
9929 
9930   for (const auto &Feat : ParseInfo.Features) {
9931     auto BareFeat = StringRef{Feat}.substr(1);
9932     if (Feat[0] == '-') {
9933       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9934           << Feature << ("no-" + BareFeat).str();
9935       return true;
9936     }
9937 
9938     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9939         !TargetInfo.isValidFeatureName(BareFeat)) {
9940       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9941           << Feature << BareFeat;
9942       return true;
9943     }
9944   }
9945   return false;
9946 }
9947 
9948 // Provide a white-list of attributes that are allowed to be combined with
9949 // multiversion functions.
9950 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
9951                                            MultiVersionKind MVType) {
9952   switch (Kind) {
9953   default:
9954     return false;
9955   case attr::Used:
9956     return MVType == MultiVersionKind::Target;
9957   }
9958 }
9959 
9960 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9961                                          MultiVersionKind MVType) {
9962   for (const Attr *A : FD->attrs()) {
9963     switch (A->getKind()) {
9964     case attr::CPUDispatch:
9965     case attr::CPUSpecific:
9966       if (MVType != MultiVersionKind::CPUDispatch &&
9967           MVType != MultiVersionKind::CPUSpecific)
9968         return true;
9969       break;
9970     case attr::Target:
9971       if (MVType != MultiVersionKind::Target)
9972         return true;
9973       break;
9974     default:
9975       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
9976         return true;
9977       break;
9978     }
9979   }
9980   return false;
9981 }
9982 
9983 bool Sema::areMultiversionVariantFunctionsCompatible(
9984     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9985     const PartialDiagnostic &NoProtoDiagID,
9986     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9987     const PartialDiagnosticAt &NoSupportDiagIDAt,
9988     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9989     bool ConstexprSupported, bool CLinkageMayDiffer) {
9990   enum DoesntSupport {
9991     FuncTemplates = 0,
9992     VirtFuncs = 1,
9993     DeducedReturn = 2,
9994     Constructors = 3,
9995     Destructors = 4,
9996     DeletedFuncs = 5,
9997     DefaultedFuncs = 6,
9998     ConstexprFuncs = 7,
9999     ConstevalFuncs = 8,
10000   };
10001   enum Different {
10002     CallingConv = 0,
10003     ReturnType = 1,
10004     ConstexprSpec = 2,
10005     InlineSpec = 3,
10006     StorageClass = 4,
10007     Linkage = 5,
10008   };
10009 
10010   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10011       !OldFD->getType()->getAs<FunctionProtoType>()) {
10012     Diag(OldFD->getLocation(), NoProtoDiagID);
10013     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10014     return true;
10015   }
10016 
10017   if (NoProtoDiagID.getDiagID() != 0 &&
10018       !NewFD->getType()->getAs<FunctionProtoType>())
10019     return Diag(NewFD->getLocation(), NoProtoDiagID);
10020 
10021   if (!TemplatesSupported &&
10022       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10023     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10024            << FuncTemplates;
10025 
10026   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10027     if (NewCXXFD->isVirtual())
10028       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10029              << VirtFuncs;
10030 
10031     if (isa<CXXConstructorDecl>(NewCXXFD))
10032       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10033              << Constructors;
10034 
10035     if (isa<CXXDestructorDecl>(NewCXXFD))
10036       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10037              << Destructors;
10038   }
10039 
10040   if (NewFD->isDeleted())
10041     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10042            << DeletedFuncs;
10043 
10044   if (NewFD->isDefaulted())
10045     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10046            << DefaultedFuncs;
10047 
10048   if (!ConstexprSupported && NewFD->isConstexpr())
10049     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10050            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10051 
10052   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10053   const auto *NewType = cast<FunctionType>(NewQType);
10054   QualType NewReturnType = NewType->getReturnType();
10055 
10056   if (NewReturnType->isUndeducedType())
10057     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10058            << DeducedReturn;
10059 
10060   // Ensure the return type is identical.
10061   if (OldFD) {
10062     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10063     const auto *OldType = cast<FunctionType>(OldQType);
10064     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10065     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10066 
10067     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10068       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10069 
10070     QualType OldReturnType = OldType->getReturnType();
10071 
10072     if (OldReturnType != NewReturnType)
10073       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10074 
10075     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10076       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10077 
10078     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10079       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10080 
10081     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10082       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10083 
10084     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10085       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10086 
10087     if (CheckEquivalentExceptionSpec(
10088             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10089             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10090       return true;
10091   }
10092   return false;
10093 }
10094 
10095 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10096                                              const FunctionDecl *NewFD,
10097                                              bool CausesMV,
10098                                              MultiVersionKind MVType) {
10099   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10100     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10101     if (OldFD)
10102       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10103     return true;
10104   }
10105 
10106   bool IsCPUSpecificCPUDispatchMVType =
10107       MVType == MultiVersionKind::CPUDispatch ||
10108       MVType == MultiVersionKind::CPUSpecific;
10109 
10110   // For now, disallow all other attributes.  These should be opt-in, but
10111   // an analysis of all of them is a future FIXME.
10112   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
10113     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
10114         << IsCPUSpecificCPUDispatchMVType;
10115     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10116     return true;
10117   }
10118 
10119   if (HasNonMultiVersionAttributes(NewFD, MVType))
10120     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10121            << IsCPUSpecificCPUDispatchMVType;
10122 
10123   // Only allow transition to MultiVersion if it hasn't been used.
10124   if (OldFD && CausesMV && OldFD->isUsed(false))
10125     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10126 
10127   return S.areMultiversionVariantFunctionsCompatible(
10128       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10129       PartialDiagnosticAt(NewFD->getLocation(),
10130                           S.PDiag(diag::note_multiversioning_caused_here)),
10131       PartialDiagnosticAt(NewFD->getLocation(),
10132                           S.PDiag(diag::err_multiversion_doesnt_support)
10133                               << IsCPUSpecificCPUDispatchMVType),
10134       PartialDiagnosticAt(NewFD->getLocation(),
10135                           S.PDiag(diag::err_multiversion_diff)),
10136       /*TemplatesSupported=*/false,
10137       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10138       /*CLinkageMayDiffer=*/false);
10139 }
10140 
10141 /// Check the validity of a multiversion function declaration that is the
10142 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10143 ///
10144 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10145 ///
10146 /// Returns true if there was an error, false otherwise.
10147 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10148                                            MultiVersionKind MVType,
10149                                            const TargetAttr *TA) {
10150   assert(MVType != MultiVersionKind::None &&
10151          "Function lacks multiversion attribute");
10152 
10153   // Target only causes MV if it is default, otherwise this is a normal
10154   // function.
10155   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10156     return false;
10157 
10158   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10159     FD->setInvalidDecl();
10160     return true;
10161   }
10162 
10163   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10164     FD->setInvalidDecl();
10165     return true;
10166   }
10167 
10168   FD->setIsMultiVersion();
10169   return false;
10170 }
10171 
10172 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10173   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10174     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10175       return true;
10176   }
10177 
10178   return false;
10179 }
10180 
10181 static bool CheckTargetCausesMultiVersioning(
10182     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10183     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10184     LookupResult &Previous) {
10185   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10186   ParsedTargetAttr NewParsed = NewTA->parse();
10187   // Sort order doesn't matter, it just needs to be consistent.
10188   llvm::sort(NewParsed.Features);
10189 
10190   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10191   // to change, this is a simple redeclaration.
10192   if (!NewTA->isDefaultVersion() &&
10193       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10194     return false;
10195 
10196   // Otherwise, this decl causes MultiVersioning.
10197   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10198     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10199     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10200     NewFD->setInvalidDecl();
10201     return true;
10202   }
10203 
10204   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10205                                        MultiVersionKind::Target)) {
10206     NewFD->setInvalidDecl();
10207     return true;
10208   }
10209 
10210   if (CheckMultiVersionValue(S, NewFD)) {
10211     NewFD->setInvalidDecl();
10212     return true;
10213   }
10214 
10215   // If this is 'default', permit the forward declaration.
10216   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10217     Redeclaration = true;
10218     OldDecl = OldFD;
10219     OldFD->setIsMultiVersion();
10220     NewFD->setIsMultiVersion();
10221     return false;
10222   }
10223 
10224   if (CheckMultiVersionValue(S, OldFD)) {
10225     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10226     NewFD->setInvalidDecl();
10227     return true;
10228   }
10229 
10230   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10231 
10232   if (OldParsed == NewParsed) {
10233     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10234     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10235     NewFD->setInvalidDecl();
10236     return true;
10237   }
10238 
10239   for (const auto *FD : OldFD->redecls()) {
10240     const auto *CurTA = FD->getAttr<TargetAttr>();
10241     // We allow forward declarations before ANY multiversioning attributes, but
10242     // nothing after the fact.
10243     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10244         (!CurTA || CurTA->isInherited())) {
10245       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10246           << 0;
10247       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10248       NewFD->setInvalidDecl();
10249       return true;
10250     }
10251   }
10252 
10253   OldFD->setIsMultiVersion();
10254   NewFD->setIsMultiVersion();
10255   Redeclaration = false;
10256   MergeTypeWithPrevious = false;
10257   OldDecl = nullptr;
10258   Previous.clear();
10259   return false;
10260 }
10261 
10262 /// Check the validity of a new function declaration being added to an existing
10263 /// multiversioned declaration collection.
10264 static bool CheckMultiVersionAdditionalDecl(
10265     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10266     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10267     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10268     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10269     LookupResult &Previous) {
10270 
10271   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10272   // Disallow mixing of multiversioning types.
10273   if ((OldMVType == MultiVersionKind::Target &&
10274        NewMVType != MultiVersionKind::Target) ||
10275       (NewMVType == MultiVersionKind::Target &&
10276        OldMVType != MultiVersionKind::Target)) {
10277     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10278     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10279     NewFD->setInvalidDecl();
10280     return true;
10281   }
10282 
10283   ParsedTargetAttr NewParsed;
10284   if (NewTA) {
10285     NewParsed = NewTA->parse();
10286     llvm::sort(NewParsed.Features);
10287   }
10288 
10289   bool UseMemberUsingDeclRules =
10290       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10291 
10292   // Next, check ALL non-overloads to see if this is a redeclaration of a
10293   // previous member of the MultiVersion set.
10294   for (NamedDecl *ND : Previous) {
10295     FunctionDecl *CurFD = ND->getAsFunction();
10296     if (!CurFD)
10297       continue;
10298     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10299       continue;
10300 
10301     if (NewMVType == MultiVersionKind::Target) {
10302       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10303       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10304         NewFD->setIsMultiVersion();
10305         Redeclaration = true;
10306         OldDecl = ND;
10307         return false;
10308       }
10309 
10310       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10311       if (CurParsed == NewParsed) {
10312         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10313         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10314         NewFD->setInvalidDecl();
10315         return true;
10316       }
10317     } else {
10318       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10319       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10320       // Handle CPUDispatch/CPUSpecific versions.
10321       // Only 1 CPUDispatch function is allowed, this will make it go through
10322       // the redeclaration errors.
10323       if (NewMVType == MultiVersionKind::CPUDispatch &&
10324           CurFD->hasAttr<CPUDispatchAttr>()) {
10325         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10326             std::equal(
10327                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10328                 NewCPUDisp->cpus_begin(),
10329                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10330                   return Cur->getName() == New->getName();
10331                 })) {
10332           NewFD->setIsMultiVersion();
10333           Redeclaration = true;
10334           OldDecl = ND;
10335           return false;
10336         }
10337 
10338         // If the declarations don't match, this is an error condition.
10339         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10340         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10341         NewFD->setInvalidDecl();
10342         return true;
10343       }
10344       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10345 
10346         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10347             std::equal(
10348                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10349                 NewCPUSpec->cpus_begin(),
10350                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10351                   return Cur->getName() == New->getName();
10352                 })) {
10353           NewFD->setIsMultiVersion();
10354           Redeclaration = true;
10355           OldDecl = ND;
10356           return false;
10357         }
10358 
10359         // Only 1 version of CPUSpecific is allowed for each CPU.
10360         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10361           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10362             if (CurII == NewII) {
10363               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10364                   << NewII;
10365               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10366               NewFD->setInvalidDecl();
10367               return true;
10368             }
10369           }
10370         }
10371       }
10372       // If the two decls aren't the same MVType, there is no possible error
10373       // condition.
10374     }
10375   }
10376 
10377   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10378   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10379   // handled in the attribute adding step.
10380   if (NewMVType == MultiVersionKind::Target &&
10381       CheckMultiVersionValue(S, NewFD)) {
10382     NewFD->setInvalidDecl();
10383     return true;
10384   }
10385 
10386   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10387                                        !OldFD->isMultiVersion(), NewMVType)) {
10388     NewFD->setInvalidDecl();
10389     return true;
10390   }
10391 
10392   // Permit forward declarations in the case where these two are compatible.
10393   if (!OldFD->isMultiVersion()) {
10394     OldFD->setIsMultiVersion();
10395     NewFD->setIsMultiVersion();
10396     Redeclaration = true;
10397     OldDecl = OldFD;
10398     return false;
10399   }
10400 
10401   NewFD->setIsMultiVersion();
10402   Redeclaration = false;
10403   MergeTypeWithPrevious = false;
10404   OldDecl = nullptr;
10405   Previous.clear();
10406   return false;
10407 }
10408 
10409 
10410 /// Check the validity of a mulitversion function declaration.
10411 /// Also sets the multiversion'ness' of the function itself.
10412 ///
10413 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10414 ///
10415 /// Returns true if there was an error, false otherwise.
10416 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10417                                       bool &Redeclaration, NamedDecl *&OldDecl,
10418                                       bool &MergeTypeWithPrevious,
10419                                       LookupResult &Previous) {
10420   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10421   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10422   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10423 
10424   // Mixing Multiversioning types is prohibited.
10425   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10426       (NewCPUDisp && NewCPUSpec)) {
10427     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10428     NewFD->setInvalidDecl();
10429     return true;
10430   }
10431 
10432   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10433 
10434   // Main isn't allowed to become a multiversion function, however it IS
10435   // permitted to have 'main' be marked with the 'target' optimization hint.
10436   if (NewFD->isMain()) {
10437     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10438         MVType == MultiVersionKind::CPUDispatch ||
10439         MVType == MultiVersionKind::CPUSpecific) {
10440       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10441       NewFD->setInvalidDecl();
10442       return true;
10443     }
10444     return false;
10445   }
10446 
10447   if (!OldDecl || !OldDecl->getAsFunction() ||
10448       OldDecl->getDeclContext()->getRedeclContext() !=
10449           NewFD->getDeclContext()->getRedeclContext()) {
10450     // If there's no previous declaration, AND this isn't attempting to cause
10451     // multiversioning, this isn't an error condition.
10452     if (MVType == MultiVersionKind::None)
10453       return false;
10454     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10455   }
10456 
10457   FunctionDecl *OldFD = OldDecl->getAsFunction();
10458 
10459   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10460     return false;
10461 
10462   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10463     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10464         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10465     NewFD->setInvalidDecl();
10466     return true;
10467   }
10468 
10469   // Handle the target potentially causes multiversioning case.
10470   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10471     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10472                                             Redeclaration, OldDecl,
10473                                             MergeTypeWithPrevious, Previous);
10474 
10475   // At this point, we have a multiversion function decl (in OldFD) AND an
10476   // appropriate attribute in the current function decl.  Resolve that these are
10477   // still compatible with previous declarations.
10478   return CheckMultiVersionAdditionalDecl(
10479       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10480       OldDecl, MergeTypeWithPrevious, Previous);
10481 }
10482 
10483 /// Perform semantic checking of a new function declaration.
10484 ///
10485 /// Performs semantic analysis of the new function declaration
10486 /// NewFD. This routine performs all semantic checking that does not
10487 /// require the actual declarator involved in the declaration, and is
10488 /// used both for the declaration of functions as they are parsed
10489 /// (called via ActOnDeclarator) and for the declaration of functions
10490 /// that have been instantiated via C++ template instantiation (called
10491 /// via InstantiateDecl).
10492 ///
10493 /// \param IsMemberSpecialization whether this new function declaration is
10494 /// a member specialization (that replaces any definition provided by the
10495 /// previous declaration).
10496 ///
10497 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10498 ///
10499 /// \returns true if the function declaration is a redeclaration.
10500 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10501                                     LookupResult &Previous,
10502                                     bool IsMemberSpecialization) {
10503   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10504          "Variably modified return types are not handled here");
10505 
10506   // Determine whether the type of this function should be merged with
10507   // a previous visible declaration. This never happens for functions in C++,
10508   // and always happens in C if the previous declaration was visible.
10509   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10510                                !Previous.isShadowed();
10511 
10512   bool Redeclaration = false;
10513   NamedDecl *OldDecl = nullptr;
10514   bool MayNeedOverloadableChecks = false;
10515 
10516   // Merge or overload the declaration with an existing declaration of
10517   // the same name, if appropriate.
10518   if (!Previous.empty()) {
10519     // Determine whether NewFD is an overload of PrevDecl or
10520     // a declaration that requires merging. If it's an overload,
10521     // there's no more work to do here; we'll just add the new
10522     // function to the scope.
10523     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10524       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10525       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10526         Redeclaration = true;
10527         OldDecl = Candidate;
10528       }
10529     } else {
10530       MayNeedOverloadableChecks = true;
10531       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10532                             /*NewIsUsingDecl*/ false)) {
10533       case Ovl_Match:
10534         Redeclaration = true;
10535         break;
10536 
10537       case Ovl_NonFunction:
10538         Redeclaration = true;
10539         break;
10540 
10541       case Ovl_Overload:
10542         Redeclaration = false;
10543         break;
10544       }
10545     }
10546   }
10547 
10548   // Check for a previous extern "C" declaration with this name.
10549   if (!Redeclaration &&
10550       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10551     if (!Previous.empty()) {
10552       // This is an extern "C" declaration with the same name as a previous
10553       // declaration, and thus redeclares that entity...
10554       Redeclaration = true;
10555       OldDecl = Previous.getFoundDecl();
10556       MergeTypeWithPrevious = false;
10557 
10558       // ... except in the presence of __attribute__((overloadable)).
10559       if (OldDecl->hasAttr<OverloadableAttr>() ||
10560           NewFD->hasAttr<OverloadableAttr>()) {
10561         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10562           MayNeedOverloadableChecks = true;
10563           Redeclaration = false;
10564           OldDecl = nullptr;
10565         }
10566       }
10567     }
10568   }
10569 
10570   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10571                                 MergeTypeWithPrevious, Previous))
10572     return Redeclaration;
10573 
10574   // C++11 [dcl.constexpr]p8:
10575   //   A constexpr specifier for a non-static member function that is not
10576   //   a constructor declares that member function to be const.
10577   //
10578   // This needs to be delayed until we know whether this is an out-of-line
10579   // definition of a static member function.
10580   //
10581   // This rule is not present in C++1y, so we produce a backwards
10582   // compatibility warning whenever it happens in C++11.
10583   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10584   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10585       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10586       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10587     CXXMethodDecl *OldMD = nullptr;
10588     if (OldDecl)
10589       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10590     if (!OldMD || !OldMD->isStatic()) {
10591       const FunctionProtoType *FPT =
10592         MD->getType()->castAs<FunctionProtoType>();
10593       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10594       EPI.TypeQuals.addConst();
10595       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10596                                           FPT->getParamTypes(), EPI));
10597 
10598       // Warn that we did this, if we're not performing template instantiation.
10599       // In that case, we'll have warned already when the template was defined.
10600       if (!inTemplateInstantiation()) {
10601         SourceLocation AddConstLoc;
10602         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10603                 .IgnoreParens().getAs<FunctionTypeLoc>())
10604           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10605 
10606         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10607           << FixItHint::CreateInsertion(AddConstLoc, " const");
10608       }
10609     }
10610   }
10611 
10612   if (Redeclaration) {
10613     // NewFD and OldDecl represent declarations that need to be
10614     // merged.
10615     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10616       NewFD->setInvalidDecl();
10617       return Redeclaration;
10618     }
10619 
10620     Previous.clear();
10621     Previous.addDecl(OldDecl);
10622 
10623     if (FunctionTemplateDecl *OldTemplateDecl =
10624             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10625       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10626       FunctionTemplateDecl *NewTemplateDecl
10627         = NewFD->getDescribedFunctionTemplate();
10628       assert(NewTemplateDecl && "Template/non-template mismatch");
10629 
10630       // The call to MergeFunctionDecl above may have created some state in
10631       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10632       // can add it as a redeclaration.
10633       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10634 
10635       NewFD->setPreviousDeclaration(OldFD);
10636       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10637       if (NewFD->isCXXClassMember()) {
10638         NewFD->setAccess(OldTemplateDecl->getAccess());
10639         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10640       }
10641 
10642       // If this is an explicit specialization of a member that is a function
10643       // template, mark it as a member specialization.
10644       if (IsMemberSpecialization &&
10645           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10646         NewTemplateDecl->setMemberSpecialization();
10647         assert(OldTemplateDecl->isMemberSpecialization());
10648         // Explicit specializations of a member template do not inherit deleted
10649         // status from the parent member template that they are specializing.
10650         if (OldFD->isDeleted()) {
10651           // FIXME: This assert will not hold in the presence of modules.
10652           assert(OldFD->getCanonicalDecl() == OldFD);
10653           // FIXME: We need an update record for this AST mutation.
10654           OldFD->setDeletedAsWritten(false);
10655         }
10656       }
10657 
10658     } else {
10659       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10660         auto *OldFD = cast<FunctionDecl>(OldDecl);
10661         // This needs to happen first so that 'inline' propagates.
10662         NewFD->setPreviousDeclaration(OldFD);
10663         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10664         if (NewFD->isCXXClassMember())
10665           NewFD->setAccess(OldFD->getAccess());
10666       }
10667     }
10668   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10669              !NewFD->getAttr<OverloadableAttr>()) {
10670     assert((Previous.empty() ||
10671             llvm::any_of(Previous,
10672                          [](const NamedDecl *ND) {
10673                            return ND->hasAttr<OverloadableAttr>();
10674                          })) &&
10675            "Non-redecls shouldn't happen without overloadable present");
10676 
10677     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10678       const auto *FD = dyn_cast<FunctionDecl>(ND);
10679       return FD && !FD->hasAttr<OverloadableAttr>();
10680     });
10681 
10682     if (OtherUnmarkedIter != Previous.end()) {
10683       Diag(NewFD->getLocation(),
10684            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10685       Diag((*OtherUnmarkedIter)->getLocation(),
10686            diag::note_attribute_overloadable_prev_overload)
10687           << false;
10688 
10689       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10690     }
10691   }
10692 
10693   // Semantic checking for this function declaration (in isolation).
10694 
10695   if (getLangOpts().CPlusPlus) {
10696     // C++-specific checks.
10697     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10698       CheckConstructor(Constructor);
10699     } else if (CXXDestructorDecl *Destructor =
10700                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10701       CXXRecordDecl *Record = Destructor->getParent();
10702       QualType ClassType = Context.getTypeDeclType(Record);
10703 
10704       // FIXME: Shouldn't we be able to perform this check even when the class
10705       // type is dependent? Both gcc and edg can handle that.
10706       if (!ClassType->isDependentType()) {
10707         DeclarationName Name
10708           = Context.DeclarationNames.getCXXDestructorName(
10709                                         Context.getCanonicalType(ClassType));
10710         if (NewFD->getDeclName() != Name) {
10711           Diag(NewFD->getLocation(), diag::err_destructor_name);
10712           NewFD->setInvalidDecl();
10713           return Redeclaration;
10714         }
10715       }
10716     } else if (CXXConversionDecl *Conversion
10717                = dyn_cast<CXXConversionDecl>(NewFD)) {
10718       ActOnConversionDeclarator(Conversion);
10719     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10720       if (auto *TD = Guide->getDescribedFunctionTemplate())
10721         CheckDeductionGuideTemplate(TD);
10722 
10723       // A deduction guide is not on the list of entities that can be
10724       // explicitly specialized.
10725       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10726         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10727             << /*explicit specialization*/ 1;
10728     }
10729 
10730     // Find any virtual functions that this function overrides.
10731     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10732       if (!Method->isFunctionTemplateSpecialization() &&
10733           !Method->getDescribedFunctionTemplate() &&
10734           Method->isCanonicalDecl()) {
10735         AddOverriddenMethods(Method->getParent(), Method);
10736       }
10737       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10738         // C++2a [class.virtual]p6
10739         // A virtual method shall not have a requires-clause.
10740         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10741              diag::err_constrained_virtual_method);
10742 
10743       if (Method->isStatic())
10744         checkThisInStaticMemberFunctionType(Method);
10745     }
10746 
10747     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10748     if (NewFD->isOverloadedOperator() &&
10749         CheckOverloadedOperatorDeclaration(NewFD)) {
10750       NewFD->setInvalidDecl();
10751       return Redeclaration;
10752     }
10753 
10754     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10755     if (NewFD->getLiteralIdentifier() &&
10756         CheckLiteralOperatorDeclaration(NewFD)) {
10757       NewFD->setInvalidDecl();
10758       return Redeclaration;
10759     }
10760 
10761     // In C++, check default arguments now that we have merged decls. Unless
10762     // the lexical context is the class, because in this case this is done
10763     // during delayed parsing anyway.
10764     if (!CurContext->isRecord())
10765       CheckCXXDefaultArguments(NewFD);
10766 
10767     // If this function declares a builtin function, check the type of this
10768     // declaration against the expected type for the builtin.
10769     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10770       ASTContext::GetBuiltinTypeError Error;
10771       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10772       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10773       // If the type of the builtin differs only in its exception
10774       // specification, that's OK.
10775       // FIXME: If the types do differ in this way, it would be better to
10776       // retain the 'noexcept' form of the type.
10777       if (!T.isNull() &&
10778           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10779                                                             NewFD->getType()))
10780         // The type of this function differs from the type of the builtin,
10781         // so forget about the builtin entirely.
10782         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10783     }
10784 
10785     // If this function is declared as being extern "C", then check to see if
10786     // the function returns a UDT (class, struct, or union type) that is not C
10787     // compatible, and if it does, warn the user.
10788     // But, issue any diagnostic on the first declaration only.
10789     if (Previous.empty() && NewFD->isExternC()) {
10790       QualType R = NewFD->getReturnType();
10791       if (R->isIncompleteType() && !R->isVoidType())
10792         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10793             << NewFD << R;
10794       else if (!R.isPODType(Context) && !R->isVoidType() &&
10795                !R->isObjCObjectPointerType())
10796         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10797     }
10798 
10799     // C++1z [dcl.fct]p6:
10800     //   [...] whether the function has a non-throwing exception-specification
10801     //   [is] part of the function type
10802     //
10803     // This results in an ABI break between C++14 and C++17 for functions whose
10804     // declared type includes an exception-specification in a parameter or
10805     // return type. (Exception specifications on the function itself are OK in
10806     // most cases, and exception specifications are not permitted in most other
10807     // contexts where they could make it into a mangling.)
10808     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10809       auto HasNoexcept = [&](QualType T) -> bool {
10810         // Strip off declarator chunks that could be between us and a function
10811         // type. We don't need to look far, exception specifications are very
10812         // restricted prior to C++17.
10813         if (auto *RT = T->getAs<ReferenceType>())
10814           T = RT->getPointeeType();
10815         else if (T->isAnyPointerType())
10816           T = T->getPointeeType();
10817         else if (auto *MPT = T->getAs<MemberPointerType>())
10818           T = MPT->getPointeeType();
10819         if (auto *FPT = T->getAs<FunctionProtoType>())
10820           if (FPT->isNothrow())
10821             return true;
10822         return false;
10823       };
10824 
10825       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10826       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10827       for (QualType T : FPT->param_types())
10828         AnyNoexcept |= HasNoexcept(T);
10829       if (AnyNoexcept)
10830         Diag(NewFD->getLocation(),
10831              diag::warn_cxx17_compat_exception_spec_in_signature)
10832             << NewFD;
10833     }
10834 
10835     if (!Redeclaration && LangOpts.CUDA)
10836       checkCUDATargetOverload(NewFD, Previous);
10837   }
10838   return Redeclaration;
10839 }
10840 
10841 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10842   // C++11 [basic.start.main]p3:
10843   //   A program that [...] declares main to be inline, static or
10844   //   constexpr is ill-formed.
10845   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10846   //   appear in a declaration of main.
10847   // static main is not an error under C99, but we should warn about it.
10848   // We accept _Noreturn main as an extension.
10849   if (FD->getStorageClass() == SC_Static)
10850     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10851          ? diag::err_static_main : diag::warn_static_main)
10852       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10853   if (FD->isInlineSpecified())
10854     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10855       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10856   if (DS.isNoreturnSpecified()) {
10857     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10858     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10859     Diag(NoreturnLoc, diag::ext_noreturn_main);
10860     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10861       << FixItHint::CreateRemoval(NoreturnRange);
10862   }
10863   if (FD->isConstexpr()) {
10864     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10865         << FD->isConsteval()
10866         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10867     FD->setConstexprKind(CSK_unspecified);
10868   }
10869 
10870   if (getLangOpts().OpenCL) {
10871     Diag(FD->getLocation(), diag::err_opencl_no_main)
10872         << FD->hasAttr<OpenCLKernelAttr>();
10873     FD->setInvalidDecl();
10874     return;
10875   }
10876 
10877   QualType T = FD->getType();
10878   assert(T->isFunctionType() && "function decl is not of function type");
10879   const FunctionType* FT = T->castAs<FunctionType>();
10880 
10881   // Set default calling convention for main()
10882   if (FT->getCallConv() != CC_C) {
10883     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10884     FD->setType(QualType(FT, 0));
10885     T = Context.getCanonicalType(FD->getType());
10886   }
10887 
10888   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10889     // In C with GNU extensions we allow main() to have non-integer return
10890     // type, but we should warn about the extension, and we disable the
10891     // implicit-return-zero rule.
10892 
10893     // GCC in C mode accepts qualified 'int'.
10894     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10895       FD->setHasImplicitReturnZero(true);
10896     else {
10897       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10898       SourceRange RTRange = FD->getReturnTypeSourceRange();
10899       if (RTRange.isValid())
10900         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10901             << FixItHint::CreateReplacement(RTRange, "int");
10902     }
10903   } else {
10904     // In C and C++, main magically returns 0 if you fall off the end;
10905     // set the flag which tells us that.
10906     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10907 
10908     // All the standards say that main() should return 'int'.
10909     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10910       FD->setHasImplicitReturnZero(true);
10911     else {
10912       // Otherwise, this is just a flat-out error.
10913       SourceRange RTRange = FD->getReturnTypeSourceRange();
10914       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10915           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10916                                 : FixItHint());
10917       FD->setInvalidDecl(true);
10918     }
10919   }
10920 
10921   // Treat protoless main() as nullary.
10922   if (isa<FunctionNoProtoType>(FT)) return;
10923 
10924   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10925   unsigned nparams = FTP->getNumParams();
10926   assert(FD->getNumParams() == nparams);
10927 
10928   bool HasExtraParameters = (nparams > 3);
10929 
10930   if (FTP->isVariadic()) {
10931     Diag(FD->getLocation(), diag::ext_variadic_main);
10932     // FIXME: if we had information about the location of the ellipsis, we
10933     // could add a FixIt hint to remove it as a parameter.
10934   }
10935 
10936   // Darwin passes an undocumented fourth argument of type char**.  If
10937   // other platforms start sprouting these, the logic below will start
10938   // getting shifty.
10939   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10940     HasExtraParameters = false;
10941 
10942   if (HasExtraParameters) {
10943     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10944     FD->setInvalidDecl(true);
10945     nparams = 3;
10946   }
10947 
10948   // FIXME: a lot of the following diagnostics would be improved
10949   // if we had some location information about types.
10950 
10951   QualType CharPP =
10952     Context.getPointerType(Context.getPointerType(Context.CharTy));
10953   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10954 
10955   for (unsigned i = 0; i < nparams; ++i) {
10956     QualType AT = FTP->getParamType(i);
10957 
10958     bool mismatch = true;
10959 
10960     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10961       mismatch = false;
10962     else if (Expected[i] == CharPP) {
10963       // As an extension, the following forms are okay:
10964       //   char const **
10965       //   char const * const *
10966       //   char * const *
10967 
10968       QualifierCollector qs;
10969       const PointerType* PT;
10970       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10971           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10972           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10973                               Context.CharTy)) {
10974         qs.removeConst();
10975         mismatch = !qs.empty();
10976       }
10977     }
10978 
10979     if (mismatch) {
10980       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10981       // TODO: suggest replacing given type with expected type
10982       FD->setInvalidDecl(true);
10983     }
10984   }
10985 
10986   if (nparams == 1 && !FD->isInvalidDecl()) {
10987     Diag(FD->getLocation(), diag::warn_main_one_arg);
10988   }
10989 
10990   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10991     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10992     FD->setInvalidDecl();
10993   }
10994 }
10995 
10996 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10997   QualType T = FD->getType();
10998   assert(T->isFunctionType() && "function decl is not of function type");
10999   const FunctionType *FT = T->castAs<FunctionType>();
11000 
11001   // Set an implicit return of 'zero' if the function can return some integral,
11002   // enumeration, pointer or nullptr type.
11003   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11004       FT->getReturnType()->isAnyPointerType() ||
11005       FT->getReturnType()->isNullPtrType())
11006     // DllMain is exempt because a return value of zero means it failed.
11007     if (FD->getName() != "DllMain")
11008       FD->setHasImplicitReturnZero(true);
11009 
11010   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11011     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11012     FD->setInvalidDecl();
11013   }
11014 }
11015 
11016 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11017   // FIXME: Need strict checking.  In C89, we need to check for
11018   // any assignment, increment, decrement, function-calls, or
11019   // commas outside of a sizeof.  In C99, it's the same list,
11020   // except that the aforementioned are allowed in unevaluated
11021   // expressions.  Everything else falls under the
11022   // "may accept other forms of constant expressions" exception.
11023   // (We never end up here for C++, so the constant expression
11024   // rules there don't matter.)
11025   const Expr *Culprit;
11026   if (Init->isConstantInitializer(Context, false, &Culprit))
11027     return false;
11028   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11029     << Culprit->getSourceRange();
11030   return true;
11031 }
11032 
11033 namespace {
11034   // Visits an initialization expression to see if OrigDecl is evaluated in
11035   // its own initialization and throws a warning if it does.
11036   class SelfReferenceChecker
11037       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11038     Sema &S;
11039     Decl *OrigDecl;
11040     bool isRecordType;
11041     bool isPODType;
11042     bool isReferenceType;
11043 
11044     bool isInitList;
11045     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11046 
11047   public:
11048     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11049 
11050     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11051                                                     S(S), OrigDecl(OrigDecl) {
11052       isPODType = false;
11053       isRecordType = false;
11054       isReferenceType = false;
11055       isInitList = false;
11056       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11057         isPODType = VD->getType().isPODType(S.Context);
11058         isRecordType = VD->getType()->isRecordType();
11059         isReferenceType = VD->getType()->isReferenceType();
11060       }
11061     }
11062 
11063     // For most expressions, just call the visitor.  For initializer lists,
11064     // track the index of the field being initialized since fields are
11065     // initialized in order allowing use of previously initialized fields.
11066     void CheckExpr(Expr *E) {
11067       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11068       if (!InitList) {
11069         Visit(E);
11070         return;
11071       }
11072 
11073       // Track and increment the index here.
11074       isInitList = true;
11075       InitFieldIndex.push_back(0);
11076       for (auto Child : InitList->children()) {
11077         CheckExpr(cast<Expr>(Child));
11078         ++InitFieldIndex.back();
11079       }
11080       InitFieldIndex.pop_back();
11081     }
11082 
11083     // Returns true if MemberExpr is checked and no further checking is needed.
11084     // Returns false if additional checking is required.
11085     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11086       llvm::SmallVector<FieldDecl*, 4> Fields;
11087       Expr *Base = E;
11088       bool ReferenceField = false;
11089 
11090       // Get the field members used.
11091       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11092         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11093         if (!FD)
11094           return false;
11095         Fields.push_back(FD);
11096         if (FD->getType()->isReferenceType())
11097           ReferenceField = true;
11098         Base = ME->getBase()->IgnoreParenImpCasts();
11099       }
11100 
11101       // Keep checking only if the base Decl is the same.
11102       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11103       if (!DRE || DRE->getDecl() != OrigDecl)
11104         return false;
11105 
11106       // A reference field can be bound to an unininitialized field.
11107       if (CheckReference && !ReferenceField)
11108         return true;
11109 
11110       // Convert FieldDecls to their index number.
11111       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11112       for (const FieldDecl *I : llvm::reverse(Fields))
11113         UsedFieldIndex.push_back(I->getFieldIndex());
11114 
11115       // See if a warning is needed by checking the first difference in index
11116       // numbers.  If field being used has index less than the field being
11117       // initialized, then the use is safe.
11118       for (auto UsedIter = UsedFieldIndex.begin(),
11119                 UsedEnd = UsedFieldIndex.end(),
11120                 OrigIter = InitFieldIndex.begin(),
11121                 OrigEnd = InitFieldIndex.end();
11122            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11123         if (*UsedIter < *OrigIter)
11124           return true;
11125         if (*UsedIter > *OrigIter)
11126           break;
11127       }
11128 
11129       // TODO: Add a different warning which will print the field names.
11130       HandleDeclRefExpr(DRE);
11131       return true;
11132     }
11133 
11134     // For most expressions, the cast is directly above the DeclRefExpr.
11135     // For conditional operators, the cast can be outside the conditional
11136     // operator if both expressions are DeclRefExpr's.
11137     void HandleValue(Expr *E) {
11138       E = E->IgnoreParens();
11139       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11140         HandleDeclRefExpr(DRE);
11141         return;
11142       }
11143 
11144       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11145         Visit(CO->getCond());
11146         HandleValue(CO->getTrueExpr());
11147         HandleValue(CO->getFalseExpr());
11148         return;
11149       }
11150 
11151       if (BinaryConditionalOperator *BCO =
11152               dyn_cast<BinaryConditionalOperator>(E)) {
11153         Visit(BCO->getCond());
11154         HandleValue(BCO->getFalseExpr());
11155         return;
11156       }
11157 
11158       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11159         HandleValue(OVE->getSourceExpr());
11160         return;
11161       }
11162 
11163       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11164         if (BO->getOpcode() == BO_Comma) {
11165           Visit(BO->getLHS());
11166           HandleValue(BO->getRHS());
11167           return;
11168         }
11169       }
11170 
11171       if (isa<MemberExpr>(E)) {
11172         if (isInitList) {
11173           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11174                                       false /*CheckReference*/))
11175             return;
11176         }
11177 
11178         Expr *Base = E->IgnoreParenImpCasts();
11179         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11180           // Check for static member variables and don't warn on them.
11181           if (!isa<FieldDecl>(ME->getMemberDecl()))
11182             return;
11183           Base = ME->getBase()->IgnoreParenImpCasts();
11184         }
11185         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11186           HandleDeclRefExpr(DRE);
11187         return;
11188       }
11189 
11190       Visit(E);
11191     }
11192 
11193     // Reference types not handled in HandleValue are handled here since all
11194     // uses of references are bad, not just r-value uses.
11195     void VisitDeclRefExpr(DeclRefExpr *E) {
11196       if (isReferenceType)
11197         HandleDeclRefExpr(E);
11198     }
11199 
11200     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11201       if (E->getCastKind() == CK_LValueToRValue) {
11202         HandleValue(E->getSubExpr());
11203         return;
11204       }
11205 
11206       Inherited::VisitImplicitCastExpr(E);
11207     }
11208 
11209     void VisitMemberExpr(MemberExpr *E) {
11210       if (isInitList) {
11211         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11212           return;
11213       }
11214 
11215       // Don't warn on arrays since they can be treated as pointers.
11216       if (E->getType()->canDecayToPointerType()) return;
11217 
11218       // Warn when a non-static method call is followed by non-static member
11219       // field accesses, which is followed by a DeclRefExpr.
11220       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11221       bool Warn = (MD && !MD->isStatic());
11222       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11223       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11224         if (!isa<FieldDecl>(ME->getMemberDecl()))
11225           Warn = false;
11226         Base = ME->getBase()->IgnoreParenImpCasts();
11227       }
11228 
11229       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11230         if (Warn)
11231           HandleDeclRefExpr(DRE);
11232         return;
11233       }
11234 
11235       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11236       // Visit that expression.
11237       Visit(Base);
11238     }
11239 
11240     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11241       Expr *Callee = E->getCallee();
11242 
11243       if (isa<UnresolvedLookupExpr>(Callee))
11244         return Inherited::VisitCXXOperatorCallExpr(E);
11245 
11246       Visit(Callee);
11247       for (auto Arg: E->arguments())
11248         HandleValue(Arg->IgnoreParenImpCasts());
11249     }
11250 
11251     void VisitUnaryOperator(UnaryOperator *E) {
11252       // For POD record types, addresses of its own members are well-defined.
11253       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11254           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11255         if (!isPODType)
11256           HandleValue(E->getSubExpr());
11257         return;
11258       }
11259 
11260       if (E->isIncrementDecrementOp()) {
11261         HandleValue(E->getSubExpr());
11262         return;
11263       }
11264 
11265       Inherited::VisitUnaryOperator(E);
11266     }
11267 
11268     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11269 
11270     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11271       if (E->getConstructor()->isCopyConstructor()) {
11272         Expr *ArgExpr = E->getArg(0);
11273         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11274           if (ILE->getNumInits() == 1)
11275             ArgExpr = ILE->getInit(0);
11276         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11277           if (ICE->getCastKind() == CK_NoOp)
11278             ArgExpr = ICE->getSubExpr();
11279         HandleValue(ArgExpr);
11280         return;
11281       }
11282       Inherited::VisitCXXConstructExpr(E);
11283     }
11284 
11285     void VisitCallExpr(CallExpr *E) {
11286       // Treat std::move as a use.
11287       if (E->isCallToStdMove()) {
11288         HandleValue(E->getArg(0));
11289         return;
11290       }
11291 
11292       Inherited::VisitCallExpr(E);
11293     }
11294 
11295     void VisitBinaryOperator(BinaryOperator *E) {
11296       if (E->isCompoundAssignmentOp()) {
11297         HandleValue(E->getLHS());
11298         Visit(E->getRHS());
11299         return;
11300       }
11301 
11302       Inherited::VisitBinaryOperator(E);
11303     }
11304 
11305     // A custom visitor for BinaryConditionalOperator is needed because the
11306     // regular visitor would check the condition and true expression separately
11307     // but both point to the same place giving duplicate diagnostics.
11308     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11309       Visit(E->getCond());
11310       Visit(E->getFalseExpr());
11311     }
11312 
11313     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11314       Decl* ReferenceDecl = DRE->getDecl();
11315       if (OrigDecl != ReferenceDecl) return;
11316       unsigned diag;
11317       if (isReferenceType) {
11318         diag = diag::warn_uninit_self_reference_in_reference_init;
11319       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11320         diag = diag::warn_static_self_reference_in_init;
11321       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11322                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11323                  DRE->getDecl()->getType()->isRecordType()) {
11324         diag = diag::warn_uninit_self_reference_in_init;
11325       } else {
11326         // Local variables will be handled by the CFG analysis.
11327         return;
11328       }
11329 
11330       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11331                             S.PDiag(diag)
11332                                 << DRE->getDecl() << OrigDecl->getLocation()
11333                                 << DRE->getSourceRange());
11334     }
11335   };
11336 
11337   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11338   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11339                                  bool DirectInit) {
11340     // Parameters arguments are occassionially constructed with itself,
11341     // for instance, in recursive functions.  Skip them.
11342     if (isa<ParmVarDecl>(OrigDecl))
11343       return;
11344 
11345     E = E->IgnoreParens();
11346 
11347     // Skip checking T a = a where T is not a record or reference type.
11348     // Doing so is a way to silence uninitialized warnings.
11349     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11350       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11351         if (ICE->getCastKind() == CK_LValueToRValue)
11352           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11353             if (DRE->getDecl() == OrigDecl)
11354               return;
11355 
11356     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11357   }
11358 } // end anonymous namespace
11359 
11360 namespace {
11361   // Simple wrapper to add the name of a variable or (if no variable is
11362   // available) a DeclarationName into a diagnostic.
11363   struct VarDeclOrName {
11364     VarDecl *VDecl;
11365     DeclarationName Name;
11366 
11367     friend const Sema::SemaDiagnosticBuilder &
11368     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11369       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11370     }
11371   };
11372 } // end anonymous namespace
11373 
11374 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11375                                             DeclarationName Name, QualType Type,
11376                                             TypeSourceInfo *TSI,
11377                                             SourceRange Range, bool DirectInit,
11378                                             Expr *Init) {
11379   bool IsInitCapture = !VDecl;
11380   assert((!VDecl || !VDecl->isInitCapture()) &&
11381          "init captures are expected to be deduced prior to initialization");
11382 
11383   VarDeclOrName VN{VDecl, Name};
11384 
11385   DeducedType *Deduced = Type->getContainedDeducedType();
11386   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11387 
11388   // C++11 [dcl.spec.auto]p3
11389   if (!Init) {
11390     assert(VDecl && "no init for init capture deduction?");
11391 
11392     // Except for class argument deduction, and then for an initializing
11393     // declaration only, i.e. no static at class scope or extern.
11394     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11395         VDecl->hasExternalStorage() ||
11396         VDecl->isStaticDataMember()) {
11397       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11398         << VDecl->getDeclName() << Type;
11399       return QualType();
11400     }
11401   }
11402 
11403   ArrayRef<Expr*> DeduceInits;
11404   if (Init)
11405     DeduceInits = Init;
11406 
11407   if (DirectInit) {
11408     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11409       DeduceInits = PL->exprs();
11410   }
11411 
11412   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11413     assert(VDecl && "non-auto type for init capture deduction?");
11414     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11415     InitializationKind Kind = InitializationKind::CreateForInit(
11416         VDecl->getLocation(), DirectInit, Init);
11417     // FIXME: Initialization should not be taking a mutable list of inits.
11418     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11419     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11420                                                        InitsCopy);
11421   }
11422 
11423   if (DirectInit) {
11424     if (auto *IL = dyn_cast<InitListExpr>(Init))
11425       DeduceInits = IL->inits();
11426   }
11427 
11428   // Deduction only works if we have exactly one source expression.
11429   if (DeduceInits.empty()) {
11430     // It isn't possible to write this directly, but it is possible to
11431     // end up in this situation with "auto x(some_pack...);"
11432     Diag(Init->getBeginLoc(), IsInitCapture
11433                                   ? diag::err_init_capture_no_expression
11434                                   : diag::err_auto_var_init_no_expression)
11435         << VN << Type << Range;
11436     return QualType();
11437   }
11438 
11439   if (DeduceInits.size() > 1) {
11440     Diag(DeduceInits[1]->getBeginLoc(),
11441          IsInitCapture ? diag::err_init_capture_multiple_expressions
11442                        : diag::err_auto_var_init_multiple_expressions)
11443         << VN << Type << Range;
11444     return QualType();
11445   }
11446 
11447   Expr *DeduceInit = DeduceInits[0];
11448   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11449     Diag(Init->getBeginLoc(), IsInitCapture
11450                                   ? diag::err_init_capture_paren_braces
11451                                   : diag::err_auto_var_init_paren_braces)
11452         << isa<InitListExpr>(Init) << VN << Type << Range;
11453     return QualType();
11454   }
11455 
11456   // Expressions default to 'id' when we're in a debugger.
11457   bool DefaultedAnyToId = false;
11458   if (getLangOpts().DebuggerCastResultToId &&
11459       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11460     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11461     if (Result.isInvalid()) {
11462       return QualType();
11463     }
11464     Init = Result.get();
11465     DefaultedAnyToId = true;
11466   }
11467 
11468   // C++ [dcl.decomp]p1:
11469   //   If the assignment-expression [...] has array type A and no ref-qualifier
11470   //   is present, e has type cv A
11471   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11472       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11473       DeduceInit->getType()->isConstantArrayType())
11474     return Context.getQualifiedType(DeduceInit->getType(),
11475                                     Type.getQualifiers());
11476 
11477   QualType DeducedType;
11478   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11479     if (!IsInitCapture)
11480       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11481     else if (isa<InitListExpr>(Init))
11482       Diag(Range.getBegin(),
11483            diag::err_init_capture_deduction_failure_from_init_list)
11484           << VN
11485           << (DeduceInit->getType().isNull() ? TSI->getType()
11486                                              : DeduceInit->getType())
11487           << DeduceInit->getSourceRange();
11488     else
11489       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11490           << VN << TSI->getType()
11491           << (DeduceInit->getType().isNull() ? TSI->getType()
11492                                              : DeduceInit->getType())
11493           << DeduceInit->getSourceRange();
11494   }
11495 
11496   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11497   // 'id' instead of a specific object type prevents most of our usual
11498   // checks.
11499   // We only want to warn outside of template instantiations, though:
11500   // inside a template, the 'id' could have come from a parameter.
11501   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11502       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11503     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11504     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11505   }
11506 
11507   return DeducedType;
11508 }
11509 
11510 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11511                                          Expr *Init) {
11512   assert(!Init || !Init->containsErrors());
11513   QualType DeducedType = deduceVarTypeFromInitializer(
11514       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11515       VDecl->getSourceRange(), DirectInit, Init);
11516   if (DeducedType.isNull()) {
11517     VDecl->setInvalidDecl();
11518     return true;
11519   }
11520 
11521   VDecl->setType(DeducedType);
11522   assert(VDecl->isLinkageValid());
11523 
11524   // In ARC, infer lifetime.
11525   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11526     VDecl->setInvalidDecl();
11527 
11528   if (getLangOpts().OpenCL)
11529     deduceOpenCLAddressSpace(VDecl);
11530 
11531   // If this is a redeclaration, check that the type we just deduced matches
11532   // the previously declared type.
11533   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11534     // We never need to merge the type, because we cannot form an incomplete
11535     // array of auto, nor deduce such a type.
11536     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11537   }
11538 
11539   // Check the deduced type is valid for a variable declaration.
11540   CheckVariableDeclarationType(VDecl);
11541   return VDecl->isInvalidDecl();
11542 }
11543 
11544 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11545                                               SourceLocation Loc) {
11546   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11547     Init = EWC->getSubExpr();
11548 
11549   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11550     Init = CE->getSubExpr();
11551 
11552   QualType InitType = Init->getType();
11553   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11554           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11555          "shouldn't be called if type doesn't have a non-trivial C struct");
11556   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11557     for (auto I : ILE->inits()) {
11558       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11559           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11560         continue;
11561       SourceLocation SL = I->getExprLoc();
11562       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11563     }
11564     return;
11565   }
11566 
11567   if (isa<ImplicitValueInitExpr>(Init)) {
11568     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11569       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11570                             NTCUK_Init);
11571   } else {
11572     // Assume all other explicit initializers involving copying some existing
11573     // object.
11574     // TODO: ignore any explicit initializers where we can guarantee
11575     // copy-elision.
11576     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11577       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11578   }
11579 }
11580 
11581 namespace {
11582 
11583 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11584   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11585   // in the source code or implicitly by the compiler if it is in a union
11586   // defined in a system header and has non-trivial ObjC ownership
11587   // qualifications. We don't want those fields to participate in determining
11588   // whether the containing union is non-trivial.
11589   return FD->hasAttr<UnavailableAttr>();
11590 }
11591 
11592 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11593     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11594                                     void> {
11595   using Super =
11596       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11597                                     void>;
11598 
11599   DiagNonTrivalCUnionDefaultInitializeVisitor(
11600       QualType OrigTy, SourceLocation OrigLoc,
11601       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11602       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11603 
11604   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11605                      const FieldDecl *FD, bool InNonTrivialUnion) {
11606     if (const auto *AT = S.Context.getAsArrayType(QT))
11607       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11608                                      InNonTrivialUnion);
11609     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11610   }
11611 
11612   void visitARCStrong(QualType QT, const FieldDecl *FD,
11613                       bool InNonTrivialUnion) {
11614     if (InNonTrivialUnion)
11615       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11616           << 1 << 0 << QT << FD->getName();
11617   }
11618 
11619   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11620     if (InNonTrivialUnion)
11621       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11622           << 1 << 0 << QT << FD->getName();
11623   }
11624 
11625   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11626     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11627     if (RD->isUnion()) {
11628       if (OrigLoc.isValid()) {
11629         bool IsUnion = false;
11630         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11631           IsUnion = OrigRD->isUnion();
11632         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11633             << 0 << OrigTy << IsUnion << UseContext;
11634         // Reset OrigLoc so that this diagnostic is emitted only once.
11635         OrigLoc = SourceLocation();
11636       }
11637       InNonTrivialUnion = true;
11638     }
11639 
11640     if (InNonTrivialUnion)
11641       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11642           << 0 << 0 << QT.getUnqualifiedType() << "";
11643 
11644     for (const FieldDecl *FD : RD->fields())
11645       if (!shouldIgnoreForRecordTriviality(FD))
11646         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11647   }
11648 
11649   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11650 
11651   // The non-trivial C union type or the struct/union type that contains a
11652   // non-trivial C union.
11653   QualType OrigTy;
11654   SourceLocation OrigLoc;
11655   Sema::NonTrivialCUnionContext UseContext;
11656   Sema &S;
11657 };
11658 
11659 struct DiagNonTrivalCUnionDestructedTypeVisitor
11660     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11661   using Super =
11662       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11663 
11664   DiagNonTrivalCUnionDestructedTypeVisitor(
11665       QualType OrigTy, SourceLocation OrigLoc,
11666       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11667       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11668 
11669   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11670                      const FieldDecl *FD, bool InNonTrivialUnion) {
11671     if (const auto *AT = S.Context.getAsArrayType(QT))
11672       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11673                                      InNonTrivialUnion);
11674     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11675   }
11676 
11677   void visitARCStrong(QualType QT, const FieldDecl *FD,
11678                       bool InNonTrivialUnion) {
11679     if (InNonTrivialUnion)
11680       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11681           << 1 << 1 << QT << FD->getName();
11682   }
11683 
11684   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11685     if (InNonTrivialUnion)
11686       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11687           << 1 << 1 << QT << FD->getName();
11688   }
11689 
11690   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11691     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11692     if (RD->isUnion()) {
11693       if (OrigLoc.isValid()) {
11694         bool IsUnion = false;
11695         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11696           IsUnion = OrigRD->isUnion();
11697         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11698             << 1 << OrigTy << IsUnion << UseContext;
11699         // Reset OrigLoc so that this diagnostic is emitted only once.
11700         OrigLoc = SourceLocation();
11701       }
11702       InNonTrivialUnion = true;
11703     }
11704 
11705     if (InNonTrivialUnion)
11706       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11707           << 0 << 1 << QT.getUnqualifiedType() << "";
11708 
11709     for (const FieldDecl *FD : RD->fields())
11710       if (!shouldIgnoreForRecordTriviality(FD))
11711         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11712   }
11713 
11714   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11715   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11716                           bool InNonTrivialUnion) {}
11717 
11718   // The non-trivial C union type or the struct/union type that contains a
11719   // non-trivial C union.
11720   QualType OrigTy;
11721   SourceLocation OrigLoc;
11722   Sema::NonTrivialCUnionContext UseContext;
11723   Sema &S;
11724 };
11725 
11726 struct DiagNonTrivalCUnionCopyVisitor
11727     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11728   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11729 
11730   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11731                                  Sema::NonTrivialCUnionContext UseContext,
11732                                  Sema &S)
11733       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11734 
11735   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11736                      const FieldDecl *FD, bool InNonTrivialUnion) {
11737     if (const auto *AT = S.Context.getAsArrayType(QT))
11738       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11739                                      InNonTrivialUnion);
11740     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11741   }
11742 
11743   void visitARCStrong(QualType QT, const FieldDecl *FD,
11744                       bool InNonTrivialUnion) {
11745     if (InNonTrivialUnion)
11746       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11747           << 1 << 2 << QT << FD->getName();
11748   }
11749 
11750   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11751     if (InNonTrivialUnion)
11752       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11753           << 1 << 2 << QT << FD->getName();
11754   }
11755 
11756   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11757     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11758     if (RD->isUnion()) {
11759       if (OrigLoc.isValid()) {
11760         bool IsUnion = false;
11761         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11762           IsUnion = OrigRD->isUnion();
11763         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11764             << 2 << OrigTy << IsUnion << UseContext;
11765         // Reset OrigLoc so that this diagnostic is emitted only once.
11766         OrigLoc = SourceLocation();
11767       }
11768       InNonTrivialUnion = true;
11769     }
11770 
11771     if (InNonTrivialUnion)
11772       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11773           << 0 << 2 << QT.getUnqualifiedType() << "";
11774 
11775     for (const FieldDecl *FD : RD->fields())
11776       if (!shouldIgnoreForRecordTriviality(FD))
11777         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11778   }
11779 
11780   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11781                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11782   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11783   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11784                             bool InNonTrivialUnion) {}
11785 
11786   // The non-trivial C union type or the struct/union type that contains a
11787   // non-trivial C union.
11788   QualType OrigTy;
11789   SourceLocation OrigLoc;
11790   Sema::NonTrivialCUnionContext UseContext;
11791   Sema &S;
11792 };
11793 
11794 } // namespace
11795 
11796 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11797                                  NonTrivialCUnionContext UseContext,
11798                                  unsigned NonTrivialKind) {
11799   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11800           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11801           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11802          "shouldn't be called if type doesn't have a non-trivial C union");
11803 
11804   if ((NonTrivialKind & NTCUK_Init) &&
11805       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11806     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11807         .visit(QT, nullptr, false);
11808   if ((NonTrivialKind & NTCUK_Destruct) &&
11809       QT.hasNonTrivialToPrimitiveDestructCUnion())
11810     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11811         .visit(QT, nullptr, false);
11812   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11813     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11814         .visit(QT, nullptr, false);
11815 }
11816 
11817 /// AddInitializerToDecl - Adds the initializer Init to the
11818 /// declaration dcl. If DirectInit is true, this is C++ direct
11819 /// initialization rather than copy initialization.
11820 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11821   // If there is no declaration, there was an error parsing it.  Just ignore
11822   // the initializer.
11823   if (!RealDecl || RealDecl->isInvalidDecl()) {
11824     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11825     return;
11826   }
11827 
11828   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11829     // Pure-specifiers are handled in ActOnPureSpecifier.
11830     Diag(Method->getLocation(), diag::err_member_function_initialization)
11831       << Method->getDeclName() << Init->getSourceRange();
11832     Method->setInvalidDecl();
11833     return;
11834   }
11835 
11836   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11837   if (!VDecl) {
11838     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11839     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11840     RealDecl->setInvalidDecl();
11841     return;
11842   }
11843 
11844   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11845   if (VDecl->getType()->isUndeducedType()) {
11846     // Attempt typo correction early so that the type of the init expression can
11847     // be deduced based on the chosen correction if the original init contains a
11848     // TypoExpr.
11849     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11850     if (!Res.isUsable() || Res.get()->containsErrors()) {
11851       RealDecl->setInvalidDecl();
11852       return;
11853     }
11854     Init = Res.get();
11855 
11856     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11857       return;
11858   }
11859 
11860   // dllimport cannot be used on variable definitions.
11861   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11862     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11863     VDecl->setInvalidDecl();
11864     return;
11865   }
11866 
11867   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11868     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11869     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11870     VDecl->setInvalidDecl();
11871     return;
11872   }
11873 
11874   if (!VDecl->getType()->isDependentType()) {
11875     // A definition must end up with a complete type, which means it must be
11876     // complete with the restriction that an array type might be completed by
11877     // the initializer; note that later code assumes this restriction.
11878     QualType BaseDeclType = VDecl->getType();
11879     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11880       BaseDeclType = Array->getElementType();
11881     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11882                             diag::err_typecheck_decl_incomplete_type)) {
11883       RealDecl->setInvalidDecl();
11884       return;
11885     }
11886 
11887     // The variable can not have an abstract class type.
11888     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11889                                diag::err_abstract_type_in_decl,
11890                                AbstractVariableType))
11891       VDecl->setInvalidDecl();
11892   }
11893 
11894   // If adding the initializer will turn this declaration into a definition,
11895   // and we already have a definition for this variable, diagnose or otherwise
11896   // handle the situation.
11897   VarDecl *Def;
11898   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11899       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11900       !VDecl->isThisDeclarationADemotedDefinition() &&
11901       checkVarDeclRedefinition(Def, VDecl))
11902     return;
11903 
11904   if (getLangOpts().CPlusPlus) {
11905     // C++ [class.static.data]p4
11906     //   If a static data member is of const integral or const
11907     //   enumeration type, its declaration in the class definition can
11908     //   specify a constant-initializer which shall be an integral
11909     //   constant expression (5.19). In that case, the member can appear
11910     //   in integral constant expressions. The member shall still be
11911     //   defined in a namespace scope if it is used in the program and the
11912     //   namespace scope definition shall not contain an initializer.
11913     //
11914     // We already performed a redefinition check above, but for static
11915     // data members we also need to check whether there was an in-class
11916     // declaration with an initializer.
11917     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11918       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11919           << VDecl->getDeclName();
11920       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11921            diag::note_previous_initializer)
11922           << 0;
11923       return;
11924     }
11925 
11926     if (VDecl->hasLocalStorage())
11927       setFunctionHasBranchProtectedScope();
11928 
11929     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11930       VDecl->setInvalidDecl();
11931       return;
11932     }
11933   }
11934 
11935   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11936   // a kernel function cannot be initialized."
11937   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11938     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11939     VDecl->setInvalidDecl();
11940     return;
11941   }
11942 
11943   // The LoaderUninitialized attribute acts as a definition (of undef).
11944   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
11945     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
11946     VDecl->setInvalidDecl();
11947     return;
11948   }
11949 
11950   // Get the decls type and save a reference for later, since
11951   // CheckInitializerTypes may change it.
11952   QualType DclT = VDecl->getType(), SavT = DclT;
11953 
11954   // Expressions default to 'id' when we're in a debugger
11955   // and we are assigning it to a variable of Objective-C pointer type.
11956   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11957       Init->getType() == Context.UnknownAnyTy) {
11958     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11959     if (Result.isInvalid()) {
11960       VDecl->setInvalidDecl();
11961       return;
11962     }
11963     Init = Result.get();
11964   }
11965 
11966   // Perform the initialization.
11967   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11968   if (!VDecl->isInvalidDecl()) {
11969     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11970     InitializationKind Kind = InitializationKind::CreateForInit(
11971         VDecl->getLocation(), DirectInit, Init);
11972 
11973     MultiExprArg Args = Init;
11974     if (CXXDirectInit)
11975       Args = MultiExprArg(CXXDirectInit->getExprs(),
11976                           CXXDirectInit->getNumExprs());
11977 
11978     // Try to correct any TypoExprs in the initialization arguments.
11979     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11980       ExprResult Res = CorrectDelayedTyposInExpr(
11981           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11982             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11983             return Init.Failed() ? ExprError() : E;
11984           });
11985       if (Res.isInvalid()) {
11986         VDecl->setInvalidDecl();
11987       } else if (Res.get() != Args[Idx]) {
11988         Args[Idx] = Res.get();
11989       }
11990     }
11991     if (VDecl->isInvalidDecl())
11992       return;
11993 
11994     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11995                                    /*TopLevelOfInitList=*/false,
11996                                    /*TreatUnavailableAsInvalid=*/false);
11997     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11998     if (Result.isInvalid()) {
11999       VDecl->setInvalidDecl();
12000       return;
12001     }
12002 
12003     Init = Result.getAs<Expr>();
12004   }
12005 
12006   // Check for self-references within variable initializers.
12007   // Variables declared within a function/method body (except for references)
12008   // are handled by a dataflow analysis.
12009   // This is undefined behavior in C++, but valid in C.
12010   if (getLangOpts().CPlusPlus) {
12011     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12012         VDecl->getType()->isReferenceType()) {
12013       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12014     }
12015   }
12016 
12017   // If the type changed, it means we had an incomplete type that was
12018   // completed by the initializer. For example:
12019   //   int ary[] = { 1, 3, 5 };
12020   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12021   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12022     VDecl->setType(DclT);
12023 
12024   if (!VDecl->isInvalidDecl()) {
12025     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12026 
12027     if (VDecl->hasAttr<BlocksAttr>())
12028       checkRetainCycles(VDecl, Init);
12029 
12030     // It is safe to assign a weak reference into a strong variable.
12031     // Although this code can still have problems:
12032     //   id x = self.weakProp;
12033     //   id y = self.weakProp;
12034     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12035     // paths through the function. This should be revisited if
12036     // -Wrepeated-use-of-weak is made flow-sensitive.
12037     if (FunctionScopeInfo *FSI = getCurFunction())
12038       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12039            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12040           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12041                            Init->getBeginLoc()))
12042         FSI->markSafeWeakUse(Init);
12043   }
12044 
12045   // The initialization is usually a full-expression.
12046   //
12047   // FIXME: If this is a braced initialization of an aggregate, it is not
12048   // an expression, and each individual field initializer is a separate
12049   // full-expression. For instance, in:
12050   //
12051   //   struct Temp { ~Temp(); };
12052   //   struct S { S(Temp); };
12053   //   struct T { S a, b; } t = { Temp(), Temp() }
12054   //
12055   // we should destroy the first Temp before constructing the second.
12056   ExprResult Result =
12057       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12058                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12059   if (Result.isInvalid()) {
12060     VDecl->setInvalidDecl();
12061     return;
12062   }
12063   Init = Result.get();
12064 
12065   // Attach the initializer to the decl.
12066   VDecl->setInit(Init);
12067 
12068   if (VDecl->isLocalVarDecl()) {
12069     // Don't check the initializer if the declaration is malformed.
12070     if (VDecl->isInvalidDecl()) {
12071       // do nothing
12072 
12073     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12074     // This is true even in C++ for OpenCL.
12075     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12076       CheckForConstantInitializer(Init, DclT);
12077 
12078     // Otherwise, C++ does not restrict the initializer.
12079     } else if (getLangOpts().CPlusPlus) {
12080       // do nothing
12081 
12082     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12083     // static storage duration shall be constant expressions or string literals.
12084     } else if (VDecl->getStorageClass() == SC_Static) {
12085       CheckForConstantInitializer(Init, DclT);
12086 
12087     // C89 is stricter than C99 for aggregate initializers.
12088     // C89 6.5.7p3: All the expressions [...] in an initializer list
12089     // for an object that has aggregate or union type shall be
12090     // constant expressions.
12091     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12092                isa<InitListExpr>(Init)) {
12093       const Expr *Culprit;
12094       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12095         Diag(Culprit->getExprLoc(),
12096              diag::ext_aggregate_init_not_constant)
12097           << Culprit->getSourceRange();
12098       }
12099     }
12100 
12101     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12102       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12103         if (VDecl->hasLocalStorage())
12104           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12105   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12106              VDecl->getLexicalDeclContext()->isRecord()) {
12107     // This is an in-class initialization for a static data member, e.g.,
12108     //
12109     // struct S {
12110     //   static const int value = 17;
12111     // };
12112 
12113     // C++ [class.mem]p4:
12114     //   A member-declarator can contain a constant-initializer only
12115     //   if it declares a static member (9.4) of const integral or
12116     //   const enumeration type, see 9.4.2.
12117     //
12118     // C++11 [class.static.data]p3:
12119     //   If a non-volatile non-inline const static data member is of integral
12120     //   or enumeration type, its declaration in the class definition can
12121     //   specify a brace-or-equal-initializer in which every initializer-clause
12122     //   that is an assignment-expression is a constant expression. A static
12123     //   data member of literal type can be declared in the class definition
12124     //   with the constexpr specifier; if so, its declaration shall specify a
12125     //   brace-or-equal-initializer in which every initializer-clause that is
12126     //   an assignment-expression is a constant expression.
12127 
12128     // Do nothing on dependent types.
12129     if (DclT->isDependentType()) {
12130 
12131     // Allow any 'static constexpr' members, whether or not they are of literal
12132     // type. We separately check that every constexpr variable is of literal
12133     // type.
12134     } else if (VDecl->isConstexpr()) {
12135 
12136     // Require constness.
12137     } else if (!DclT.isConstQualified()) {
12138       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12139         << Init->getSourceRange();
12140       VDecl->setInvalidDecl();
12141 
12142     // We allow integer constant expressions in all cases.
12143     } else if (DclT->isIntegralOrEnumerationType()) {
12144       // Check whether the expression is a constant expression.
12145       SourceLocation Loc;
12146       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12147         // In C++11, a non-constexpr const static data member with an
12148         // in-class initializer cannot be volatile.
12149         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12150       else if (Init->isValueDependent())
12151         ; // Nothing to check.
12152       else if (Init->isIntegerConstantExpr(Context, &Loc))
12153         ; // Ok, it's an ICE!
12154       else if (Init->getType()->isScopedEnumeralType() &&
12155                Init->isCXX11ConstantExpr(Context))
12156         ; // Ok, it is a scoped-enum constant expression.
12157       else if (Init->isEvaluatable(Context)) {
12158         // If we can constant fold the initializer through heroics, accept it,
12159         // but report this as a use of an extension for -pedantic.
12160         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12161           << Init->getSourceRange();
12162       } else {
12163         // Otherwise, this is some crazy unknown case.  Report the issue at the
12164         // location provided by the isIntegerConstantExpr failed check.
12165         Diag(Loc, diag::err_in_class_initializer_non_constant)
12166           << Init->getSourceRange();
12167         VDecl->setInvalidDecl();
12168       }
12169 
12170     // We allow foldable floating-point constants as an extension.
12171     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12172       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12173       // it anyway and provide a fixit to add the 'constexpr'.
12174       if (getLangOpts().CPlusPlus11) {
12175         Diag(VDecl->getLocation(),
12176              diag::ext_in_class_initializer_float_type_cxx11)
12177             << DclT << Init->getSourceRange();
12178         Diag(VDecl->getBeginLoc(),
12179              diag::note_in_class_initializer_float_type_cxx11)
12180             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12181       } else {
12182         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12183           << DclT << Init->getSourceRange();
12184 
12185         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12186           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12187             << Init->getSourceRange();
12188           VDecl->setInvalidDecl();
12189         }
12190       }
12191 
12192     // Suggest adding 'constexpr' in C++11 for literal types.
12193     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12194       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12195           << DclT << Init->getSourceRange()
12196           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12197       VDecl->setConstexpr(true);
12198 
12199     } else {
12200       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12201         << DclT << Init->getSourceRange();
12202       VDecl->setInvalidDecl();
12203     }
12204   } else if (VDecl->isFileVarDecl()) {
12205     // In C, extern is typically used to avoid tentative definitions when
12206     // declaring variables in headers, but adding an intializer makes it a
12207     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12208     // In C++, extern is often used to give implictly static const variables
12209     // external linkage, so don't warn in that case. If selectany is present,
12210     // this might be header code intended for C and C++ inclusion, so apply the
12211     // C++ rules.
12212     if (VDecl->getStorageClass() == SC_Extern &&
12213         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12214          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12215         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12216         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12217       Diag(VDecl->getLocation(), diag::warn_extern_init);
12218 
12219     // In Microsoft C++ mode, a const variable defined in namespace scope has
12220     // external linkage by default if the variable is declared with
12221     // __declspec(dllexport).
12222     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12223         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12224         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12225       VDecl->setStorageClass(SC_Extern);
12226 
12227     // C99 6.7.8p4. All file scoped initializers need to be constant.
12228     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12229       CheckForConstantInitializer(Init, DclT);
12230   }
12231 
12232   QualType InitType = Init->getType();
12233   if (!InitType.isNull() &&
12234       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12235        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12236     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12237 
12238   // We will represent direct-initialization similarly to copy-initialization:
12239   //    int x(1);  -as-> int x = 1;
12240   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12241   //
12242   // Clients that want to distinguish between the two forms, can check for
12243   // direct initializer using VarDecl::getInitStyle().
12244   // A major benefit is that clients that don't particularly care about which
12245   // exactly form was it (like the CodeGen) can handle both cases without
12246   // special case code.
12247 
12248   // C++ 8.5p11:
12249   // The form of initialization (using parentheses or '=') is generally
12250   // insignificant, but does matter when the entity being initialized has a
12251   // class type.
12252   if (CXXDirectInit) {
12253     assert(DirectInit && "Call-style initializer must be direct init.");
12254     VDecl->setInitStyle(VarDecl::CallInit);
12255   } else if (DirectInit) {
12256     // This must be list-initialization. No other way is direct-initialization.
12257     VDecl->setInitStyle(VarDecl::ListInit);
12258   }
12259 
12260   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12261     DeclsToCheckForDeferredDiags.push_back(VDecl);
12262   CheckCompleteVariableDeclaration(VDecl);
12263 }
12264 
12265 /// ActOnInitializerError - Given that there was an error parsing an
12266 /// initializer for the given declaration, try to return to some form
12267 /// of sanity.
12268 void Sema::ActOnInitializerError(Decl *D) {
12269   // Our main concern here is re-establishing invariants like "a
12270   // variable's type is either dependent or complete".
12271   if (!D || D->isInvalidDecl()) return;
12272 
12273   VarDecl *VD = dyn_cast<VarDecl>(D);
12274   if (!VD) return;
12275 
12276   // Bindings are not usable if we can't make sense of the initializer.
12277   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12278     for (auto *BD : DD->bindings())
12279       BD->setInvalidDecl();
12280 
12281   // Auto types are meaningless if we can't make sense of the initializer.
12282   if (ParsingInitForAutoVars.count(D)) {
12283     D->setInvalidDecl();
12284     return;
12285   }
12286 
12287   QualType Ty = VD->getType();
12288   if (Ty->isDependentType()) return;
12289 
12290   // Require a complete type.
12291   if (RequireCompleteType(VD->getLocation(),
12292                           Context.getBaseElementType(Ty),
12293                           diag::err_typecheck_decl_incomplete_type)) {
12294     VD->setInvalidDecl();
12295     return;
12296   }
12297 
12298   // Require a non-abstract type.
12299   if (RequireNonAbstractType(VD->getLocation(), Ty,
12300                              diag::err_abstract_type_in_decl,
12301                              AbstractVariableType)) {
12302     VD->setInvalidDecl();
12303     return;
12304   }
12305 
12306   // Don't bother complaining about constructors or destructors,
12307   // though.
12308 }
12309 
12310 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12311   // If there is no declaration, there was an error parsing it. Just ignore it.
12312   if (!RealDecl)
12313     return;
12314 
12315   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12316     QualType Type = Var->getType();
12317 
12318     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12319     if (isa<DecompositionDecl>(RealDecl)) {
12320       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12321       Var->setInvalidDecl();
12322       return;
12323     }
12324 
12325     if (Type->isUndeducedType() &&
12326         DeduceVariableDeclarationType(Var, false, nullptr))
12327       return;
12328 
12329     // C++11 [class.static.data]p3: A static data member can be declared with
12330     // the constexpr specifier; if so, its declaration shall specify
12331     // a brace-or-equal-initializer.
12332     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12333     // the definition of a variable [...] or the declaration of a static data
12334     // member.
12335     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12336         !Var->isThisDeclarationADemotedDefinition()) {
12337       if (Var->isStaticDataMember()) {
12338         // C++1z removes the relevant rule; the in-class declaration is always
12339         // a definition there.
12340         if (!getLangOpts().CPlusPlus17 &&
12341             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12342           Diag(Var->getLocation(),
12343                diag::err_constexpr_static_mem_var_requires_init)
12344             << Var->getDeclName();
12345           Var->setInvalidDecl();
12346           return;
12347         }
12348       } else {
12349         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12350         Var->setInvalidDecl();
12351         return;
12352       }
12353     }
12354 
12355     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12356     // be initialized.
12357     if (!Var->isInvalidDecl() &&
12358         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12359         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12360       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12361       Var->setInvalidDecl();
12362       return;
12363     }
12364 
12365     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12366       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12367         if (!RD->hasTrivialDefaultConstructor()) {
12368           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12369           Var->setInvalidDecl();
12370           return;
12371         }
12372       }
12373       if (Var->getStorageClass() == SC_Extern) {
12374         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12375             << Var;
12376         Var->setInvalidDecl();
12377         return;
12378       }
12379     }
12380 
12381     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12382     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12383         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12384       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12385                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12386 
12387 
12388     switch (DefKind) {
12389     case VarDecl::Definition:
12390       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12391         break;
12392 
12393       // We have an out-of-line definition of a static data member
12394       // that has an in-class initializer, so we type-check this like
12395       // a declaration.
12396       //
12397       LLVM_FALLTHROUGH;
12398 
12399     case VarDecl::DeclarationOnly:
12400       // It's only a declaration.
12401 
12402       // Block scope. C99 6.7p7: If an identifier for an object is
12403       // declared with no linkage (C99 6.2.2p6), the type for the
12404       // object shall be complete.
12405       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12406           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12407           RequireCompleteType(Var->getLocation(), Type,
12408                               diag::err_typecheck_decl_incomplete_type))
12409         Var->setInvalidDecl();
12410 
12411       // Make sure that the type is not abstract.
12412       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12413           RequireNonAbstractType(Var->getLocation(), Type,
12414                                  diag::err_abstract_type_in_decl,
12415                                  AbstractVariableType))
12416         Var->setInvalidDecl();
12417       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12418           Var->getStorageClass() == SC_PrivateExtern) {
12419         Diag(Var->getLocation(), diag::warn_private_extern);
12420         Diag(Var->getLocation(), diag::note_private_extern);
12421       }
12422 
12423       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12424           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12425         ExternalDeclarations.push_back(Var);
12426 
12427       return;
12428 
12429     case VarDecl::TentativeDefinition:
12430       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12431       // object that has file scope without an initializer, and without a
12432       // storage-class specifier or with the storage-class specifier "static",
12433       // constitutes a tentative definition. Note: A tentative definition with
12434       // external linkage is valid (C99 6.2.2p5).
12435       if (!Var->isInvalidDecl()) {
12436         if (const IncompleteArrayType *ArrayT
12437                                     = Context.getAsIncompleteArrayType(Type)) {
12438           if (RequireCompleteSizedType(
12439                   Var->getLocation(), ArrayT->getElementType(),
12440                   diag::err_array_incomplete_or_sizeless_type))
12441             Var->setInvalidDecl();
12442         } else if (Var->getStorageClass() == SC_Static) {
12443           // C99 6.9.2p3: If the declaration of an identifier for an object is
12444           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12445           // declared type shall not be an incomplete type.
12446           // NOTE: code such as the following
12447           //     static struct s;
12448           //     struct s { int a; };
12449           // is accepted by gcc. Hence here we issue a warning instead of
12450           // an error and we do not invalidate the static declaration.
12451           // NOTE: to avoid multiple warnings, only check the first declaration.
12452           if (Var->isFirstDecl())
12453             RequireCompleteType(Var->getLocation(), Type,
12454                                 diag::ext_typecheck_decl_incomplete_type);
12455         }
12456       }
12457 
12458       // Record the tentative definition; we're done.
12459       if (!Var->isInvalidDecl())
12460         TentativeDefinitions.push_back(Var);
12461       return;
12462     }
12463 
12464     // Provide a specific diagnostic for uninitialized variable
12465     // definitions with incomplete array type.
12466     if (Type->isIncompleteArrayType()) {
12467       Diag(Var->getLocation(),
12468            diag::err_typecheck_incomplete_array_needs_initializer);
12469       Var->setInvalidDecl();
12470       return;
12471     }
12472 
12473     // Provide a specific diagnostic for uninitialized variable
12474     // definitions with reference type.
12475     if (Type->isReferenceType()) {
12476       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12477         << Var->getDeclName()
12478         << SourceRange(Var->getLocation(), Var->getLocation());
12479       Var->setInvalidDecl();
12480       return;
12481     }
12482 
12483     // Do not attempt to type-check the default initializer for a
12484     // variable with dependent type.
12485     if (Type->isDependentType())
12486       return;
12487 
12488     if (Var->isInvalidDecl())
12489       return;
12490 
12491     if (!Var->hasAttr<AliasAttr>()) {
12492       if (RequireCompleteType(Var->getLocation(),
12493                               Context.getBaseElementType(Type),
12494                               diag::err_typecheck_decl_incomplete_type)) {
12495         Var->setInvalidDecl();
12496         return;
12497       }
12498     } else {
12499       return;
12500     }
12501 
12502     // The variable can not have an abstract class type.
12503     if (RequireNonAbstractType(Var->getLocation(), Type,
12504                                diag::err_abstract_type_in_decl,
12505                                AbstractVariableType)) {
12506       Var->setInvalidDecl();
12507       return;
12508     }
12509 
12510     // Check for jumps past the implicit initializer.  C++0x
12511     // clarifies that this applies to a "variable with automatic
12512     // storage duration", not a "local variable".
12513     // C++11 [stmt.dcl]p3
12514     //   A program that jumps from a point where a variable with automatic
12515     //   storage duration is not in scope to a point where it is in scope is
12516     //   ill-formed unless the variable has scalar type, class type with a
12517     //   trivial default constructor and a trivial destructor, a cv-qualified
12518     //   version of one of these types, or an array of one of the preceding
12519     //   types and is declared without an initializer.
12520     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12521       if (const RecordType *Record
12522             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12523         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12524         // Mark the function (if we're in one) for further checking even if the
12525         // looser rules of C++11 do not require such checks, so that we can
12526         // diagnose incompatibilities with C++98.
12527         if (!CXXRecord->isPOD())
12528           setFunctionHasBranchProtectedScope();
12529       }
12530     }
12531     // In OpenCL, we can't initialize objects in the __local address space,
12532     // even implicitly, so don't synthesize an implicit initializer.
12533     if (getLangOpts().OpenCL &&
12534         Var->getType().getAddressSpace() == LangAS::opencl_local)
12535       return;
12536     // C++03 [dcl.init]p9:
12537     //   If no initializer is specified for an object, and the
12538     //   object is of (possibly cv-qualified) non-POD class type (or
12539     //   array thereof), the object shall be default-initialized; if
12540     //   the object is of const-qualified type, the underlying class
12541     //   type shall have a user-declared default
12542     //   constructor. Otherwise, if no initializer is specified for
12543     //   a non- static object, the object and its subobjects, if
12544     //   any, have an indeterminate initial value); if the object
12545     //   or any of its subobjects are of const-qualified type, the
12546     //   program is ill-formed.
12547     // C++0x [dcl.init]p11:
12548     //   If no initializer is specified for an object, the object is
12549     //   default-initialized; [...].
12550     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12551     InitializationKind Kind
12552       = InitializationKind::CreateDefault(Var->getLocation());
12553 
12554     InitializationSequence InitSeq(*this, Entity, Kind, None);
12555     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12556     if (Init.isInvalid())
12557       Var->setInvalidDecl();
12558     else if (Init.get()) {
12559       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12560       // This is important for template substitution.
12561       Var->setInitStyle(VarDecl::CallInit);
12562     }
12563 
12564     CheckCompleteVariableDeclaration(Var);
12565   }
12566 }
12567 
12568 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12569   // If there is no declaration, there was an error parsing it. Ignore it.
12570   if (!D)
12571     return;
12572 
12573   VarDecl *VD = dyn_cast<VarDecl>(D);
12574   if (!VD) {
12575     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12576     D->setInvalidDecl();
12577     return;
12578   }
12579 
12580   VD->setCXXForRangeDecl(true);
12581 
12582   // for-range-declaration cannot be given a storage class specifier.
12583   int Error = -1;
12584   switch (VD->getStorageClass()) {
12585   case SC_None:
12586     break;
12587   case SC_Extern:
12588     Error = 0;
12589     break;
12590   case SC_Static:
12591     Error = 1;
12592     break;
12593   case SC_PrivateExtern:
12594     Error = 2;
12595     break;
12596   case SC_Auto:
12597     Error = 3;
12598     break;
12599   case SC_Register:
12600     Error = 4;
12601     break;
12602   }
12603   if (Error != -1) {
12604     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12605       << VD->getDeclName() << Error;
12606     D->setInvalidDecl();
12607   }
12608 }
12609 
12610 StmtResult
12611 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12612                                  IdentifierInfo *Ident,
12613                                  ParsedAttributes &Attrs,
12614                                  SourceLocation AttrEnd) {
12615   // C++1y [stmt.iter]p1:
12616   //   A range-based for statement of the form
12617   //      for ( for-range-identifier : for-range-initializer ) statement
12618   //   is equivalent to
12619   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12620   DeclSpec DS(Attrs.getPool().getFactory());
12621 
12622   const char *PrevSpec;
12623   unsigned DiagID;
12624   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12625                      getPrintingPolicy());
12626 
12627   Declarator D(DS, DeclaratorContext::ForContext);
12628   D.SetIdentifier(Ident, IdentLoc);
12629   D.takeAttributes(Attrs, AttrEnd);
12630 
12631   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12632                 IdentLoc);
12633   Decl *Var = ActOnDeclarator(S, D);
12634   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12635   FinalizeDeclaration(Var);
12636   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12637                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12638 }
12639 
12640 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12641   if (var->isInvalidDecl()) return;
12642 
12643   if (getLangOpts().OpenCL) {
12644     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12645     // initialiser
12646     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12647         !var->hasInit()) {
12648       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12649           << 1 /*Init*/;
12650       var->setInvalidDecl();
12651       return;
12652     }
12653   }
12654 
12655   // In Objective-C, don't allow jumps past the implicit initialization of a
12656   // local retaining variable.
12657   if (getLangOpts().ObjC &&
12658       var->hasLocalStorage()) {
12659     switch (var->getType().getObjCLifetime()) {
12660     case Qualifiers::OCL_None:
12661     case Qualifiers::OCL_ExplicitNone:
12662     case Qualifiers::OCL_Autoreleasing:
12663       break;
12664 
12665     case Qualifiers::OCL_Weak:
12666     case Qualifiers::OCL_Strong:
12667       setFunctionHasBranchProtectedScope();
12668       break;
12669     }
12670   }
12671 
12672   if (var->hasLocalStorage() &&
12673       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12674     setFunctionHasBranchProtectedScope();
12675 
12676   // Warn about externally-visible variables being defined without a
12677   // prior declaration.  We only want to do this for global
12678   // declarations, but we also specifically need to avoid doing it for
12679   // class members because the linkage of an anonymous class can
12680   // change if it's later given a typedef name.
12681   if (var->isThisDeclarationADefinition() &&
12682       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12683       var->isExternallyVisible() && var->hasLinkage() &&
12684       !var->isInline() && !var->getDescribedVarTemplate() &&
12685       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12686       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12687       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12688                                   var->getLocation())) {
12689     // Find a previous declaration that's not a definition.
12690     VarDecl *prev = var->getPreviousDecl();
12691     while (prev && prev->isThisDeclarationADefinition())
12692       prev = prev->getPreviousDecl();
12693 
12694     if (!prev) {
12695       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12696       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12697           << /* variable */ 0;
12698     }
12699   }
12700 
12701   // Cache the result of checking for constant initialization.
12702   Optional<bool> CacheHasConstInit;
12703   const Expr *CacheCulprit = nullptr;
12704   auto checkConstInit = [&]() mutable {
12705     if (!CacheHasConstInit)
12706       CacheHasConstInit = var->getInit()->isConstantInitializer(
12707             Context, var->getType()->isReferenceType(), &CacheCulprit);
12708     return *CacheHasConstInit;
12709   };
12710 
12711   if (var->getTLSKind() == VarDecl::TLS_Static) {
12712     if (var->getType().isDestructedType()) {
12713       // GNU C++98 edits for __thread, [basic.start.term]p3:
12714       //   The type of an object with thread storage duration shall not
12715       //   have a non-trivial destructor.
12716       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12717       if (getLangOpts().CPlusPlus11)
12718         Diag(var->getLocation(), diag::note_use_thread_local);
12719     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12720       if (!checkConstInit()) {
12721         // GNU C++98 edits for __thread, [basic.start.init]p4:
12722         //   An object of thread storage duration shall not require dynamic
12723         //   initialization.
12724         // FIXME: Need strict checking here.
12725         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12726           << CacheCulprit->getSourceRange();
12727         if (getLangOpts().CPlusPlus11)
12728           Diag(var->getLocation(), diag::note_use_thread_local);
12729       }
12730     }
12731   }
12732 
12733   // Apply section attributes and pragmas to global variables.
12734   bool GlobalStorage = var->hasGlobalStorage();
12735   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12736       !inTemplateInstantiation()) {
12737     PragmaStack<StringLiteral *> *Stack = nullptr;
12738     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12739     if (var->getType().isConstQualified())
12740       Stack = &ConstSegStack;
12741     else if (!var->getInit()) {
12742       Stack = &BSSSegStack;
12743       SectionFlags |= ASTContext::PSF_Write;
12744     } else {
12745       Stack = &DataSegStack;
12746       SectionFlags |= ASTContext::PSF_Write;
12747     }
12748     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12749       var->addAttr(SectionAttr::CreateImplicit(
12750           Context, Stack->CurrentValue->getString(),
12751           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12752           SectionAttr::Declspec_allocate));
12753     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12754       if (UnifySection(SA->getName(), SectionFlags, var))
12755         var->dropAttr<SectionAttr>();
12756 
12757     // Apply the init_seg attribute if this has an initializer.  If the
12758     // initializer turns out to not be dynamic, we'll end up ignoring this
12759     // attribute.
12760     if (CurInitSeg && var->getInit())
12761       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12762                                                CurInitSegLoc,
12763                                                AttributeCommonInfo::AS_Pragma));
12764   }
12765 
12766   // All the following checks are C++ only.
12767   if (!getLangOpts().CPlusPlus) {
12768       // If this variable must be emitted, add it as an initializer for the
12769       // current module.
12770      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12771        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12772      return;
12773   }
12774 
12775   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12776     CheckCompleteDecompositionDeclaration(DD);
12777 
12778   QualType type = var->getType();
12779   if (type->isDependentType()) return;
12780 
12781   if (var->hasAttr<BlocksAttr>())
12782     getCurFunction()->addByrefBlockVar(var);
12783 
12784   Expr *Init = var->getInit();
12785   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12786   QualType baseType = Context.getBaseElementType(type);
12787 
12788   if (Init && !Init->isValueDependent()) {
12789     if (var->isConstexpr()) {
12790       SmallVector<PartialDiagnosticAt, 8> Notes;
12791       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12792         SourceLocation DiagLoc = var->getLocation();
12793         // If the note doesn't add any useful information other than a source
12794         // location, fold it into the primary diagnostic.
12795         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12796               diag::note_invalid_subexpr_in_const_expr) {
12797           DiagLoc = Notes[0].first;
12798           Notes.clear();
12799         }
12800         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12801           << var << Init->getSourceRange();
12802         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12803           Diag(Notes[I].first, Notes[I].second);
12804       }
12805     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12806       // Check whether the initializer of a const variable of integral or
12807       // enumeration type is an ICE now, since we can't tell whether it was
12808       // initialized by a constant expression if we check later.
12809       var->checkInitIsICE();
12810     }
12811 
12812     // Don't emit further diagnostics about constexpr globals since they
12813     // were just diagnosed.
12814     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12815       // FIXME: Need strict checking in C++03 here.
12816       bool DiagErr = getLangOpts().CPlusPlus11
12817           ? !var->checkInitIsICE() : !checkConstInit();
12818       if (DiagErr) {
12819         auto *Attr = var->getAttr<ConstInitAttr>();
12820         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12821           << Init->getSourceRange();
12822         Diag(Attr->getLocation(),
12823              diag::note_declared_required_constant_init_here)
12824             << Attr->getRange() << Attr->isConstinit();
12825         if (getLangOpts().CPlusPlus11) {
12826           APValue Value;
12827           SmallVector<PartialDiagnosticAt, 8> Notes;
12828           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12829           for (auto &it : Notes)
12830             Diag(it.first, it.second);
12831         } else {
12832           Diag(CacheCulprit->getExprLoc(),
12833                diag::note_invalid_subexpr_in_const_expr)
12834               << CacheCulprit->getSourceRange();
12835         }
12836       }
12837     }
12838     else if (!var->isConstexpr() && IsGlobal &&
12839              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12840                                     var->getLocation())) {
12841       // Warn about globals which don't have a constant initializer.  Don't
12842       // warn about globals with a non-trivial destructor because we already
12843       // warned about them.
12844       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12845       if (!(RD && !RD->hasTrivialDestructor())) {
12846         if (!checkConstInit())
12847           Diag(var->getLocation(), diag::warn_global_constructor)
12848             << Init->getSourceRange();
12849       }
12850     }
12851   }
12852 
12853   // Require the destructor.
12854   if (const RecordType *recordType = baseType->getAs<RecordType>())
12855     FinalizeVarWithDestructor(var, recordType);
12856 
12857   // If this variable must be emitted, add it as an initializer for the current
12858   // module.
12859   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12860     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12861 }
12862 
12863 /// Determines if a variable's alignment is dependent.
12864 static bool hasDependentAlignment(VarDecl *VD) {
12865   if (VD->getType()->isDependentType())
12866     return true;
12867   for (auto *I : VD->specific_attrs<AlignedAttr>())
12868     if (I->isAlignmentDependent())
12869       return true;
12870   return false;
12871 }
12872 
12873 /// Check if VD needs to be dllexport/dllimport due to being in a
12874 /// dllexport/import function.
12875 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12876   assert(VD->isStaticLocal());
12877 
12878   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12879 
12880   // Find outermost function when VD is in lambda function.
12881   while (FD && !getDLLAttr(FD) &&
12882          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12883          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12884     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12885   }
12886 
12887   if (!FD)
12888     return;
12889 
12890   // Static locals inherit dll attributes from their function.
12891   if (Attr *A = getDLLAttr(FD)) {
12892     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12893     NewAttr->setInherited(true);
12894     VD->addAttr(NewAttr);
12895   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12896     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12897     NewAttr->setInherited(true);
12898     VD->addAttr(NewAttr);
12899 
12900     // Export this function to enforce exporting this static variable even
12901     // if it is not used in this compilation unit.
12902     if (!FD->hasAttr<DLLExportAttr>())
12903       FD->addAttr(NewAttr);
12904 
12905   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12906     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12907     NewAttr->setInherited(true);
12908     VD->addAttr(NewAttr);
12909   }
12910 }
12911 
12912 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12913 /// any semantic actions necessary after any initializer has been attached.
12914 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12915   // Note that we are no longer parsing the initializer for this declaration.
12916   ParsingInitForAutoVars.erase(ThisDecl);
12917 
12918   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12919   if (!VD)
12920     return;
12921 
12922   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12923   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12924       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12925     if (PragmaClangBSSSection.Valid)
12926       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12927           Context, PragmaClangBSSSection.SectionName,
12928           PragmaClangBSSSection.PragmaLocation,
12929           AttributeCommonInfo::AS_Pragma));
12930     if (PragmaClangDataSection.Valid)
12931       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12932           Context, PragmaClangDataSection.SectionName,
12933           PragmaClangDataSection.PragmaLocation,
12934           AttributeCommonInfo::AS_Pragma));
12935     if (PragmaClangRodataSection.Valid)
12936       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12937           Context, PragmaClangRodataSection.SectionName,
12938           PragmaClangRodataSection.PragmaLocation,
12939           AttributeCommonInfo::AS_Pragma));
12940     if (PragmaClangRelroSection.Valid)
12941       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12942           Context, PragmaClangRelroSection.SectionName,
12943           PragmaClangRelroSection.PragmaLocation,
12944           AttributeCommonInfo::AS_Pragma));
12945   }
12946 
12947   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12948     for (auto *BD : DD->bindings()) {
12949       FinalizeDeclaration(BD);
12950     }
12951   }
12952 
12953   checkAttributesAfterMerging(*this, *VD);
12954 
12955   // Perform TLS alignment check here after attributes attached to the variable
12956   // which may affect the alignment have been processed. Only perform the check
12957   // if the target has a maximum TLS alignment (zero means no constraints).
12958   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12959     // Protect the check so that it's not performed on dependent types and
12960     // dependent alignments (we can't determine the alignment in that case).
12961     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12962         !VD->isInvalidDecl()) {
12963       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12964       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12965         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12966           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12967           << (unsigned)MaxAlignChars.getQuantity();
12968       }
12969     }
12970   }
12971 
12972   if (VD->isStaticLocal()) {
12973     CheckStaticLocalForDllExport(VD);
12974 
12975     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12976       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12977       // function, only __shared__ variables or variables without any device
12978       // memory qualifiers may be declared with static storage class.
12979       // Note: It is unclear how a function-scope non-const static variable
12980       // without device memory qualifier is implemented, therefore only static
12981       // const variable without device memory qualifier is allowed.
12982       [&]() {
12983         if (!getLangOpts().CUDA)
12984           return;
12985         if (VD->hasAttr<CUDASharedAttr>())
12986           return;
12987         if (VD->getType().isConstQualified() &&
12988             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12989           return;
12990         if (CUDADiagIfDeviceCode(VD->getLocation(),
12991                                  diag::err_device_static_local_var)
12992             << CurrentCUDATarget())
12993           VD->setInvalidDecl();
12994       }();
12995     }
12996   }
12997 
12998   // Perform check for initializers of device-side global variables.
12999   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13000   // 7.5). We must also apply the same checks to all __shared__
13001   // variables whether they are local or not. CUDA also allows
13002   // constant initializers for __constant__ and __device__ variables.
13003   if (getLangOpts().CUDA)
13004     checkAllowedCUDAInitializer(VD);
13005 
13006   // Grab the dllimport or dllexport attribute off of the VarDecl.
13007   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13008 
13009   // Imported static data members cannot be defined out-of-line.
13010   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13011     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13012         VD->isThisDeclarationADefinition()) {
13013       // We allow definitions of dllimport class template static data members
13014       // with a warning.
13015       CXXRecordDecl *Context =
13016         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13017       bool IsClassTemplateMember =
13018           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13019           Context->getDescribedClassTemplate();
13020 
13021       Diag(VD->getLocation(),
13022            IsClassTemplateMember
13023                ? diag::warn_attribute_dllimport_static_field_definition
13024                : diag::err_attribute_dllimport_static_field_definition);
13025       Diag(IA->getLocation(), diag::note_attribute);
13026       if (!IsClassTemplateMember)
13027         VD->setInvalidDecl();
13028     }
13029   }
13030 
13031   // dllimport/dllexport variables cannot be thread local, their TLS index
13032   // isn't exported with the variable.
13033   if (DLLAttr && VD->getTLSKind()) {
13034     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13035     if (F && getDLLAttr(F)) {
13036       assert(VD->isStaticLocal());
13037       // But if this is a static local in a dlimport/dllexport function, the
13038       // function will never be inlined, which means the var would never be
13039       // imported, so having it marked import/export is safe.
13040     } else {
13041       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13042                                                                     << DLLAttr;
13043       VD->setInvalidDecl();
13044     }
13045   }
13046 
13047   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13048     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13049       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13050       VD->dropAttr<UsedAttr>();
13051     }
13052   }
13053 
13054   const DeclContext *DC = VD->getDeclContext();
13055   // If there's a #pragma GCC visibility in scope, and this isn't a class
13056   // member, set the visibility of this variable.
13057   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13058     AddPushedVisibilityAttribute(VD);
13059 
13060   // FIXME: Warn on unused var template partial specializations.
13061   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13062     MarkUnusedFileScopedDecl(VD);
13063 
13064   // Now we have parsed the initializer and can update the table of magic
13065   // tag values.
13066   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13067       !VD->getType()->isIntegralOrEnumerationType())
13068     return;
13069 
13070   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13071     const Expr *MagicValueExpr = VD->getInit();
13072     if (!MagicValueExpr) {
13073       continue;
13074     }
13075     llvm::APSInt MagicValueInt;
13076     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
13077       Diag(I->getRange().getBegin(),
13078            diag::err_type_tag_for_datatype_not_ice)
13079         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13080       continue;
13081     }
13082     if (MagicValueInt.getActiveBits() > 64) {
13083       Diag(I->getRange().getBegin(),
13084            diag::err_type_tag_for_datatype_too_large)
13085         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13086       continue;
13087     }
13088     uint64_t MagicValue = MagicValueInt.getZExtValue();
13089     RegisterTypeTagForDatatype(I->getArgumentKind(),
13090                                MagicValue,
13091                                I->getMatchingCType(),
13092                                I->getLayoutCompatible(),
13093                                I->getMustBeNull());
13094   }
13095 }
13096 
13097 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13098   auto *VD = dyn_cast<VarDecl>(DD);
13099   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13100 }
13101 
13102 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13103                                                    ArrayRef<Decl *> Group) {
13104   SmallVector<Decl*, 8> Decls;
13105 
13106   if (DS.isTypeSpecOwned())
13107     Decls.push_back(DS.getRepAsDecl());
13108 
13109   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13110   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13111   bool DiagnosedMultipleDecomps = false;
13112   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13113   bool DiagnosedNonDeducedAuto = false;
13114 
13115   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13116     if (Decl *D = Group[i]) {
13117       // For declarators, there are some additional syntactic-ish checks we need
13118       // to perform.
13119       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13120         if (!FirstDeclaratorInGroup)
13121           FirstDeclaratorInGroup = DD;
13122         if (!FirstDecompDeclaratorInGroup)
13123           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13124         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13125             !hasDeducedAuto(DD))
13126           FirstNonDeducedAutoInGroup = DD;
13127 
13128         if (FirstDeclaratorInGroup != DD) {
13129           // A decomposition declaration cannot be combined with any other
13130           // declaration in the same group.
13131           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13132             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13133                  diag::err_decomp_decl_not_alone)
13134                 << FirstDeclaratorInGroup->getSourceRange()
13135                 << DD->getSourceRange();
13136             DiagnosedMultipleDecomps = true;
13137           }
13138 
13139           // A declarator that uses 'auto' in any way other than to declare a
13140           // variable with a deduced type cannot be combined with any other
13141           // declarator in the same group.
13142           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13143             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13144                  diag::err_auto_non_deduced_not_alone)
13145                 << FirstNonDeducedAutoInGroup->getType()
13146                        ->hasAutoForTrailingReturnType()
13147                 << FirstDeclaratorInGroup->getSourceRange()
13148                 << DD->getSourceRange();
13149             DiagnosedNonDeducedAuto = true;
13150           }
13151         }
13152       }
13153 
13154       Decls.push_back(D);
13155     }
13156   }
13157 
13158   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13159     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13160       handleTagNumbering(Tag, S);
13161       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13162           getLangOpts().CPlusPlus)
13163         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13164     }
13165   }
13166 
13167   return BuildDeclaratorGroup(Decls);
13168 }
13169 
13170 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13171 /// group, performing any necessary semantic checking.
13172 Sema::DeclGroupPtrTy
13173 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13174   // C++14 [dcl.spec.auto]p7: (DR1347)
13175   //   If the type that replaces the placeholder type is not the same in each
13176   //   deduction, the program is ill-formed.
13177   if (Group.size() > 1) {
13178     QualType Deduced;
13179     VarDecl *DeducedDecl = nullptr;
13180     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13181       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13182       if (!D || D->isInvalidDecl())
13183         break;
13184       DeducedType *DT = D->getType()->getContainedDeducedType();
13185       if (!DT || DT->getDeducedType().isNull())
13186         continue;
13187       if (Deduced.isNull()) {
13188         Deduced = DT->getDeducedType();
13189         DeducedDecl = D;
13190       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13191         auto *AT = dyn_cast<AutoType>(DT);
13192         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13193              diag::err_auto_different_deductions)
13194           << (AT ? (unsigned)AT->getKeyword() : 3)
13195           << Deduced << DeducedDecl->getDeclName()
13196           << DT->getDeducedType() << D->getDeclName()
13197           << DeducedDecl->getInit()->getSourceRange()
13198           << D->getInit()->getSourceRange();
13199         D->setInvalidDecl();
13200         break;
13201       }
13202     }
13203   }
13204 
13205   ActOnDocumentableDecls(Group);
13206 
13207   return DeclGroupPtrTy::make(
13208       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13209 }
13210 
13211 void Sema::ActOnDocumentableDecl(Decl *D) {
13212   ActOnDocumentableDecls(D);
13213 }
13214 
13215 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13216   // Don't parse the comment if Doxygen diagnostics are ignored.
13217   if (Group.empty() || !Group[0])
13218     return;
13219 
13220   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13221                       Group[0]->getLocation()) &&
13222       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13223                       Group[0]->getLocation()))
13224     return;
13225 
13226   if (Group.size() >= 2) {
13227     // This is a decl group.  Normally it will contain only declarations
13228     // produced from declarator list.  But in case we have any definitions or
13229     // additional declaration references:
13230     //   'typedef struct S {} S;'
13231     //   'typedef struct S *S;'
13232     //   'struct S *pS;'
13233     // FinalizeDeclaratorGroup adds these as separate declarations.
13234     Decl *MaybeTagDecl = Group[0];
13235     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13236       Group = Group.slice(1);
13237     }
13238   }
13239 
13240   // FIMXE: We assume every Decl in the group is in the same file.
13241   // This is false when preprocessor constructs the group from decls in
13242   // different files (e. g. macros or #include).
13243   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13244 }
13245 
13246 /// Common checks for a parameter-declaration that should apply to both function
13247 /// parameters and non-type template parameters.
13248 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13249   // Check that there are no default arguments inside the type of this
13250   // parameter.
13251   if (getLangOpts().CPlusPlus)
13252     CheckExtraCXXDefaultArguments(D);
13253 
13254   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13255   if (D.getCXXScopeSpec().isSet()) {
13256     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13257       << D.getCXXScopeSpec().getRange();
13258   }
13259 
13260   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13261   // simple identifier except [...irrelevant cases...].
13262   switch (D.getName().getKind()) {
13263   case UnqualifiedIdKind::IK_Identifier:
13264     break;
13265 
13266   case UnqualifiedIdKind::IK_OperatorFunctionId:
13267   case UnqualifiedIdKind::IK_ConversionFunctionId:
13268   case UnqualifiedIdKind::IK_LiteralOperatorId:
13269   case UnqualifiedIdKind::IK_ConstructorName:
13270   case UnqualifiedIdKind::IK_DestructorName:
13271   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13272   case UnqualifiedIdKind::IK_DeductionGuideName:
13273     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13274       << GetNameForDeclarator(D).getName();
13275     break;
13276 
13277   case UnqualifiedIdKind::IK_TemplateId:
13278   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13279     // GetNameForDeclarator would not produce a useful name in this case.
13280     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13281     break;
13282   }
13283 }
13284 
13285 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13286 /// to introduce parameters into function prototype scope.
13287 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13288   const DeclSpec &DS = D.getDeclSpec();
13289 
13290   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13291 
13292   // C++03 [dcl.stc]p2 also permits 'auto'.
13293   StorageClass SC = SC_None;
13294   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13295     SC = SC_Register;
13296     // In C++11, the 'register' storage class specifier is deprecated.
13297     // In C++17, it is not allowed, but we tolerate it as an extension.
13298     if (getLangOpts().CPlusPlus11) {
13299       Diag(DS.getStorageClassSpecLoc(),
13300            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13301                                      : diag::warn_deprecated_register)
13302         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13303     }
13304   } else if (getLangOpts().CPlusPlus &&
13305              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13306     SC = SC_Auto;
13307   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13308     Diag(DS.getStorageClassSpecLoc(),
13309          diag::err_invalid_storage_class_in_func_decl);
13310     D.getMutableDeclSpec().ClearStorageClassSpecs();
13311   }
13312 
13313   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13314     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13315       << DeclSpec::getSpecifierName(TSCS);
13316   if (DS.isInlineSpecified())
13317     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13318         << getLangOpts().CPlusPlus17;
13319   if (DS.hasConstexprSpecifier())
13320     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13321         << 0 << D.getDeclSpec().getConstexprSpecifier();
13322 
13323   DiagnoseFunctionSpecifiers(DS);
13324 
13325   CheckFunctionOrTemplateParamDeclarator(S, D);
13326 
13327   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13328   QualType parmDeclType = TInfo->getType();
13329 
13330   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13331   IdentifierInfo *II = D.getIdentifier();
13332   if (II) {
13333     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13334                    ForVisibleRedeclaration);
13335     LookupName(R, S);
13336     if (R.isSingleResult()) {
13337       NamedDecl *PrevDecl = R.getFoundDecl();
13338       if (PrevDecl->isTemplateParameter()) {
13339         // Maybe we will complain about the shadowed template parameter.
13340         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13341         // Just pretend that we didn't see the previous declaration.
13342         PrevDecl = nullptr;
13343       } else if (S->isDeclScope(PrevDecl)) {
13344         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13345         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13346 
13347         // Recover by removing the name
13348         II = nullptr;
13349         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13350         D.setInvalidType(true);
13351       }
13352     }
13353   }
13354 
13355   // Temporarily put parameter variables in the translation unit, not
13356   // the enclosing context.  This prevents them from accidentally
13357   // looking like class members in C++.
13358   ParmVarDecl *New =
13359       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13360                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13361 
13362   if (D.isInvalidType())
13363     New->setInvalidDecl();
13364 
13365   assert(S->isFunctionPrototypeScope());
13366   assert(S->getFunctionPrototypeDepth() >= 1);
13367   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13368                     S->getNextFunctionPrototypeIndex());
13369 
13370   // Add the parameter declaration into this scope.
13371   S->AddDecl(New);
13372   if (II)
13373     IdResolver.AddDecl(New);
13374 
13375   ProcessDeclAttributes(S, New, D);
13376 
13377   if (D.getDeclSpec().isModulePrivateSpecified())
13378     Diag(New->getLocation(), diag::err_module_private_local)
13379       << 1 << New->getDeclName()
13380       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13381       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13382 
13383   if (New->hasAttr<BlocksAttr>()) {
13384     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13385   }
13386 
13387   if (getLangOpts().OpenCL)
13388     deduceOpenCLAddressSpace(New);
13389 
13390   return New;
13391 }
13392 
13393 /// Synthesizes a variable for a parameter arising from a
13394 /// typedef.
13395 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13396                                               SourceLocation Loc,
13397                                               QualType T) {
13398   /* FIXME: setting StartLoc == Loc.
13399      Would it be worth to modify callers so as to provide proper source
13400      location for the unnamed parameters, embedding the parameter's type? */
13401   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13402                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13403                                            SC_None, nullptr);
13404   Param->setImplicit();
13405   return Param;
13406 }
13407 
13408 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13409   // Don't diagnose unused-parameter errors in template instantiations; we
13410   // will already have done so in the template itself.
13411   if (inTemplateInstantiation())
13412     return;
13413 
13414   for (const ParmVarDecl *Parameter : Parameters) {
13415     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13416         !Parameter->hasAttr<UnusedAttr>()) {
13417       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13418         << Parameter->getDeclName();
13419     }
13420   }
13421 }
13422 
13423 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13424     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13425   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13426     return;
13427 
13428   // Warn if the return value is pass-by-value and larger than the specified
13429   // threshold.
13430   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13431     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13432     if (Size > LangOpts.NumLargeByValueCopy)
13433       Diag(D->getLocation(), diag::warn_return_value_size)
13434           << D->getDeclName() << Size;
13435   }
13436 
13437   // Warn if any parameter is pass-by-value and larger than the specified
13438   // threshold.
13439   for (const ParmVarDecl *Parameter : Parameters) {
13440     QualType T = Parameter->getType();
13441     if (T->isDependentType() || !T.isPODType(Context))
13442       continue;
13443     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13444     if (Size > LangOpts.NumLargeByValueCopy)
13445       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13446           << Parameter->getDeclName() << Size;
13447   }
13448 }
13449 
13450 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13451                                   SourceLocation NameLoc, IdentifierInfo *Name,
13452                                   QualType T, TypeSourceInfo *TSInfo,
13453                                   StorageClass SC) {
13454   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13455   if (getLangOpts().ObjCAutoRefCount &&
13456       T.getObjCLifetime() == Qualifiers::OCL_None &&
13457       T->isObjCLifetimeType()) {
13458 
13459     Qualifiers::ObjCLifetime lifetime;
13460 
13461     // Special cases for arrays:
13462     //   - if it's const, use __unsafe_unretained
13463     //   - otherwise, it's an error
13464     if (T->isArrayType()) {
13465       if (!T.isConstQualified()) {
13466         if (DelayedDiagnostics.shouldDelayDiagnostics())
13467           DelayedDiagnostics.add(
13468               sema::DelayedDiagnostic::makeForbiddenType(
13469               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13470         else
13471           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13472               << TSInfo->getTypeLoc().getSourceRange();
13473       }
13474       lifetime = Qualifiers::OCL_ExplicitNone;
13475     } else {
13476       lifetime = T->getObjCARCImplicitLifetime();
13477     }
13478     T = Context.getLifetimeQualifiedType(T, lifetime);
13479   }
13480 
13481   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13482                                          Context.getAdjustedParameterType(T),
13483                                          TSInfo, SC, nullptr);
13484 
13485   // Make a note if we created a new pack in the scope of a lambda, so that
13486   // we know that references to that pack must also be expanded within the
13487   // lambda scope.
13488   if (New->isParameterPack())
13489     if (auto *LSI = getEnclosingLambda())
13490       LSI->LocalPacks.push_back(New);
13491 
13492   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13493       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13494     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13495                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13496 
13497   // Parameters can not be abstract class types.
13498   // For record types, this is done by the AbstractClassUsageDiagnoser once
13499   // the class has been completely parsed.
13500   if (!CurContext->isRecord() &&
13501       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13502                              AbstractParamType))
13503     New->setInvalidDecl();
13504 
13505   // Parameter declarators cannot be interface types. All ObjC objects are
13506   // passed by reference.
13507   if (T->isObjCObjectType()) {
13508     SourceLocation TypeEndLoc =
13509         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13510     Diag(NameLoc,
13511          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13512       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13513     T = Context.getObjCObjectPointerType(T);
13514     New->setType(T);
13515   }
13516 
13517   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13518   // duration shall not be qualified by an address-space qualifier."
13519   // Since all parameters have automatic store duration, they can not have
13520   // an address space.
13521   if (T.getAddressSpace() != LangAS::Default &&
13522       // OpenCL allows function arguments declared to be an array of a type
13523       // to be qualified with an address space.
13524       !(getLangOpts().OpenCL &&
13525         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13526     Diag(NameLoc, diag::err_arg_with_address_space);
13527     New->setInvalidDecl();
13528   }
13529 
13530   return New;
13531 }
13532 
13533 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13534                                            SourceLocation LocAfterDecls) {
13535   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13536 
13537   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13538   // for a K&R function.
13539   if (!FTI.hasPrototype) {
13540     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13541       --i;
13542       if (FTI.Params[i].Param == nullptr) {
13543         SmallString<256> Code;
13544         llvm::raw_svector_ostream(Code)
13545             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13546         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13547             << FTI.Params[i].Ident
13548             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13549 
13550         // Implicitly declare the argument as type 'int' for lack of a better
13551         // type.
13552         AttributeFactory attrs;
13553         DeclSpec DS(attrs);
13554         const char* PrevSpec; // unused
13555         unsigned DiagID; // unused
13556         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13557                            DiagID, Context.getPrintingPolicy());
13558         // Use the identifier location for the type source range.
13559         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13560         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13561         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13562         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13563         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13564       }
13565     }
13566   }
13567 }
13568 
13569 Decl *
13570 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13571                               MultiTemplateParamsArg TemplateParameterLists,
13572                               SkipBodyInfo *SkipBody) {
13573   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13574   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13575   Scope *ParentScope = FnBodyScope->getParent();
13576 
13577   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13578   // we define a non-templated function definition, we will create a declaration
13579   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13580   // The base function declaration will have the equivalent of an `omp declare
13581   // variant` annotation which specifies the mangled definition as a
13582   // specialization function under the OpenMP context defined as part of the
13583   // `omp begin declare variant`.
13584   FunctionDecl *BaseFD = nullptr;
13585   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13586       TemplateParameterLists.empty())
13587     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13588         ParentScope, D);
13589 
13590   D.setFunctionDefinitionKind(FDK_Definition);
13591   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13592   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13593 
13594   if (BaseFD)
13595     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13596         cast<FunctionDecl>(Dcl), BaseFD);
13597 
13598   return Dcl;
13599 }
13600 
13601 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13602   Consumer.HandleInlineFunctionDefinition(D);
13603 }
13604 
13605 static bool
13606 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13607                                 const FunctionDecl *&PossiblePrototype) {
13608   // Don't warn about invalid declarations.
13609   if (FD->isInvalidDecl())
13610     return false;
13611 
13612   // Or declarations that aren't global.
13613   if (!FD->isGlobal())
13614     return false;
13615 
13616   // Don't warn about C++ member functions.
13617   if (isa<CXXMethodDecl>(FD))
13618     return false;
13619 
13620   // Don't warn about 'main'.
13621   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13622     if (IdentifierInfo *II = FD->getIdentifier())
13623       if (II->isStr("main"))
13624         return false;
13625 
13626   // Don't warn about inline functions.
13627   if (FD->isInlined())
13628     return false;
13629 
13630   // Don't warn about function templates.
13631   if (FD->getDescribedFunctionTemplate())
13632     return false;
13633 
13634   // Don't warn about function template specializations.
13635   if (FD->isFunctionTemplateSpecialization())
13636     return false;
13637 
13638   // Don't warn for OpenCL kernels.
13639   if (FD->hasAttr<OpenCLKernelAttr>())
13640     return false;
13641 
13642   // Don't warn on explicitly deleted functions.
13643   if (FD->isDeleted())
13644     return false;
13645 
13646   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13647        Prev; Prev = Prev->getPreviousDecl()) {
13648     // Ignore any declarations that occur in function or method
13649     // scope, because they aren't visible from the header.
13650     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13651       continue;
13652 
13653     PossiblePrototype = Prev;
13654     return Prev->getType()->isFunctionNoProtoType();
13655   }
13656 
13657   return true;
13658 }
13659 
13660 void
13661 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13662                                    const FunctionDecl *EffectiveDefinition,
13663                                    SkipBodyInfo *SkipBody) {
13664   const FunctionDecl *Definition = EffectiveDefinition;
13665   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13666     // If this is a friend function defined in a class template, it does not
13667     // have a body until it is used, nevertheless it is a definition, see
13668     // [temp.inst]p2:
13669     //
13670     // ... for the purpose of determining whether an instantiated redeclaration
13671     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13672     // corresponds to a definition in the template is considered to be a
13673     // definition.
13674     //
13675     // The following code must produce redefinition error:
13676     //
13677     //     template<typename T> struct C20 { friend void func_20() {} };
13678     //     C20<int> c20i;
13679     //     void func_20() {}
13680     //
13681     for (auto I : FD->redecls()) {
13682       if (I != FD && !I->isInvalidDecl() &&
13683           I->getFriendObjectKind() != Decl::FOK_None) {
13684         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13685           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13686             // A merged copy of the same function, instantiated as a member of
13687             // the same class, is OK.
13688             if (declaresSameEntity(OrigFD, Original) &&
13689                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13690                                    cast<Decl>(FD->getLexicalDeclContext())))
13691               continue;
13692           }
13693 
13694           if (Original->isThisDeclarationADefinition()) {
13695             Definition = I;
13696             break;
13697           }
13698         }
13699       }
13700     }
13701   }
13702 
13703   if (!Definition)
13704     // Similar to friend functions a friend function template may be a
13705     // definition and do not have a body if it is instantiated in a class
13706     // template.
13707     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13708       for (auto I : FTD->redecls()) {
13709         auto D = cast<FunctionTemplateDecl>(I);
13710         if (D != FTD) {
13711           assert(!D->isThisDeclarationADefinition() &&
13712                  "More than one definition in redeclaration chain");
13713           if (D->getFriendObjectKind() != Decl::FOK_None)
13714             if (FunctionTemplateDecl *FT =
13715                                        D->getInstantiatedFromMemberTemplate()) {
13716               if (FT->isThisDeclarationADefinition()) {
13717                 Definition = D->getTemplatedDecl();
13718                 break;
13719               }
13720             }
13721         }
13722       }
13723     }
13724 
13725   if (!Definition)
13726     return;
13727 
13728   if (canRedefineFunction(Definition, getLangOpts()))
13729     return;
13730 
13731   // Don't emit an error when this is redefinition of a typo-corrected
13732   // definition.
13733   if (TypoCorrectedFunctionDefinitions.count(Definition))
13734     return;
13735 
13736   // If we don't have a visible definition of the function, and it's inline or
13737   // a template, skip the new definition.
13738   if (SkipBody && !hasVisibleDefinition(Definition) &&
13739       (Definition->getFormalLinkage() == InternalLinkage ||
13740        Definition->isInlined() ||
13741        Definition->getDescribedFunctionTemplate() ||
13742        Definition->getNumTemplateParameterLists())) {
13743     SkipBody->ShouldSkip = true;
13744     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13745     if (auto *TD = Definition->getDescribedFunctionTemplate())
13746       makeMergedDefinitionVisible(TD);
13747     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13748     return;
13749   }
13750 
13751   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13752       Definition->getStorageClass() == SC_Extern)
13753     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13754         << FD->getDeclName() << getLangOpts().CPlusPlus;
13755   else
13756     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13757 
13758   Diag(Definition->getLocation(), diag::note_previous_definition);
13759   FD->setInvalidDecl();
13760 }
13761 
13762 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13763                                    Sema &S) {
13764   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13765 
13766   LambdaScopeInfo *LSI = S.PushLambdaScope();
13767   LSI->CallOperator = CallOperator;
13768   LSI->Lambda = LambdaClass;
13769   LSI->ReturnType = CallOperator->getReturnType();
13770   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13771 
13772   if (LCD == LCD_None)
13773     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13774   else if (LCD == LCD_ByCopy)
13775     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13776   else if (LCD == LCD_ByRef)
13777     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13778   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13779 
13780   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13781   LSI->Mutable = !CallOperator->isConst();
13782 
13783   // Add the captures to the LSI so they can be noted as already
13784   // captured within tryCaptureVar.
13785   auto I = LambdaClass->field_begin();
13786   for (const auto &C : LambdaClass->captures()) {
13787     if (C.capturesVariable()) {
13788       VarDecl *VD = C.getCapturedVar();
13789       if (VD->isInitCapture())
13790         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13791       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13792       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13793           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13794           /*EllipsisLoc*/C.isPackExpansion()
13795                          ? C.getEllipsisLoc() : SourceLocation(),
13796           I->getType(), /*Invalid*/false);
13797 
13798     } else if (C.capturesThis()) {
13799       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13800                           C.getCaptureKind() == LCK_StarThis);
13801     } else {
13802       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13803                              I->getType());
13804     }
13805     ++I;
13806   }
13807 }
13808 
13809 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13810                                     SkipBodyInfo *SkipBody) {
13811   if (!D) {
13812     // Parsing the function declaration failed in some way. Push on a fake scope
13813     // anyway so we can try to parse the function body.
13814     PushFunctionScope();
13815     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13816     return D;
13817   }
13818 
13819   FunctionDecl *FD = nullptr;
13820 
13821   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13822     FD = FunTmpl->getTemplatedDecl();
13823   else
13824     FD = cast<FunctionDecl>(D);
13825 
13826   // Do not push if it is a lambda because one is already pushed when building
13827   // the lambda in ActOnStartOfLambdaDefinition().
13828   if (!isLambdaCallOperator(FD))
13829     PushExpressionEvaluationContext(
13830         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13831                           : ExprEvalContexts.back().Context);
13832 
13833   // Check for defining attributes before the check for redefinition.
13834   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13835     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13836     FD->dropAttr<AliasAttr>();
13837     FD->setInvalidDecl();
13838   }
13839   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13840     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13841     FD->dropAttr<IFuncAttr>();
13842     FD->setInvalidDecl();
13843   }
13844 
13845   // See if this is a redefinition. If 'will have body' is already set, then
13846   // these checks were already performed when it was set.
13847   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13848     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13849 
13850     // If we're skipping the body, we're done. Don't enter the scope.
13851     if (SkipBody && SkipBody->ShouldSkip)
13852       return D;
13853   }
13854 
13855   // Mark this function as "will have a body eventually".  This lets users to
13856   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13857   // this function.
13858   FD->setWillHaveBody();
13859 
13860   // If we are instantiating a generic lambda call operator, push
13861   // a LambdaScopeInfo onto the function stack.  But use the information
13862   // that's already been calculated (ActOnLambdaExpr) to prime the current
13863   // LambdaScopeInfo.
13864   // When the template operator is being specialized, the LambdaScopeInfo,
13865   // has to be properly restored so that tryCaptureVariable doesn't try
13866   // and capture any new variables. In addition when calculating potential
13867   // captures during transformation of nested lambdas, it is necessary to
13868   // have the LSI properly restored.
13869   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13870     assert(inTemplateInstantiation() &&
13871            "There should be an active template instantiation on the stack "
13872            "when instantiating a generic lambda!");
13873     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13874   } else {
13875     // Enter a new function scope
13876     PushFunctionScope();
13877   }
13878 
13879   // Builtin functions cannot be defined.
13880   if (unsigned BuiltinID = FD->getBuiltinID()) {
13881     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13882         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13883       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13884       FD->setInvalidDecl();
13885     }
13886   }
13887 
13888   // The return type of a function definition must be complete
13889   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13890   QualType ResultType = FD->getReturnType();
13891   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13892       !FD->isInvalidDecl() &&
13893       RequireCompleteType(FD->getLocation(), ResultType,
13894                           diag::err_func_def_incomplete_result))
13895     FD->setInvalidDecl();
13896 
13897   if (FnBodyScope)
13898     PushDeclContext(FnBodyScope, FD);
13899 
13900   // Check the validity of our function parameters
13901   CheckParmsForFunctionDef(FD->parameters(),
13902                            /*CheckParameterNames=*/true);
13903 
13904   // Add non-parameter declarations already in the function to the current
13905   // scope.
13906   if (FnBodyScope) {
13907     for (Decl *NPD : FD->decls()) {
13908       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13909       if (!NonParmDecl)
13910         continue;
13911       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13912              "parameters should not be in newly created FD yet");
13913 
13914       // If the decl has a name, make it accessible in the current scope.
13915       if (NonParmDecl->getDeclName())
13916         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13917 
13918       // Similarly, dive into enums and fish their constants out, making them
13919       // accessible in this scope.
13920       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13921         for (auto *EI : ED->enumerators())
13922           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13923       }
13924     }
13925   }
13926 
13927   // Introduce our parameters into the function scope
13928   for (auto Param : FD->parameters()) {
13929     Param->setOwningFunction(FD);
13930 
13931     // If this has an identifier, add it to the scope stack.
13932     if (Param->getIdentifier() && FnBodyScope) {
13933       CheckShadow(FnBodyScope, Param);
13934 
13935       PushOnScopeChains(Param, FnBodyScope);
13936     }
13937   }
13938 
13939   // Ensure that the function's exception specification is instantiated.
13940   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13941     ResolveExceptionSpec(D->getLocation(), FPT);
13942 
13943   // dllimport cannot be applied to non-inline function definitions.
13944   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13945       !FD->isTemplateInstantiation()) {
13946     assert(!FD->hasAttr<DLLExportAttr>());
13947     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13948     FD->setInvalidDecl();
13949     return D;
13950   }
13951   // We want to attach documentation to original Decl (which might be
13952   // a function template).
13953   ActOnDocumentableDecl(D);
13954   if (getCurLexicalContext()->isObjCContainer() &&
13955       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13956       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13957     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13958 
13959   return D;
13960 }
13961 
13962 /// Given the set of return statements within a function body,
13963 /// compute the variables that are subject to the named return value
13964 /// optimization.
13965 ///
13966 /// Each of the variables that is subject to the named return value
13967 /// optimization will be marked as NRVO variables in the AST, and any
13968 /// return statement that has a marked NRVO variable as its NRVO candidate can
13969 /// use the named return value optimization.
13970 ///
13971 /// This function applies a very simplistic algorithm for NRVO: if every return
13972 /// statement in the scope of a variable has the same NRVO candidate, that
13973 /// candidate is an NRVO variable.
13974 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13975   ReturnStmt **Returns = Scope->Returns.data();
13976 
13977   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13978     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13979       if (!NRVOCandidate->isNRVOVariable())
13980         Returns[I]->setNRVOCandidate(nullptr);
13981     }
13982   }
13983 }
13984 
13985 bool Sema::canDelayFunctionBody(const Declarator &D) {
13986   // We can't delay parsing the body of a constexpr function template (yet).
13987   if (D.getDeclSpec().hasConstexprSpecifier())
13988     return false;
13989 
13990   // We can't delay parsing the body of a function template with a deduced
13991   // return type (yet).
13992   if (D.getDeclSpec().hasAutoTypeSpec()) {
13993     // If the placeholder introduces a non-deduced trailing return type,
13994     // we can still delay parsing it.
13995     if (D.getNumTypeObjects()) {
13996       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13997       if (Outer.Kind == DeclaratorChunk::Function &&
13998           Outer.Fun.hasTrailingReturnType()) {
13999         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14000         return Ty.isNull() || !Ty->isUndeducedType();
14001       }
14002     }
14003     return false;
14004   }
14005 
14006   return true;
14007 }
14008 
14009 bool Sema::canSkipFunctionBody(Decl *D) {
14010   // We cannot skip the body of a function (or function template) which is
14011   // constexpr, since we may need to evaluate its body in order to parse the
14012   // rest of the file.
14013   // We cannot skip the body of a function with an undeduced return type,
14014   // because any callers of that function need to know the type.
14015   if (const FunctionDecl *FD = D->getAsFunction()) {
14016     if (FD->isConstexpr())
14017       return false;
14018     // We can't simply call Type::isUndeducedType here, because inside template
14019     // auto can be deduced to a dependent type, which is not considered
14020     // "undeduced".
14021     if (FD->getReturnType()->getContainedDeducedType())
14022       return false;
14023   }
14024   return Consumer.shouldSkipFunctionBody(D);
14025 }
14026 
14027 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14028   if (!Decl)
14029     return nullptr;
14030   if (FunctionDecl *FD = Decl->getAsFunction())
14031     FD->setHasSkippedBody();
14032   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14033     MD->setHasSkippedBody();
14034   return Decl;
14035 }
14036 
14037 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14038   return ActOnFinishFunctionBody(D, BodyArg, false);
14039 }
14040 
14041 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14042 /// body.
14043 class ExitFunctionBodyRAII {
14044 public:
14045   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14046   ~ExitFunctionBodyRAII() {
14047     if (!IsLambda)
14048       S.PopExpressionEvaluationContext();
14049   }
14050 
14051 private:
14052   Sema &S;
14053   bool IsLambda = false;
14054 };
14055 
14056 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14057   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14058 
14059   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14060     if (EscapeInfo.count(BD))
14061       return EscapeInfo[BD];
14062 
14063     bool R = false;
14064     const BlockDecl *CurBD = BD;
14065 
14066     do {
14067       R = !CurBD->doesNotEscape();
14068       if (R)
14069         break;
14070       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14071     } while (CurBD);
14072 
14073     return EscapeInfo[BD] = R;
14074   };
14075 
14076   // If the location where 'self' is implicitly retained is inside a escaping
14077   // block, emit a diagnostic.
14078   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14079        S.ImplicitlyRetainedSelfLocs)
14080     if (IsOrNestedInEscapingBlock(P.second))
14081       S.Diag(P.first, diag::warn_implicitly_retains_self)
14082           << FixItHint::CreateInsertion(P.first, "self->");
14083 }
14084 
14085 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14086                                     bool IsInstantiation) {
14087   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14088 
14089   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14090   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14091 
14092   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14093     CheckCompletedCoroutineBody(FD, Body);
14094 
14095   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14096   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14097   // meant to pop the context added in ActOnStartOfFunctionDef().
14098   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14099 
14100   if (FD) {
14101     FD->setBody(Body);
14102     FD->setWillHaveBody(false);
14103 
14104     if (getLangOpts().CPlusPlus14) {
14105       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14106           FD->getReturnType()->isUndeducedType()) {
14107         // If the function has a deduced result type but contains no 'return'
14108         // statements, the result type as written must be exactly 'auto', and
14109         // the deduced result type is 'void'.
14110         if (!FD->getReturnType()->getAs<AutoType>()) {
14111           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14112               << FD->getReturnType();
14113           FD->setInvalidDecl();
14114         } else {
14115           // Substitute 'void' for the 'auto' in the type.
14116           TypeLoc ResultType = getReturnTypeLoc(FD);
14117           Context.adjustDeducedFunctionResultType(
14118               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14119         }
14120       }
14121     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14122       // In C++11, we don't use 'auto' deduction rules for lambda call
14123       // operators because we don't support return type deduction.
14124       auto *LSI = getCurLambda();
14125       if (LSI->HasImplicitReturnType) {
14126         deduceClosureReturnType(*LSI);
14127 
14128         // C++11 [expr.prim.lambda]p4:
14129         //   [...] if there are no return statements in the compound-statement
14130         //   [the deduced type is] the type void
14131         QualType RetType =
14132             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14133 
14134         // Update the return type to the deduced type.
14135         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14136         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14137                                             Proto->getExtProtoInfo()));
14138       }
14139     }
14140 
14141     // If the function implicitly returns zero (like 'main') or is naked,
14142     // don't complain about missing return statements.
14143     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14144       WP.disableCheckFallThrough();
14145 
14146     // MSVC permits the use of pure specifier (=0) on function definition,
14147     // defined at class scope, warn about this non-standard construct.
14148     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14149       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14150 
14151     if (!FD->isInvalidDecl()) {
14152       // Don't diagnose unused parameters of defaulted or deleted functions.
14153       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14154         DiagnoseUnusedParameters(FD->parameters());
14155       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14156                                              FD->getReturnType(), FD);
14157 
14158       // If this is a structor, we need a vtable.
14159       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14160         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14161       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14162         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14163 
14164       // Try to apply the named return value optimization. We have to check
14165       // if we can do this here because lambdas keep return statements around
14166       // to deduce an implicit return type.
14167       if (FD->getReturnType()->isRecordType() &&
14168           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14169         computeNRVO(Body, getCurFunction());
14170     }
14171 
14172     // GNU warning -Wmissing-prototypes:
14173     //   Warn if a global function is defined without a previous
14174     //   prototype declaration. This warning is issued even if the
14175     //   definition itself provides a prototype. The aim is to detect
14176     //   global functions that fail to be declared in header files.
14177     const FunctionDecl *PossiblePrototype = nullptr;
14178     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14179       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14180 
14181       if (PossiblePrototype) {
14182         // We found a declaration that is not a prototype,
14183         // but that could be a zero-parameter prototype
14184         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14185           TypeLoc TL = TI->getTypeLoc();
14186           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14187             Diag(PossiblePrototype->getLocation(),
14188                  diag::note_declaration_not_a_prototype)
14189                 << (FD->getNumParams() != 0)
14190                 << (FD->getNumParams() == 0
14191                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14192                         : FixItHint{});
14193         }
14194       } else {
14195         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14196             << /* function */ 1
14197             << (FD->getStorageClass() == SC_None
14198                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14199                                                  "static ")
14200                     : FixItHint{});
14201       }
14202 
14203       // GNU warning -Wstrict-prototypes
14204       //   Warn if K&R function is defined without a previous declaration.
14205       //   This warning is issued only if the definition itself does not provide
14206       //   a prototype. Only K&R definitions do not provide a prototype.
14207       if (!FD->hasWrittenPrototype()) {
14208         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14209         TypeLoc TL = TI->getTypeLoc();
14210         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14211         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14212       }
14213     }
14214 
14215     // Warn on CPUDispatch with an actual body.
14216     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14217       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14218         if (!CmpndBody->body_empty())
14219           Diag(CmpndBody->body_front()->getBeginLoc(),
14220                diag::warn_dispatch_body_ignored);
14221 
14222     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14223       const CXXMethodDecl *KeyFunction;
14224       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14225           MD->isVirtual() &&
14226           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14227           MD == KeyFunction->getCanonicalDecl()) {
14228         // Update the key-function state if necessary for this ABI.
14229         if (FD->isInlined() &&
14230             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14231           Context.setNonKeyFunction(MD);
14232 
14233           // If the newly-chosen key function is already defined, then we
14234           // need to mark the vtable as used retroactively.
14235           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14236           const FunctionDecl *Definition;
14237           if (KeyFunction && KeyFunction->isDefined(Definition))
14238             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14239         } else {
14240           // We just defined they key function; mark the vtable as used.
14241           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14242         }
14243       }
14244     }
14245 
14246     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14247            "Function parsing confused");
14248   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14249     assert(MD == getCurMethodDecl() && "Method parsing confused");
14250     MD->setBody(Body);
14251     if (!MD->isInvalidDecl()) {
14252       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14253                                              MD->getReturnType(), MD);
14254 
14255       if (Body)
14256         computeNRVO(Body, getCurFunction());
14257     }
14258     if (getCurFunction()->ObjCShouldCallSuper) {
14259       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14260           << MD->getSelector().getAsString();
14261       getCurFunction()->ObjCShouldCallSuper = false;
14262     }
14263     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14264       const ObjCMethodDecl *InitMethod = nullptr;
14265       bool isDesignated =
14266           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14267       assert(isDesignated && InitMethod);
14268       (void)isDesignated;
14269 
14270       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14271         auto IFace = MD->getClassInterface();
14272         if (!IFace)
14273           return false;
14274         auto SuperD = IFace->getSuperClass();
14275         if (!SuperD)
14276           return false;
14277         return SuperD->getIdentifier() ==
14278             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14279       };
14280       // Don't issue this warning for unavailable inits or direct subclasses
14281       // of NSObject.
14282       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14283         Diag(MD->getLocation(),
14284              diag::warn_objc_designated_init_missing_super_call);
14285         Diag(InitMethod->getLocation(),
14286              diag::note_objc_designated_init_marked_here);
14287       }
14288       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14289     }
14290     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14291       // Don't issue this warning for unavaialable inits.
14292       if (!MD->isUnavailable())
14293         Diag(MD->getLocation(),
14294              diag::warn_objc_secondary_init_missing_init_call);
14295       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14296     }
14297 
14298     diagnoseImplicitlyRetainedSelf(*this);
14299   } else {
14300     // Parsing the function declaration failed in some way. Pop the fake scope
14301     // we pushed on.
14302     PopFunctionScopeInfo(ActivePolicy, dcl);
14303     return nullptr;
14304   }
14305 
14306   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14307     DiagnoseUnguardedAvailabilityViolations(dcl);
14308 
14309   assert(!getCurFunction()->ObjCShouldCallSuper &&
14310          "This should only be set for ObjC methods, which should have been "
14311          "handled in the block above.");
14312 
14313   // Verify and clean out per-function state.
14314   if (Body && (!FD || !FD->isDefaulted())) {
14315     // C++ constructors that have function-try-blocks can't have return
14316     // statements in the handlers of that block. (C++ [except.handle]p14)
14317     // Verify this.
14318     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14319       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14320 
14321     // Verify that gotos and switch cases don't jump into scopes illegally.
14322     if (getCurFunction()->NeedsScopeChecking() &&
14323         !PP.isCodeCompletionEnabled())
14324       DiagnoseInvalidJumps(Body);
14325 
14326     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14327       if (!Destructor->getParent()->isDependentType())
14328         CheckDestructor(Destructor);
14329 
14330       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14331                                              Destructor->getParent());
14332     }
14333 
14334     // If any errors have occurred, clear out any temporaries that may have
14335     // been leftover. This ensures that these temporaries won't be picked up for
14336     // deletion in some later function.
14337     if (getDiagnostics().hasErrorOccurred() ||
14338         getDiagnostics().getSuppressAllDiagnostics()) {
14339       DiscardCleanupsInEvaluationContext();
14340     }
14341     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14342         !isa<FunctionTemplateDecl>(dcl)) {
14343       // Since the body is valid, issue any analysis-based warnings that are
14344       // enabled.
14345       ActivePolicy = &WP;
14346     }
14347 
14348     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14349         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14350       FD->setInvalidDecl();
14351 
14352     if (FD && FD->hasAttr<NakedAttr>()) {
14353       for (const Stmt *S : Body->children()) {
14354         // Allow local register variables without initializer as they don't
14355         // require prologue.
14356         bool RegisterVariables = false;
14357         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14358           for (const auto *Decl : DS->decls()) {
14359             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14360               RegisterVariables =
14361                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14362               if (!RegisterVariables)
14363                 break;
14364             }
14365           }
14366         }
14367         if (RegisterVariables)
14368           continue;
14369         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14370           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14371           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14372           FD->setInvalidDecl();
14373           break;
14374         }
14375       }
14376     }
14377 
14378     assert(ExprCleanupObjects.size() ==
14379                ExprEvalContexts.back().NumCleanupObjects &&
14380            "Leftover temporaries in function");
14381     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14382     assert(MaybeODRUseExprs.empty() &&
14383            "Leftover expressions for odr-use checking");
14384   }
14385 
14386   if (!IsInstantiation)
14387     PopDeclContext();
14388 
14389   PopFunctionScopeInfo(ActivePolicy, dcl);
14390   // If any errors have occurred, clear out any temporaries that may have
14391   // been leftover. This ensures that these temporaries won't be picked up for
14392   // deletion in some later function.
14393   if (getDiagnostics().hasErrorOccurred()) {
14394     DiscardCleanupsInEvaluationContext();
14395   }
14396 
14397   if (LangOpts.OpenMP || LangOpts.CUDA) {
14398     auto ES = getEmissionStatus(FD);
14399     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14400         ES == Sema::FunctionEmissionStatus::Unknown)
14401       DeclsToCheckForDeferredDiags.push_back(FD);
14402   }
14403 
14404   return dcl;
14405 }
14406 
14407 /// When we finish delayed parsing of an attribute, we must attach it to the
14408 /// relevant Decl.
14409 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14410                                        ParsedAttributes &Attrs) {
14411   // Always attach attributes to the underlying decl.
14412   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14413     D = TD->getTemplatedDecl();
14414   ProcessDeclAttributeList(S, D, Attrs);
14415 
14416   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14417     if (Method->isStatic())
14418       checkThisInStaticMemberFunctionAttributes(Method);
14419 }
14420 
14421 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14422 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14423 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14424                                           IdentifierInfo &II, Scope *S) {
14425   // Find the scope in which the identifier is injected and the corresponding
14426   // DeclContext.
14427   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14428   // In that case, we inject the declaration into the translation unit scope
14429   // instead.
14430   Scope *BlockScope = S;
14431   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14432     BlockScope = BlockScope->getParent();
14433 
14434   Scope *ContextScope = BlockScope;
14435   while (!ContextScope->getEntity())
14436     ContextScope = ContextScope->getParent();
14437   ContextRAII SavedContext(*this, ContextScope->getEntity());
14438 
14439   // Before we produce a declaration for an implicitly defined
14440   // function, see whether there was a locally-scoped declaration of
14441   // this name as a function or variable. If so, use that
14442   // (non-visible) declaration, and complain about it.
14443   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14444   if (ExternCPrev) {
14445     // We still need to inject the function into the enclosing block scope so
14446     // that later (non-call) uses can see it.
14447     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14448 
14449     // C89 footnote 38:
14450     //   If in fact it is not defined as having type "function returning int",
14451     //   the behavior is undefined.
14452     if (!isa<FunctionDecl>(ExternCPrev) ||
14453         !Context.typesAreCompatible(
14454             cast<FunctionDecl>(ExternCPrev)->getType(),
14455             Context.getFunctionNoProtoType(Context.IntTy))) {
14456       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14457           << ExternCPrev << !getLangOpts().C99;
14458       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14459       return ExternCPrev;
14460     }
14461   }
14462 
14463   // Extension in C99.  Legal in C90, but warn about it.
14464   unsigned diag_id;
14465   if (II.getName().startswith("__builtin_"))
14466     diag_id = diag::warn_builtin_unknown;
14467   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14468   else if (getLangOpts().OpenCL)
14469     diag_id = diag::err_opencl_implicit_function_decl;
14470   else if (getLangOpts().C99)
14471     diag_id = diag::ext_implicit_function_decl;
14472   else
14473     diag_id = diag::warn_implicit_function_decl;
14474   Diag(Loc, diag_id) << &II;
14475 
14476   // If we found a prior declaration of this function, don't bother building
14477   // another one. We've already pushed that one into scope, so there's nothing
14478   // more to do.
14479   if (ExternCPrev)
14480     return ExternCPrev;
14481 
14482   // Because typo correction is expensive, only do it if the implicit
14483   // function declaration is going to be treated as an error.
14484   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14485     TypoCorrection Corrected;
14486     DeclFilterCCC<FunctionDecl> CCC{};
14487     if (S && (Corrected =
14488                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14489                               S, nullptr, CCC, CTK_NonError)))
14490       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14491                    /*ErrorRecovery*/false);
14492   }
14493 
14494   // Set a Declarator for the implicit definition: int foo();
14495   const char *Dummy;
14496   AttributeFactory attrFactory;
14497   DeclSpec DS(attrFactory);
14498   unsigned DiagID;
14499   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14500                                   Context.getPrintingPolicy());
14501   (void)Error; // Silence warning.
14502   assert(!Error && "Error setting up implicit decl!");
14503   SourceLocation NoLoc;
14504   Declarator D(DS, DeclaratorContext::BlockContext);
14505   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14506                                              /*IsAmbiguous=*/false,
14507                                              /*LParenLoc=*/NoLoc,
14508                                              /*Params=*/nullptr,
14509                                              /*NumParams=*/0,
14510                                              /*EllipsisLoc=*/NoLoc,
14511                                              /*RParenLoc=*/NoLoc,
14512                                              /*RefQualifierIsLvalueRef=*/true,
14513                                              /*RefQualifierLoc=*/NoLoc,
14514                                              /*MutableLoc=*/NoLoc, EST_None,
14515                                              /*ESpecRange=*/SourceRange(),
14516                                              /*Exceptions=*/nullptr,
14517                                              /*ExceptionRanges=*/nullptr,
14518                                              /*NumExceptions=*/0,
14519                                              /*NoexceptExpr=*/nullptr,
14520                                              /*ExceptionSpecTokens=*/nullptr,
14521                                              /*DeclsInPrototype=*/None, Loc,
14522                                              Loc, D),
14523                 std::move(DS.getAttributes()), SourceLocation());
14524   D.SetIdentifier(&II, Loc);
14525 
14526   // Insert this function into the enclosing block scope.
14527   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14528   FD->setImplicit();
14529 
14530   AddKnownFunctionAttributes(FD);
14531 
14532   return FD;
14533 }
14534 
14535 /// If this function is a C++ replaceable global allocation function
14536 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14537 /// adds any function attributes that we know a priori based on the standard.
14538 ///
14539 /// We need to check for duplicate attributes both here and where user-written
14540 /// attributes are applied to declarations.
14541 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14542     FunctionDecl *FD) {
14543   if (FD->isInvalidDecl())
14544     return;
14545 
14546   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14547       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14548     return;
14549 
14550   Optional<unsigned> AlignmentParam;
14551   bool IsNothrow = false;
14552   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14553     return;
14554 
14555   // C++2a [basic.stc.dynamic.allocation]p4:
14556   //   An allocation function that has a non-throwing exception specification
14557   //   indicates failure by returning a null pointer value. Any other allocation
14558   //   function never returns a null pointer value and indicates failure only by
14559   //   throwing an exception [...]
14560   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14561     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14562 
14563   // C++2a [basic.stc.dynamic.allocation]p2:
14564   //   An allocation function attempts to allocate the requested amount of
14565   //   storage. [...] If the request succeeds, the value returned by a
14566   //   replaceable allocation function is a [...] pointer value p0 different
14567   //   from any previously returned value p1 [...]
14568   //
14569   // However, this particular information is being added in codegen,
14570   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14571 
14572   // C++2a [basic.stc.dynamic.allocation]p2:
14573   //   An allocation function attempts to allocate the requested amount of
14574   //   storage. If it is successful, it returns the address of the start of a
14575   //   block of storage whose length in bytes is at least as large as the
14576   //   requested size.
14577   if (!FD->hasAttr<AllocSizeAttr>()) {
14578     FD->addAttr(AllocSizeAttr::CreateImplicit(
14579         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14580         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14581   }
14582 
14583   // C++2a [basic.stc.dynamic.allocation]p3:
14584   //   For an allocation function [...], the pointer returned on a successful
14585   //   call shall represent the address of storage that is aligned as follows:
14586   //   (3.1) If the allocation function takes an argument of type
14587   //         std​::​align_­val_­t, the storage will have the alignment
14588   //         specified by the value of this argument.
14589   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14590     FD->addAttr(AllocAlignAttr::CreateImplicit(
14591         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14592   }
14593 
14594   // FIXME:
14595   // C++2a [basic.stc.dynamic.allocation]p3:
14596   //   For an allocation function [...], the pointer returned on a successful
14597   //   call shall represent the address of storage that is aligned as follows:
14598   //   (3.2) Otherwise, if the allocation function is named operator new[],
14599   //         the storage is aligned for any object that does not have
14600   //         new-extended alignment ([basic.align]) and is no larger than the
14601   //         requested size.
14602   //   (3.3) Otherwise, the storage is aligned for any object that does not
14603   //         have new-extended alignment and is of the requested size.
14604 }
14605 
14606 /// Adds any function attributes that we know a priori based on
14607 /// the declaration of this function.
14608 ///
14609 /// These attributes can apply both to implicitly-declared builtins
14610 /// (like __builtin___printf_chk) or to library-declared functions
14611 /// like NSLog or printf.
14612 ///
14613 /// We need to check for duplicate attributes both here and where user-written
14614 /// attributes are applied to declarations.
14615 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14616   if (FD->isInvalidDecl())
14617     return;
14618 
14619   // If this is a built-in function, map its builtin attributes to
14620   // actual attributes.
14621   if (unsigned BuiltinID = FD->getBuiltinID()) {
14622     // Handle printf-formatting attributes.
14623     unsigned FormatIdx;
14624     bool HasVAListArg;
14625     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14626       if (!FD->hasAttr<FormatAttr>()) {
14627         const char *fmt = "printf";
14628         unsigned int NumParams = FD->getNumParams();
14629         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14630             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14631           fmt = "NSString";
14632         FD->addAttr(FormatAttr::CreateImplicit(Context,
14633                                                &Context.Idents.get(fmt),
14634                                                FormatIdx+1,
14635                                                HasVAListArg ? 0 : FormatIdx+2,
14636                                                FD->getLocation()));
14637       }
14638     }
14639     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14640                                              HasVAListArg)) {
14641      if (!FD->hasAttr<FormatAttr>())
14642        FD->addAttr(FormatAttr::CreateImplicit(Context,
14643                                               &Context.Idents.get("scanf"),
14644                                               FormatIdx+1,
14645                                               HasVAListArg ? 0 : FormatIdx+2,
14646                                               FD->getLocation()));
14647     }
14648 
14649     // Handle automatically recognized callbacks.
14650     SmallVector<int, 4> Encoding;
14651     if (!FD->hasAttr<CallbackAttr>() &&
14652         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14653       FD->addAttr(CallbackAttr::CreateImplicit(
14654           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14655 
14656     // Mark const if we don't care about errno and that is the only thing
14657     // preventing the function from being const. This allows IRgen to use LLVM
14658     // intrinsics for such functions.
14659     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14660         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14661       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14662 
14663     // We make "fma" on some platforms const because we know it does not set
14664     // errno in those environments even though it could set errno based on the
14665     // C standard.
14666     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14667     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14668         !FD->hasAttr<ConstAttr>()) {
14669       switch (BuiltinID) {
14670       case Builtin::BI__builtin_fma:
14671       case Builtin::BI__builtin_fmaf:
14672       case Builtin::BI__builtin_fmal:
14673       case Builtin::BIfma:
14674       case Builtin::BIfmaf:
14675       case Builtin::BIfmal:
14676         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14677         break;
14678       default:
14679         break;
14680       }
14681     }
14682 
14683     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14684         !FD->hasAttr<ReturnsTwiceAttr>())
14685       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14686                                          FD->getLocation()));
14687     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14688       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14689     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14690       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14691     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14692       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14693     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14694         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14695       // Add the appropriate attribute, depending on the CUDA compilation mode
14696       // and which target the builtin belongs to. For example, during host
14697       // compilation, aux builtins are __device__, while the rest are __host__.
14698       if (getLangOpts().CUDAIsDevice !=
14699           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14700         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14701       else
14702         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14703     }
14704   }
14705 
14706   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14707 
14708   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14709   // throw, add an implicit nothrow attribute to any extern "C" function we come
14710   // across.
14711   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14712       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14713     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14714     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14715       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14716   }
14717 
14718   IdentifierInfo *Name = FD->getIdentifier();
14719   if (!Name)
14720     return;
14721   if ((!getLangOpts().CPlusPlus &&
14722        FD->getDeclContext()->isTranslationUnit()) ||
14723       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14724        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14725        LinkageSpecDecl::lang_c)) {
14726     // Okay: this could be a libc/libm/Objective-C function we know
14727     // about.
14728   } else
14729     return;
14730 
14731   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14732     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14733     // target-specific builtins, perhaps?
14734     if (!FD->hasAttr<FormatAttr>())
14735       FD->addAttr(FormatAttr::CreateImplicit(Context,
14736                                              &Context.Idents.get("printf"), 2,
14737                                              Name->isStr("vasprintf") ? 0 : 3,
14738                                              FD->getLocation()));
14739   }
14740 
14741   if (Name->isStr("__CFStringMakeConstantString")) {
14742     // We already have a __builtin___CFStringMakeConstantString,
14743     // but builds that use -fno-constant-cfstrings don't go through that.
14744     if (!FD->hasAttr<FormatArgAttr>())
14745       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14746                                                 FD->getLocation()));
14747   }
14748 }
14749 
14750 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14751                                     TypeSourceInfo *TInfo) {
14752   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14753   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14754 
14755   if (!TInfo) {
14756     assert(D.isInvalidType() && "no declarator info for valid type");
14757     TInfo = Context.getTrivialTypeSourceInfo(T);
14758   }
14759 
14760   // Scope manipulation handled by caller.
14761   TypedefDecl *NewTD =
14762       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14763                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14764 
14765   // Bail out immediately if we have an invalid declaration.
14766   if (D.isInvalidType()) {
14767     NewTD->setInvalidDecl();
14768     return NewTD;
14769   }
14770 
14771   if (D.getDeclSpec().isModulePrivateSpecified()) {
14772     if (CurContext->isFunctionOrMethod())
14773       Diag(NewTD->getLocation(), diag::err_module_private_local)
14774         << 2 << NewTD->getDeclName()
14775         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14776         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14777     else
14778       NewTD->setModulePrivate();
14779   }
14780 
14781   // C++ [dcl.typedef]p8:
14782   //   If the typedef declaration defines an unnamed class (or
14783   //   enum), the first typedef-name declared by the declaration
14784   //   to be that class type (or enum type) is used to denote the
14785   //   class type (or enum type) for linkage purposes only.
14786   // We need to check whether the type was declared in the declaration.
14787   switch (D.getDeclSpec().getTypeSpecType()) {
14788   case TST_enum:
14789   case TST_struct:
14790   case TST_interface:
14791   case TST_union:
14792   case TST_class: {
14793     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14794     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14795     break;
14796   }
14797 
14798   default:
14799     break;
14800   }
14801 
14802   return NewTD;
14803 }
14804 
14805 /// Check that this is a valid underlying type for an enum declaration.
14806 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14807   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14808   QualType T = TI->getType();
14809 
14810   if (T->isDependentType())
14811     return false;
14812 
14813   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14814     if (BT->isInteger())
14815       return false;
14816 
14817   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14818   return true;
14819 }
14820 
14821 /// Check whether this is a valid redeclaration of a previous enumeration.
14822 /// \return true if the redeclaration was invalid.
14823 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14824                                   QualType EnumUnderlyingTy, bool IsFixed,
14825                                   const EnumDecl *Prev) {
14826   if (IsScoped != Prev->isScoped()) {
14827     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14828       << Prev->isScoped();
14829     Diag(Prev->getLocation(), diag::note_previous_declaration);
14830     return true;
14831   }
14832 
14833   if (IsFixed && Prev->isFixed()) {
14834     if (!EnumUnderlyingTy->isDependentType() &&
14835         !Prev->getIntegerType()->isDependentType() &&
14836         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14837                                         Prev->getIntegerType())) {
14838       // TODO: Highlight the underlying type of the redeclaration.
14839       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14840         << EnumUnderlyingTy << Prev->getIntegerType();
14841       Diag(Prev->getLocation(), diag::note_previous_declaration)
14842           << Prev->getIntegerTypeRange();
14843       return true;
14844     }
14845   } else if (IsFixed != Prev->isFixed()) {
14846     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14847       << Prev->isFixed();
14848     Diag(Prev->getLocation(), diag::note_previous_declaration);
14849     return true;
14850   }
14851 
14852   return false;
14853 }
14854 
14855 /// Get diagnostic %select index for tag kind for
14856 /// redeclaration diagnostic message.
14857 /// WARNING: Indexes apply to particular diagnostics only!
14858 ///
14859 /// \returns diagnostic %select index.
14860 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14861   switch (Tag) {
14862   case TTK_Struct: return 0;
14863   case TTK_Interface: return 1;
14864   case TTK_Class:  return 2;
14865   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14866   }
14867 }
14868 
14869 /// Determine if tag kind is a class-key compatible with
14870 /// class for redeclaration (class, struct, or __interface).
14871 ///
14872 /// \returns true iff the tag kind is compatible.
14873 static bool isClassCompatTagKind(TagTypeKind Tag)
14874 {
14875   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14876 }
14877 
14878 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14879                                              TagTypeKind TTK) {
14880   if (isa<TypedefDecl>(PrevDecl))
14881     return NTK_Typedef;
14882   else if (isa<TypeAliasDecl>(PrevDecl))
14883     return NTK_TypeAlias;
14884   else if (isa<ClassTemplateDecl>(PrevDecl))
14885     return NTK_Template;
14886   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14887     return NTK_TypeAliasTemplate;
14888   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14889     return NTK_TemplateTemplateArgument;
14890   switch (TTK) {
14891   case TTK_Struct:
14892   case TTK_Interface:
14893   case TTK_Class:
14894     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14895   case TTK_Union:
14896     return NTK_NonUnion;
14897   case TTK_Enum:
14898     return NTK_NonEnum;
14899   }
14900   llvm_unreachable("invalid TTK");
14901 }
14902 
14903 /// Determine whether a tag with a given kind is acceptable
14904 /// as a redeclaration of the given tag declaration.
14905 ///
14906 /// \returns true if the new tag kind is acceptable, false otherwise.
14907 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14908                                         TagTypeKind NewTag, bool isDefinition,
14909                                         SourceLocation NewTagLoc,
14910                                         const IdentifierInfo *Name) {
14911   // C++ [dcl.type.elab]p3:
14912   //   The class-key or enum keyword present in the
14913   //   elaborated-type-specifier shall agree in kind with the
14914   //   declaration to which the name in the elaborated-type-specifier
14915   //   refers. This rule also applies to the form of
14916   //   elaborated-type-specifier that declares a class-name or
14917   //   friend class since it can be construed as referring to the
14918   //   definition of the class. Thus, in any
14919   //   elaborated-type-specifier, the enum keyword shall be used to
14920   //   refer to an enumeration (7.2), the union class-key shall be
14921   //   used to refer to a union (clause 9), and either the class or
14922   //   struct class-key shall be used to refer to a class (clause 9)
14923   //   declared using the class or struct class-key.
14924   TagTypeKind OldTag = Previous->getTagKind();
14925   if (OldTag != NewTag &&
14926       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14927     return false;
14928 
14929   // Tags are compatible, but we might still want to warn on mismatched tags.
14930   // Non-class tags can't be mismatched at this point.
14931   if (!isClassCompatTagKind(NewTag))
14932     return true;
14933 
14934   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14935   // by our warning analysis. We don't want to warn about mismatches with (eg)
14936   // declarations in system headers that are designed to be specialized, but if
14937   // a user asks us to warn, we should warn if their code contains mismatched
14938   // declarations.
14939   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14940     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14941                                       Loc);
14942   };
14943   if (IsIgnoredLoc(NewTagLoc))
14944     return true;
14945 
14946   auto IsIgnored = [&](const TagDecl *Tag) {
14947     return IsIgnoredLoc(Tag->getLocation());
14948   };
14949   while (IsIgnored(Previous)) {
14950     Previous = Previous->getPreviousDecl();
14951     if (!Previous)
14952       return true;
14953     OldTag = Previous->getTagKind();
14954   }
14955 
14956   bool isTemplate = false;
14957   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14958     isTemplate = Record->getDescribedClassTemplate();
14959 
14960   if (inTemplateInstantiation()) {
14961     if (OldTag != NewTag) {
14962       // In a template instantiation, do not offer fix-its for tag mismatches
14963       // since they usually mess up the template instead of fixing the problem.
14964       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14965         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14966         << getRedeclDiagFromTagKind(OldTag);
14967       // FIXME: Note previous location?
14968     }
14969     return true;
14970   }
14971 
14972   if (isDefinition) {
14973     // On definitions, check all previous tags and issue a fix-it for each
14974     // one that doesn't match the current tag.
14975     if (Previous->getDefinition()) {
14976       // Don't suggest fix-its for redefinitions.
14977       return true;
14978     }
14979 
14980     bool previousMismatch = false;
14981     for (const TagDecl *I : Previous->redecls()) {
14982       if (I->getTagKind() != NewTag) {
14983         // Ignore previous declarations for which the warning was disabled.
14984         if (IsIgnored(I))
14985           continue;
14986 
14987         if (!previousMismatch) {
14988           previousMismatch = true;
14989           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14990             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14991             << getRedeclDiagFromTagKind(I->getTagKind());
14992         }
14993         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14994           << getRedeclDiagFromTagKind(NewTag)
14995           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14996                TypeWithKeyword::getTagTypeKindName(NewTag));
14997       }
14998     }
14999     return true;
15000   }
15001 
15002   // Identify the prevailing tag kind: this is the kind of the definition (if
15003   // there is a non-ignored definition), or otherwise the kind of the prior
15004   // (non-ignored) declaration.
15005   const TagDecl *PrevDef = Previous->getDefinition();
15006   if (PrevDef && IsIgnored(PrevDef))
15007     PrevDef = nullptr;
15008   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15009   if (Redecl->getTagKind() != NewTag) {
15010     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15011       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15012       << getRedeclDiagFromTagKind(OldTag);
15013     Diag(Redecl->getLocation(), diag::note_previous_use);
15014 
15015     // If there is a previous definition, suggest a fix-it.
15016     if (PrevDef) {
15017       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15018         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15019         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15020              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15021     }
15022   }
15023 
15024   return true;
15025 }
15026 
15027 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15028 /// from an outer enclosing namespace or file scope inside a friend declaration.
15029 /// This should provide the commented out code in the following snippet:
15030 ///   namespace N {
15031 ///     struct X;
15032 ///     namespace M {
15033 ///       struct Y { friend struct /*N::*/ X; };
15034 ///     }
15035 ///   }
15036 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15037                                          SourceLocation NameLoc) {
15038   // While the decl is in a namespace, do repeated lookup of that name and see
15039   // if we get the same namespace back.  If we do not, continue until
15040   // translation unit scope, at which point we have a fully qualified NNS.
15041   SmallVector<IdentifierInfo *, 4> Namespaces;
15042   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15043   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15044     // This tag should be declared in a namespace, which can only be enclosed by
15045     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15046     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15047     if (!Namespace || Namespace->isAnonymousNamespace())
15048       return FixItHint();
15049     IdentifierInfo *II = Namespace->getIdentifier();
15050     Namespaces.push_back(II);
15051     NamedDecl *Lookup = SemaRef.LookupSingleName(
15052         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15053     if (Lookup == Namespace)
15054       break;
15055   }
15056 
15057   // Once we have all the namespaces, reverse them to go outermost first, and
15058   // build an NNS.
15059   SmallString<64> Insertion;
15060   llvm::raw_svector_ostream OS(Insertion);
15061   if (DC->isTranslationUnit())
15062     OS << "::";
15063   std::reverse(Namespaces.begin(), Namespaces.end());
15064   for (auto *II : Namespaces)
15065     OS << II->getName() << "::";
15066   return FixItHint::CreateInsertion(NameLoc, Insertion);
15067 }
15068 
15069 /// Determine whether a tag originally declared in context \p OldDC can
15070 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15071 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15072 /// using-declaration).
15073 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15074                                          DeclContext *NewDC) {
15075   OldDC = OldDC->getRedeclContext();
15076   NewDC = NewDC->getRedeclContext();
15077 
15078   if (OldDC->Equals(NewDC))
15079     return true;
15080 
15081   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15082   // encloses the other).
15083   if (S.getLangOpts().MSVCCompat &&
15084       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15085     return true;
15086 
15087   return false;
15088 }
15089 
15090 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15091 /// former case, Name will be non-null.  In the later case, Name will be null.
15092 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15093 /// reference/declaration/definition of a tag.
15094 ///
15095 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15096 /// trailing-type-specifier) other than one in an alias-declaration.
15097 ///
15098 /// \param SkipBody If non-null, will be set to indicate if the caller should
15099 /// skip the definition of this tag and treat it as if it were a declaration.
15100 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15101                      SourceLocation KWLoc, CXXScopeSpec &SS,
15102                      IdentifierInfo *Name, SourceLocation NameLoc,
15103                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15104                      SourceLocation ModulePrivateLoc,
15105                      MultiTemplateParamsArg TemplateParameterLists,
15106                      bool &OwnedDecl, bool &IsDependent,
15107                      SourceLocation ScopedEnumKWLoc,
15108                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15109                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15110                      SkipBodyInfo *SkipBody) {
15111   // If this is not a definition, it must have a name.
15112   IdentifierInfo *OrigName = Name;
15113   assert((Name != nullptr || TUK == TUK_Definition) &&
15114          "Nameless record must be a definition!");
15115   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15116 
15117   OwnedDecl = false;
15118   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15119   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15120 
15121   // FIXME: Check member specializations more carefully.
15122   bool isMemberSpecialization = false;
15123   bool Invalid = false;
15124 
15125   // We only need to do this matching if we have template parameters
15126   // or a scope specifier, which also conveniently avoids this work
15127   // for non-C++ cases.
15128   if (TemplateParameterLists.size() > 0 ||
15129       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15130     if (TemplateParameterList *TemplateParams =
15131             MatchTemplateParametersToScopeSpecifier(
15132                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15133                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15134       if (Kind == TTK_Enum) {
15135         Diag(KWLoc, diag::err_enum_template);
15136         return nullptr;
15137       }
15138 
15139       if (TemplateParams->size() > 0) {
15140         // This is a declaration or definition of a class template (which may
15141         // be a member of another template).
15142 
15143         if (Invalid)
15144           return nullptr;
15145 
15146         OwnedDecl = false;
15147         DeclResult Result = CheckClassTemplate(
15148             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15149             AS, ModulePrivateLoc,
15150             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15151             TemplateParameterLists.data(), SkipBody);
15152         return Result.get();
15153       } else {
15154         // The "template<>" header is extraneous.
15155         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15156           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15157         isMemberSpecialization = true;
15158       }
15159     }
15160   }
15161 
15162   // Figure out the underlying type if this a enum declaration. We need to do
15163   // this early, because it's needed to detect if this is an incompatible
15164   // redeclaration.
15165   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15166   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15167 
15168   if (Kind == TTK_Enum) {
15169     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15170       // No underlying type explicitly specified, or we failed to parse the
15171       // type, default to int.
15172       EnumUnderlying = Context.IntTy.getTypePtr();
15173     } else if (UnderlyingType.get()) {
15174       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15175       // integral type; any cv-qualification is ignored.
15176       TypeSourceInfo *TI = nullptr;
15177       GetTypeFromParser(UnderlyingType.get(), &TI);
15178       EnumUnderlying = TI;
15179 
15180       if (CheckEnumUnderlyingType(TI))
15181         // Recover by falling back to int.
15182         EnumUnderlying = Context.IntTy.getTypePtr();
15183 
15184       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15185                                           UPPC_FixedUnderlyingType))
15186         EnumUnderlying = Context.IntTy.getTypePtr();
15187 
15188     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15189       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15190       // of 'int'. However, if this is an unfixed forward declaration, don't set
15191       // the underlying type unless the user enables -fms-compatibility. This
15192       // makes unfixed forward declared enums incomplete and is more conforming.
15193       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15194         EnumUnderlying = Context.IntTy.getTypePtr();
15195     }
15196   }
15197 
15198   DeclContext *SearchDC = CurContext;
15199   DeclContext *DC = CurContext;
15200   bool isStdBadAlloc = false;
15201   bool isStdAlignValT = false;
15202 
15203   RedeclarationKind Redecl = forRedeclarationInCurContext();
15204   if (TUK == TUK_Friend || TUK == TUK_Reference)
15205     Redecl = NotForRedeclaration;
15206 
15207   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15208   /// implemented asks for structural equivalence checking, the returned decl
15209   /// here is passed back to the parser, allowing the tag body to be parsed.
15210   auto createTagFromNewDecl = [&]() -> TagDecl * {
15211     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15212     // If there is an identifier, use the location of the identifier as the
15213     // location of the decl, otherwise use the location of the struct/union
15214     // keyword.
15215     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15216     TagDecl *New = nullptr;
15217 
15218     if (Kind == TTK_Enum) {
15219       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15220                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15221       // If this is an undefined enum, bail.
15222       if (TUK != TUK_Definition && !Invalid)
15223         return nullptr;
15224       if (EnumUnderlying) {
15225         EnumDecl *ED = cast<EnumDecl>(New);
15226         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15227           ED->setIntegerTypeSourceInfo(TI);
15228         else
15229           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15230         ED->setPromotionType(ED->getIntegerType());
15231       }
15232     } else { // struct/union
15233       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15234                                nullptr);
15235     }
15236 
15237     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15238       // Add alignment attributes if necessary; these attributes are checked
15239       // when the ASTContext lays out the structure.
15240       //
15241       // It is important for implementing the correct semantics that this
15242       // happen here (in ActOnTag). The #pragma pack stack is
15243       // maintained as a result of parser callbacks which can occur at
15244       // many points during the parsing of a struct declaration (because
15245       // the #pragma tokens are effectively skipped over during the
15246       // parsing of the struct).
15247       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15248         AddAlignmentAttributesForRecord(RD);
15249         AddMsStructLayoutForRecord(RD);
15250       }
15251     }
15252     New->setLexicalDeclContext(CurContext);
15253     return New;
15254   };
15255 
15256   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15257   if (Name && SS.isNotEmpty()) {
15258     // We have a nested-name tag ('struct foo::bar').
15259 
15260     // Check for invalid 'foo::'.
15261     if (SS.isInvalid()) {
15262       Name = nullptr;
15263       goto CreateNewDecl;
15264     }
15265 
15266     // If this is a friend or a reference to a class in a dependent
15267     // context, don't try to make a decl for it.
15268     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15269       DC = computeDeclContext(SS, false);
15270       if (!DC) {
15271         IsDependent = true;
15272         return nullptr;
15273       }
15274     } else {
15275       DC = computeDeclContext(SS, true);
15276       if (!DC) {
15277         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15278           << SS.getRange();
15279         return nullptr;
15280       }
15281     }
15282 
15283     if (RequireCompleteDeclContext(SS, DC))
15284       return nullptr;
15285 
15286     SearchDC = DC;
15287     // Look-up name inside 'foo::'.
15288     LookupQualifiedName(Previous, DC);
15289 
15290     if (Previous.isAmbiguous())
15291       return nullptr;
15292 
15293     if (Previous.empty()) {
15294       // Name lookup did not find anything. However, if the
15295       // nested-name-specifier refers to the current instantiation,
15296       // and that current instantiation has any dependent base
15297       // classes, we might find something at instantiation time: treat
15298       // this as a dependent elaborated-type-specifier.
15299       // But this only makes any sense for reference-like lookups.
15300       if (Previous.wasNotFoundInCurrentInstantiation() &&
15301           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15302         IsDependent = true;
15303         return nullptr;
15304       }
15305 
15306       // A tag 'foo::bar' must already exist.
15307       Diag(NameLoc, diag::err_not_tag_in_scope)
15308         << Kind << Name << DC << SS.getRange();
15309       Name = nullptr;
15310       Invalid = true;
15311       goto CreateNewDecl;
15312     }
15313   } else if (Name) {
15314     // C++14 [class.mem]p14:
15315     //   If T is the name of a class, then each of the following shall have a
15316     //   name different from T:
15317     //    -- every member of class T that is itself a type
15318     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15319         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15320       return nullptr;
15321 
15322     // If this is a named struct, check to see if there was a previous forward
15323     // declaration or definition.
15324     // FIXME: We're looking into outer scopes here, even when we
15325     // shouldn't be. Doing so can result in ambiguities that we
15326     // shouldn't be diagnosing.
15327     LookupName(Previous, S);
15328 
15329     // When declaring or defining a tag, ignore ambiguities introduced
15330     // by types using'ed into this scope.
15331     if (Previous.isAmbiguous() &&
15332         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15333       LookupResult::Filter F = Previous.makeFilter();
15334       while (F.hasNext()) {
15335         NamedDecl *ND = F.next();
15336         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15337                 SearchDC->getRedeclContext()))
15338           F.erase();
15339       }
15340       F.done();
15341     }
15342 
15343     // C++11 [namespace.memdef]p3:
15344     //   If the name in a friend declaration is neither qualified nor
15345     //   a template-id and the declaration is a function or an
15346     //   elaborated-type-specifier, the lookup to determine whether
15347     //   the entity has been previously declared shall not consider
15348     //   any scopes outside the innermost enclosing namespace.
15349     //
15350     // MSVC doesn't implement the above rule for types, so a friend tag
15351     // declaration may be a redeclaration of a type declared in an enclosing
15352     // scope.  They do implement this rule for friend functions.
15353     //
15354     // Does it matter that this should be by scope instead of by
15355     // semantic context?
15356     if (!Previous.empty() && TUK == TUK_Friend) {
15357       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15358       LookupResult::Filter F = Previous.makeFilter();
15359       bool FriendSawTagOutsideEnclosingNamespace = false;
15360       while (F.hasNext()) {
15361         NamedDecl *ND = F.next();
15362         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15363         if (DC->isFileContext() &&
15364             !EnclosingNS->Encloses(ND->getDeclContext())) {
15365           if (getLangOpts().MSVCCompat)
15366             FriendSawTagOutsideEnclosingNamespace = true;
15367           else
15368             F.erase();
15369         }
15370       }
15371       F.done();
15372 
15373       // Diagnose this MSVC extension in the easy case where lookup would have
15374       // unambiguously found something outside the enclosing namespace.
15375       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15376         NamedDecl *ND = Previous.getFoundDecl();
15377         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15378             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15379       }
15380     }
15381 
15382     // Note:  there used to be some attempt at recovery here.
15383     if (Previous.isAmbiguous())
15384       return nullptr;
15385 
15386     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15387       // FIXME: This makes sure that we ignore the contexts associated
15388       // with C structs, unions, and enums when looking for a matching
15389       // tag declaration or definition. See the similar lookup tweak
15390       // in Sema::LookupName; is there a better way to deal with this?
15391       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15392         SearchDC = SearchDC->getParent();
15393     }
15394   }
15395 
15396   if (Previous.isSingleResult() &&
15397       Previous.getFoundDecl()->isTemplateParameter()) {
15398     // Maybe we will complain about the shadowed template parameter.
15399     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15400     // Just pretend that we didn't see the previous declaration.
15401     Previous.clear();
15402   }
15403 
15404   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15405       DC->Equals(getStdNamespace())) {
15406     if (Name->isStr("bad_alloc")) {
15407       // This is a declaration of or a reference to "std::bad_alloc".
15408       isStdBadAlloc = true;
15409 
15410       // If std::bad_alloc has been implicitly declared (but made invisible to
15411       // name lookup), fill in this implicit declaration as the previous
15412       // declaration, so that the declarations get chained appropriately.
15413       if (Previous.empty() && StdBadAlloc)
15414         Previous.addDecl(getStdBadAlloc());
15415     } else if (Name->isStr("align_val_t")) {
15416       isStdAlignValT = true;
15417       if (Previous.empty() && StdAlignValT)
15418         Previous.addDecl(getStdAlignValT());
15419     }
15420   }
15421 
15422   // If we didn't find a previous declaration, and this is a reference
15423   // (or friend reference), move to the correct scope.  In C++, we
15424   // also need to do a redeclaration lookup there, just in case
15425   // there's a shadow friend decl.
15426   if (Name && Previous.empty() &&
15427       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15428     if (Invalid) goto CreateNewDecl;
15429     assert(SS.isEmpty());
15430 
15431     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15432       // C++ [basic.scope.pdecl]p5:
15433       //   -- for an elaborated-type-specifier of the form
15434       //
15435       //          class-key identifier
15436       //
15437       //      if the elaborated-type-specifier is used in the
15438       //      decl-specifier-seq or parameter-declaration-clause of a
15439       //      function defined in namespace scope, the identifier is
15440       //      declared as a class-name in the namespace that contains
15441       //      the declaration; otherwise, except as a friend
15442       //      declaration, the identifier is declared in the smallest
15443       //      non-class, non-function-prototype scope that contains the
15444       //      declaration.
15445       //
15446       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15447       // C structs and unions.
15448       //
15449       // It is an error in C++ to declare (rather than define) an enum
15450       // type, including via an elaborated type specifier.  We'll
15451       // diagnose that later; for now, declare the enum in the same
15452       // scope as we would have picked for any other tag type.
15453       //
15454       // GNU C also supports this behavior as part of its incomplete
15455       // enum types extension, while GNU C++ does not.
15456       //
15457       // Find the context where we'll be declaring the tag.
15458       // FIXME: We would like to maintain the current DeclContext as the
15459       // lexical context,
15460       SearchDC = getTagInjectionContext(SearchDC);
15461 
15462       // Find the scope where we'll be declaring the tag.
15463       S = getTagInjectionScope(S, getLangOpts());
15464     } else {
15465       assert(TUK == TUK_Friend);
15466       // C++ [namespace.memdef]p3:
15467       //   If a friend declaration in a non-local class first declares a
15468       //   class or function, the friend class or function is a member of
15469       //   the innermost enclosing namespace.
15470       SearchDC = SearchDC->getEnclosingNamespaceContext();
15471     }
15472 
15473     // In C++, we need to do a redeclaration lookup to properly
15474     // diagnose some problems.
15475     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15476     // hidden declaration so that we don't get ambiguity errors when using a
15477     // type declared by an elaborated-type-specifier.  In C that is not correct
15478     // and we should instead merge compatible types found by lookup.
15479     if (getLangOpts().CPlusPlus) {
15480       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15481       LookupQualifiedName(Previous, SearchDC);
15482     } else {
15483       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15484       LookupName(Previous, S);
15485     }
15486   }
15487 
15488   // If we have a known previous declaration to use, then use it.
15489   if (Previous.empty() && SkipBody && SkipBody->Previous)
15490     Previous.addDecl(SkipBody->Previous);
15491 
15492   if (!Previous.empty()) {
15493     NamedDecl *PrevDecl = Previous.getFoundDecl();
15494     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15495 
15496     // It's okay to have a tag decl in the same scope as a typedef
15497     // which hides a tag decl in the same scope.  Finding this
15498     // insanity with a redeclaration lookup can only actually happen
15499     // in C++.
15500     //
15501     // This is also okay for elaborated-type-specifiers, which is
15502     // technically forbidden by the current standard but which is
15503     // okay according to the likely resolution of an open issue;
15504     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15505     if (getLangOpts().CPlusPlus) {
15506       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15507         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15508           TagDecl *Tag = TT->getDecl();
15509           if (Tag->getDeclName() == Name &&
15510               Tag->getDeclContext()->getRedeclContext()
15511                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15512             PrevDecl = Tag;
15513             Previous.clear();
15514             Previous.addDecl(Tag);
15515             Previous.resolveKind();
15516           }
15517         }
15518       }
15519     }
15520 
15521     // If this is a redeclaration of a using shadow declaration, it must
15522     // declare a tag in the same context. In MSVC mode, we allow a
15523     // redefinition if either context is within the other.
15524     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15525       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15526       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15527           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15528           !(OldTag && isAcceptableTagRedeclContext(
15529                           *this, OldTag->getDeclContext(), SearchDC))) {
15530         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15531         Diag(Shadow->getTargetDecl()->getLocation(),
15532              diag::note_using_decl_target);
15533         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15534             << 0;
15535         // Recover by ignoring the old declaration.
15536         Previous.clear();
15537         goto CreateNewDecl;
15538       }
15539     }
15540 
15541     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15542       // If this is a use of a previous tag, or if the tag is already declared
15543       // in the same scope (so that the definition/declaration completes or
15544       // rementions the tag), reuse the decl.
15545       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15546           isDeclInScope(DirectPrevDecl, SearchDC, S,
15547                         SS.isNotEmpty() || isMemberSpecialization)) {
15548         // Make sure that this wasn't declared as an enum and now used as a
15549         // struct or something similar.
15550         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15551                                           TUK == TUK_Definition, KWLoc,
15552                                           Name)) {
15553           bool SafeToContinue
15554             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15555                Kind != TTK_Enum);
15556           if (SafeToContinue)
15557             Diag(KWLoc, diag::err_use_with_wrong_tag)
15558               << Name
15559               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15560                                               PrevTagDecl->getKindName());
15561           else
15562             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15563           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15564 
15565           if (SafeToContinue)
15566             Kind = PrevTagDecl->getTagKind();
15567           else {
15568             // Recover by making this an anonymous redefinition.
15569             Name = nullptr;
15570             Previous.clear();
15571             Invalid = true;
15572           }
15573         }
15574 
15575         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15576           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15577 
15578           // If this is an elaborated-type-specifier for a scoped enumeration,
15579           // the 'class' keyword is not necessary and not permitted.
15580           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15581             if (ScopedEnum)
15582               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15583                 << PrevEnum->isScoped()
15584                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15585             return PrevTagDecl;
15586           }
15587 
15588           QualType EnumUnderlyingTy;
15589           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15590             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15591           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15592             EnumUnderlyingTy = QualType(T, 0);
15593 
15594           // All conflicts with previous declarations are recovered by
15595           // returning the previous declaration, unless this is a definition,
15596           // in which case we want the caller to bail out.
15597           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15598                                      ScopedEnum, EnumUnderlyingTy,
15599                                      IsFixed, PrevEnum))
15600             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15601         }
15602 
15603         // C++11 [class.mem]p1:
15604         //   A member shall not be declared twice in the member-specification,
15605         //   except that a nested class or member class template can be declared
15606         //   and then later defined.
15607         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15608             S->isDeclScope(PrevDecl)) {
15609           Diag(NameLoc, diag::ext_member_redeclared);
15610           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15611         }
15612 
15613         if (!Invalid) {
15614           // If this is a use, just return the declaration we found, unless
15615           // we have attributes.
15616           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15617             if (!Attrs.empty()) {
15618               // FIXME: Diagnose these attributes. For now, we create a new
15619               // declaration to hold them.
15620             } else if (TUK == TUK_Reference &&
15621                        (PrevTagDecl->getFriendObjectKind() ==
15622                             Decl::FOK_Undeclared ||
15623                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15624                        SS.isEmpty()) {
15625               // This declaration is a reference to an existing entity, but
15626               // has different visibility from that entity: it either makes
15627               // a friend visible or it makes a type visible in a new module.
15628               // In either case, create a new declaration. We only do this if
15629               // the declaration would have meant the same thing if no prior
15630               // declaration were found, that is, if it was found in the same
15631               // scope where we would have injected a declaration.
15632               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15633                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15634                 return PrevTagDecl;
15635               // This is in the injected scope, create a new declaration in
15636               // that scope.
15637               S = getTagInjectionScope(S, getLangOpts());
15638             } else {
15639               return PrevTagDecl;
15640             }
15641           }
15642 
15643           // Diagnose attempts to redefine a tag.
15644           if (TUK == TUK_Definition) {
15645             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15646               // If we're defining a specialization and the previous definition
15647               // is from an implicit instantiation, don't emit an error
15648               // here; we'll catch this in the general case below.
15649               bool IsExplicitSpecializationAfterInstantiation = false;
15650               if (isMemberSpecialization) {
15651                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15652                   IsExplicitSpecializationAfterInstantiation =
15653                     RD->getTemplateSpecializationKind() !=
15654                     TSK_ExplicitSpecialization;
15655                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15656                   IsExplicitSpecializationAfterInstantiation =
15657                     ED->getTemplateSpecializationKind() !=
15658                     TSK_ExplicitSpecialization;
15659               }
15660 
15661               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15662               // not keep more that one definition around (merge them). However,
15663               // ensure the decl passes the structural compatibility check in
15664               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15665               NamedDecl *Hidden = nullptr;
15666               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15667                 // There is a definition of this tag, but it is not visible. We
15668                 // explicitly make use of C++'s one definition rule here, and
15669                 // assume that this definition is identical to the hidden one
15670                 // we already have. Make the existing definition visible and
15671                 // use it in place of this one.
15672                 if (!getLangOpts().CPlusPlus) {
15673                   // Postpone making the old definition visible until after we
15674                   // complete parsing the new one and do the structural
15675                   // comparison.
15676                   SkipBody->CheckSameAsPrevious = true;
15677                   SkipBody->New = createTagFromNewDecl();
15678                   SkipBody->Previous = Def;
15679                   return Def;
15680                 } else {
15681                   SkipBody->ShouldSkip = true;
15682                   SkipBody->Previous = Def;
15683                   makeMergedDefinitionVisible(Hidden);
15684                   // Carry on and handle it like a normal definition. We'll
15685                   // skip starting the definitiion later.
15686                 }
15687               } else if (!IsExplicitSpecializationAfterInstantiation) {
15688                 // A redeclaration in function prototype scope in C isn't
15689                 // visible elsewhere, so merely issue a warning.
15690                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15691                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15692                 else
15693                   Diag(NameLoc, diag::err_redefinition) << Name;
15694                 notePreviousDefinition(Def,
15695                                        NameLoc.isValid() ? NameLoc : KWLoc);
15696                 // If this is a redefinition, recover by making this
15697                 // struct be anonymous, which will make any later
15698                 // references get the previous definition.
15699                 Name = nullptr;
15700                 Previous.clear();
15701                 Invalid = true;
15702               }
15703             } else {
15704               // If the type is currently being defined, complain
15705               // about a nested redefinition.
15706               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15707               if (TD->isBeingDefined()) {
15708                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15709                 Diag(PrevTagDecl->getLocation(),
15710                      diag::note_previous_definition);
15711                 Name = nullptr;
15712                 Previous.clear();
15713                 Invalid = true;
15714               }
15715             }
15716 
15717             // Okay, this is definition of a previously declared or referenced
15718             // tag. We're going to create a new Decl for it.
15719           }
15720 
15721           // Okay, we're going to make a redeclaration.  If this is some kind
15722           // of reference, make sure we build the redeclaration in the same DC
15723           // as the original, and ignore the current access specifier.
15724           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15725             SearchDC = PrevTagDecl->getDeclContext();
15726             AS = AS_none;
15727           }
15728         }
15729         // If we get here we have (another) forward declaration or we
15730         // have a definition.  Just create a new decl.
15731 
15732       } else {
15733         // If we get here, this is a definition of a new tag type in a nested
15734         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15735         // new decl/type.  We set PrevDecl to NULL so that the entities
15736         // have distinct types.
15737         Previous.clear();
15738       }
15739       // If we get here, we're going to create a new Decl. If PrevDecl
15740       // is non-NULL, it's a definition of the tag declared by
15741       // PrevDecl. If it's NULL, we have a new definition.
15742 
15743     // Otherwise, PrevDecl is not a tag, but was found with tag
15744     // lookup.  This is only actually possible in C++, where a few
15745     // things like templates still live in the tag namespace.
15746     } else {
15747       // Use a better diagnostic if an elaborated-type-specifier
15748       // found the wrong kind of type on the first
15749       // (non-redeclaration) lookup.
15750       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15751           !Previous.isForRedeclaration()) {
15752         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15753         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15754                                                        << Kind;
15755         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15756         Invalid = true;
15757 
15758       // Otherwise, only diagnose if the declaration is in scope.
15759       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15760                                 SS.isNotEmpty() || isMemberSpecialization)) {
15761         // do nothing
15762 
15763       // Diagnose implicit declarations introduced by elaborated types.
15764       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15765         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15766         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15767         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15768         Invalid = true;
15769 
15770       // Otherwise it's a declaration.  Call out a particularly common
15771       // case here.
15772       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15773         unsigned Kind = 0;
15774         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15775         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15776           << Name << Kind << TND->getUnderlyingType();
15777         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15778         Invalid = true;
15779 
15780       // Otherwise, diagnose.
15781       } else {
15782         // The tag name clashes with something else in the target scope,
15783         // issue an error and recover by making this tag be anonymous.
15784         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15785         notePreviousDefinition(PrevDecl, NameLoc);
15786         Name = nullptr;
15787         Invalid = true;
15788       }
15789 
15790       // The existing declaration isn't relevant to us; we're in a
15791       // new scope, so clear out the previous declaration.
15792       Previous.clear();
15793     }
15794   }
15795 
15796 CreateNewDecl:
15797 
15798   TagDecl *PrevDecl = nullptr;
15799   if (Previous.isSingleResult())
15800     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15801 
15802   // If there is an identifier, use the location of the identifier as the
15803   // location of the decl, otherwise use the location of the struct/union
15804   // keyword.
15805   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15806 
15807   // Otherwise, create a new declaration. If there is a previous
15808   // declaration of the same entity, the two will be linked via
15809   // PrevDecl.
15810   TagDecl *New;
15811 
15812   if (Kind == TTK_Enum) {
15813     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15814     // enum X { A, B, C } D;    D should chain to X.
15815     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15816                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15817                            ScopedEnumUsesClassTag, IsFixed);
15818 
15819     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15820       StdAlignValT = cast<EnumDecl>(New);
15821 
15822     // If this is an undefined enum, warn.
15823     if (TUK != TUK_Definition && !Invalid) {
15824       TagDecl *Def;
15825       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15826         // C++0x: 7.2p2: opaque-enum-declaration.
15827         // Conflicts are diagnosed above. Do nothing.
15828       }
15829       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15830         Diag(Loc, diag::ext_forward_ref_enum_def)
15831           << New;
15832         Diag(Def->getLocation(), diag::note_previous_definition);
15833       } else {
15834         unsigned DiagID = diag::ext_forward_ref_enum;
15835         if (getLangOpts().MSVCCompat)
15836           DiagID = diag::ext_ms_forward_ref_enum;
15837         else if (getLangOpts().CPlusPlus)
15838           DiagID = diag::err_forward_ref_enum;
15839         Diag(Loc, DiagID);
15840       }
15841     }
15842 
15843     if (EnumUnderlying) {
15844       EnumDecl *ED = cast<EnumDecl>(New);
15845       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15846         ED->setIntegerTypeSourceInfo(TI);
15847       else
15848         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15849       ED->setPromotionType(ED->getIntegerType());
15850       assert(ED->isComplete() && "enum with type should be complete");
15851     }
15852   } else {
15853     // struct/union/class
15854 
15855     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15856     // struct X { int A; } D;    D should chain to X.
15857     if (getLangOpts().CPlusPlus) {
15858       // FIXME: Look for a way to use RecordDecl for simple structs.
15859       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15860                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15861 
15862       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15863         StdBadAlloc = cast<CXXRecordDecl>(New);
15864     } else
15865       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15866                                cast_or_null<RecordDecl>(PrevDecl));
15867   }
15868 
15869   // C++11 [dcl.type]p3:
15870   //   A type-specifier-seq shall not define a class or enumeration [...].
15871   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15872       TUK == TUK_Definition) {
15873     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15874       << Context.getTagDeclType(New);
15875     Invalid = true;
15876   }
15877 
15878   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15879       DC->getDeclKind() == Decl::Enum) {
15880     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15881       << Context.getTagDeclType(New);
15882     Invalid = true;
15883   }
15884 
15885   // Maybe add qualifier info.
15886   if (SS.isNotEmpty()) {
15887     if (SS.isSet()) {
15888       // If this is either a declaration or a definition, check the
15889       // nested-name-specifier against the current context.
15890       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15891           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15892                                        isMemberSpecialization))
15893         Invalid = true;
15894 
15895       New->setQualifierInfo(SS.getWithLocInContext(Context));
15896       if (TemplateParameterLists.size() > 0) {
15897         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15898       }
15899     }
15900     else
15901       Invalid = true;
15902   }
15903 
15904   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15905     // Add alignment attributes if necessary; these attributes are checked when
15906     // the ASTContext lays out the structure.
15907     //
15908     // It is important for implementing the correct semantics that this
15909     // happen here (in ActOnTag). The #pragma pack stack is
15910     // maintained as a result of parser callbacks which can occur at
15911     // many points during the parsing of a struct declaration (because
15912     // the #pragma tokens are effectively skipped over during the
15913     // parsing of the struct).
15914     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15915       AddAlignmentAttributesForRecord(RD);
15916       AddMsStructLayoutForRecord(RD);
15917     }
15918   }
15919 
15920   if (ModulePrivateLoc.isValid()) {
15921     if (isMemberSpecialization)
15922       Diag(New->getLocation(), diag::err_module_private_specialization)
15923         << 2
15924         << FixItHint::CreateRemoval(ModulePrivateLoc);
15925     // __module_private__ does not apply to local classes. However, we only
15926     // diagnose this as an error when the declaration specifiers are
15927     // freestanding. Here, we just ignore the __module_private__.
15928     else if (!SearchDC->isFunctionOrMethod())
15929       New->setModulePrivate();
15930   }
15931 
15932   // If this is a specialization of a member class (of a class template),
15933   // check the specialization.
15934   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15935     Invalid = true;
15936 
15937   // If we're declaring or defining a tag in function prototype scope in C,
15938   // note that this type can only be used within the function and add it to
15939   // the list of decls to inject into the function definition scope.
15940   if ((Name || Kind == TTK_Enum) &&
15941       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15942     if (getLangOpts().CPlusPlus) {
15943       // C++ [dcl.fct]p6:
15944       //   Types shall not be defined in return or parameter types.
15945       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15946         Diag(Loc, diag::err_type_defined_in_param_type)
15947             << Name;
15948         Invalid = true;
15949       }
15950     } else if (!PrevDecl) {
15951       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15952     }
15953   }
15954 
15955   if (Invalid)
15956     New->setInvalidDecl();
15957 
15958   // Set the lexical context. If the tag has a C++ scope specifier, the
15959   // lexical context will be different from the semantic context.
15960   New->setLexicalDeclContext(CurContext);
15961 
15962   // Mark this as a friend decl if applicable.
15963   // In Microsoft mode, a friend declaration also acts as a forward
15964   // declaration so we always pass true to setObjectOfFriendDecl to make
15965   // the tag name visible.
15966   if (TUK == TUK_Friend)
15967     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15968 
15969   // Set the access specifier.
15970   if (!Invalid && SearchDC->isRecord())
15971     SetMemberAccessSpecifier(New, PrevDecl, AS);
15972 
15973   if (PrevDecl)
15974     CheckRedeclarationModuleOwnership(New, PrevDecl);
15975 
15976   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15977     New->startDefinition();
15978 
15979   ProcessDeclAttributeList(S, New, Attrs);
15980   AddPragmaAttributes(S, New);
15981 
15982   // If this has an identifier, add it to the scope stack.
15983   if (TUK == TUK_Friend) {
15984     // We might be replacing an existing declaration in the lookup tables;
15985     // if so, borrow its access specifier.
15986     if (PrevDecl)
15987       New->setAccess(PrevDecl->getAccess());
15988 
15989     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15990     DC->makeDeclVisibleInContext(New);
15991     if (Name) // can be null along some error paths
15992       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15993         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15994   } else if (Name) {
15995     S = getNonFieldDeclScope(S);
15996     PushOnScopeChains(New, S, true);
15997   } else {
15998     CurContext->addDecl(New);
15999   }
16000 
16001   // If this is the C FILE type, notify the AST context.
16002   if (IdentifierInfo *II = New->getIdentifier())
16003     if (!New->isInvalidDecl() &&
16004         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16005         II->isStr("FILE"))
16006       Context.setFILEDecl(New);
16007 
16008   if (PrevDecl)
16009     mergeDeclAttributes(New, PrevDecl);
16010 
16011   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16012     inferGslOwnerPointerAttribute(CXXRD);
16013 
16014   // If there's a #pragma GCC visibility in scope, set the visibility of this
16015   // record.
16016   AddPushedVisibilityAttribute(New);
16017 
16018   if (isMemberSpecialization && !New->isInvalidDecl())
16019     CompleteMemberSpecialization(New, Previous);
16020 
16021   OwnedDecl = true;
16022   // In C++, don't return an invalid declaration. We can't recover well from
16023   // the cases where we make the type anonymous.
16024   if (Invalid && getLangOpts().CPlusPlus) {
16025     if (New->isBeingDefined())
16026       if (auto RD = dyn_cast<RecordDecl>(New))
16027         RD->completeDefinition();
16028     return nullptr;
16029   } else if (SkipBody && SkipBody->ShouldSkip) {
16030     return SkipBody->Previous;
16031   } else {
16032     return New;
16033   }
16034 }
16035 
16036 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16037   AdjustDeclIfTemplate(TagD);
16038   TagDecl *Tag = cast<TagDecl>(TagD);
16039 
16040   // Enter the tag context.
16041   PushDeclContext(S, Tag);
16042 
16043   ActOnDocumentableDecl(TagD);
16044 
16045   // If there's a #pragma GCC visibility in scope, set the visibility of this
16046   // record.
16047   AddPushedVisibilityAttribute(Tag);
16048 }
16049 
16050 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16051                                     SkipBodyInfo &SkipBody) {
16052   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16053     return false;
16054 
16055   // Make the previous decl visible.
16056   makeMergedDefinitionVisible(SkipBody.Previous);
16057   return true;
16058 }
16059 
16060 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16061   assert(isa<ObjCContainerDecl>(IDecl) &&
16062          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16063   DeclContext *OCD = cast<DeclContext>(IDecl);
16064   assert(getContainingDC(OCD) == CurContext &&
16065       "The next DeclContext should be lexically contained in the current one.");
16066   CurContext = OCD;
16067   return IDecl;
16068 }
16069 
16070 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16071                                            SourceLocation FinalLoc,
16072                                            bool IsFinalSpelledSealed,
16073                                            SourceLocation LBraceLoc) {
16074   AdjustDeclIfTemplate(TagD);
16075   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16076 
16077   FieldCollector->StartClass();
16078 
16079   if (!Record->getIdentifier())
16080     return;
16081 
16082   if (FinalLoc.isValid())
16083     Record->addAttr(FinalAttr::Create(
16084         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16085         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16086 
16087   // C++ [class]p2:
16088   //   [...] The class-name is also inserted into the scope of the
16089   //   class itself; this is known as the injected-class-name. For
16090   //   purposes of access checking, the injected-class-name is treated
16091   //   as if it were a public member name.
16092   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16093       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16094       Record->getLocation(), Record->getIdentifier(),
16095       /*PrevDecl=*/nullptr,
16096       /*DelayTypeCreation=*/true);
16097   Context.getTypeDeclType(InjectedClassName, Record);
16098   InjectedClassName->setImplicit();
16099   InjectedClassName->setAccess(AS_public);
16100   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16101       InjectedClassName->setDescribedClassTemplate(Template);
16102   PushOnScopeChains(InjectedClassName, S);
16103   assert(InjectedClassName->isInjectedClassName() &&
16104          "Broken injected-class-name");
16105 }
16106 
16107 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16108                                     SourceRange BraceRange) {
16109   AdjustDeclIfTemplate(TagD);
16110   TagDecl *Tag = cast<TagDecl>(TagD);
16111   Tag->setBraceRange(BraceRange);
16112 
16113   // Make sure we "complete" the definition even it is invalid.
16114   if (Tag->isBeingDefined()) {
16115     assert(Tag->isInvalidDecl() && "We should already have completed it");
16116     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16117       RD->completeDefinition();
16118   }
16119 
16120   if (isa<CXXRecordDecl>(Tag)) {
16121     FieldCollector->FinishClass();
16122   }
16123 
16124   // Exit this scope of this tag's definition.
16125   PopDeclContext();
16126 
16127   if (getCurLexicalContext()->isObjCContainer() &&
16128       Tag->getDeclContext()->isFileContext())
16129     Tag->setTopLevelDeclInObjCContainer();
16130 
16131   // Notify the consumer that we've defined a tag.
16132   if (!Tag->isInvalidDecl())
16133     Consumer.HandleTagDeclDefinition(Tag);
16134 }
16135 
16136 void Sema::ActOnObjCContainerFinishDefinition() {
16137   // Exit this scope of this interface definition.
16138   PopDeclContext();
16139 }
16140 
16141 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16142   assert(DC == CurContext && "Mismatch of container contexts");
16143   OriginalLexicalContext = DC;
16144   ActOnObjCContainerFinishDefinition();
16145 }
16146 
16147 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16148   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16149   OriginalLexicalContext = nullptr;
16150 }
16151 
16152 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16153   AdjustDeclIfTemplate(TagD);
16154   TagDecl *Tag = cast<TagDecl>(TagD);
16155   Tag->setInvalidDecl();
16156 
16157   // Make sure we "complete" the definition even it is invalid.
16158   if (Tag->isBeingDefined()) {
16159     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16160       RD->completeDefinition();
16161   }
16162 
16163   // We're undoing ActOnTagStartDefinition here, not
16164   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16165   // the FieldCollector.
16166 
16167   PopDeclContext();
16168 }
16169 
16170 // Note that FieldName may be null for anonymous bitfields.
16171 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16172                                 IdentifierInfo *FieldName,
16173                                 QualType FieldTy, bool IsMsStruct,
16174                                 Expr *BitWidth, bool *ZeroWidth) {
16175   assert(BitWidth);
16176   if (BitWidth->containsErrors())
16177     return ExprError();
16178 
16179   // Default to true; that shouldn't confuse checks for emptiness
16180   if (ZeroWidth)
16181     *ZeroWidth = true;
16182 
16183   // C99 6.7.2.1p4 - verify the field type.
16184   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16185   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16186     // Handle incomplete and sizeless types with a specific error.
16187     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16188                                  diag::err_field_incomplete_or_sizeless))
16189       return ExprError();
16190     if (FieldName)
16191       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16192         << FieldName << FieldTy << BitWidth->getSourceRange();
16193     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16194       << FieldTy << BitWidth->getSourceRange();
16195   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16196                                              UPPC_BitFieldWidth))
16197     return ExprError();
16198 
16199   // If the bit-width is type- or value-dependent, don't try to check
16200   // it now.
16201   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16202     return BitWidth;
16203 
16204   llvm::APSInt Value;
16205   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16206   if (ICE.isInvalid())
16207     return ICE;
16208   BitWidth = ICE.get();
16209 
16210   if (Value != 0 && ZeroWidth)
16211     *ZeroWidth = false;
16212 
16213   // Zero-width bitfield is ok for anonymous field.
16214   if (Value == 0 && FieldName)
16215     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16216 
16217   if (Value.isSigned() && Value.isNegative()) {
16218     if (FieldName)
16219       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16220                << FieldName << Value.toString(10);
16221     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16222       << Value.toString(10);
16223   }
16224 
16225   if (!FieldTy->isDependentType()) {
16226     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16227     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16228     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16229 
16230     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16231     // ABI.
16232     bool CStdConstraintViolation =
16233         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16234     bool MSBitfieldViolation =
16235         Value.ugt(TypeStorageSize) &&
16236         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16237     if (CStdConstraintViolation || MSBitfieldViolation) {
16238       unsigned DiagWidth =
16239           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16240       if (FieldName)
16241         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16242                << FieldName << (unsigned)Value.getZExtValue()
16243                << !CStdConstraintViolation << DiagWidth;
16244 
16245       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16246              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16247              << DiagWidth;
16248     }
16249 
16250     // Warn on types where the user might conceivably expect to get all
16251     // specified bits as value bits: that's all integral types other than
16252     // 'bool'.
16253     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16254       if (FieldName)
16255         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16256             << FieldName << (unsigned)Value.getZExtValue()
16257             << (unsigned)TypeWidth;
16258       else
16259         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16260             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16261     }
16262   }
16263 
16264   return BitWidth;
16265 }
16266 
16267 /// ActOnField - Each field of a C struct/union is passed into this in order
16268 /// to create a FieldDecl object for it.
16269 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16270                        Declarator &D, Expr *BitfieldWidth) {
16271   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16272                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16273                                /*InitStyle=*/ICIS_NoInit, AS_public);
16274   return Res;
16275 }
16276 
16277 /// HandleField - Analyze a field of a C struct or a C++ data member.
16278 ///
16279 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16280                              SourceLocation DeclStart,
16281                              Declarator &D, Expr *BitWidth,
16282                              InClassInitStyle InitStyle,
16283                              AccessSpecifier AS) {
16284   if (D.isDecompositionDeclarator()) {
16285     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16286     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16287       << Decomp.getSourceRange();
16288     return nullptr;
16289   }
16290 
16291   IdentifierInfo *II = D.getIdentifier();
16292   SourceLocation Loc = DeclStart;
16293   if (II) Loc = D.getIdentifierLoc();
16294 
16295   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16296   QualType T = TInfo->getType();
16297   if (getLangOpts().CPlusPlus) {
16298     CheckExtraCXXDefaultArguments(D);
16299 
16300     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16301                                         UPPC_DataMemberType)) {
16302       D.setInvalidType();
16303       T = Context.IntTy;
16304       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16305     }
16306   }
16307 
16308   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16309 
16310   if (D.getDeclSpec().isInlineSpecified())
16311     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16312         << getLangOpts().CPlusPlus17;
16313   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16314     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16315          diag::err_invalid_thread)
16316       << DeclSpec::getSpecifierName(TSCS);
16317 
16318   // Check to see if this name was declared as a member previously
16319   NamedDecl *PrevDecl = nullptr;
16320   LookupResult Previous(*this, II, Loc, LookupMemberName,
16321                         ForVisibleRedeclaration);
16322   LookupName(Previous, S);
16323   switch (Previous.getResultKind()) {
16324     case LookupResult::Found:
16325     case LookupResult::FoundUnresolvedValue:
16326       PrevDecl = Previous.getAsSingle<NamedDecl>();
16327       break;
16328 
16329     case LookupResult::FoundOverloaded:
16330       PrevDecl = Previous.getRepresentativeDecl();
16331       break;
16332 
16333     case LookupResult::NotFound:
16334     case LookupResult::NotFoundInCurrentInstantiation:
16335     case LookupResult::Ambiguous:
16336       break;
16337   }
16338   Previous.suppressDiagnostics();
16339 
16340   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16341     // Maybe we will complain about the shadowed template parameter.
16342     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16343     // Just pretend that we didn't see the previous declaration.
16344     PrevDecl = nullptr;
16345   }
16346 
16347   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16348     PrevDecl = nullptr;
16349 
16350   bool Mutable
16351     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16352   SourceLocation TSSL = D.getBeginLoc();
16353   FieldDecl *NewFD
16354     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16355                      TSSL, AS, PrevDecl, &D);
16356 
16357   if (NewFD->isInvalidDecl())
16358     Record->setInvalidDecl();
16359 
16360   if (D.getDeclSpec().isModulePrivateSpecified())
16361     NewFD->setModulePrivate();
16362 
16363   if (NewFD->isInvalidDecl() && PrevDecl) {
16364     // Don't introduce NewFD into scope; there's already something
16365     // with the same name in the same scope.
16366   } else if (II) {
16367     PushOnScopeChains(NewFD, S);
16368   } else
16369     Record->addDecl(NewFD);
16370 
16371   return NewFD;
16372 }
16373 
16374 /// Build a new FieldDecl and check its well-formedness.
16375 ///
16376 /// This routine builds a new FieldDecl given the fields name, type,
16377 /// record, etc. \p PrevDecl should refer to any previous declaration
16378 /// with the same name and in the same scope as the field to be
16379 /// created.
16380 ///
16381 /// \returns a new FieldDecl.
16382 ///
16383 /// \todo The Declarator argument is a hack. It will be removed once
16384 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16385                                 TypeSourceInfo *TInfo,
16386                                 RecordDecl *Record, SourceLocation Loc,
16387                                 bool Mutable, Expr *BitWidth,
16388                                 InClassInitStyle InitStyle,
16389                                 SourceLocation TSSL,
16390                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16391                                 Declarator *D) {
16392   IdentifierInfo *II = Name.getAsIdentifierInfo();
16393   bool InvalidDecl = false;
16394   if (D) InvalidDecl = D->isInvalidType();
16395 
16396   // If we receive a broken type, recover by assuming 'int' and
16397   // marking this declaration as invalid.
16398   if (T.isNull()) {
16399     InvalidDecl = true;
16400     T = Context.IntTy;
16401   }
16402 
16403   QualType EltTy = Context.getBaseElementType(T);
16404   if (!EltTy->isDependentType()) {
16405     if (RequireCompleteSizedType(Loc, EltTy,
16406                                  diag::err_field_incomplete_or_sizeless)) {
16407       // Fields of incomplete type force their record to be invalid.
16408       Record->setInvalidDecl();
16409       InvalidDecl = true;
16410     } else {
16411       NamedDecl *Def;
16412       EltTy->isIncompleteType(&Def);
16413       if (Def && Def->isInvalidDecl()) {
16414         Record->setInvalidDecl();
16415         InvalidDecl = true;
16416       }
16417     }
16418   }
16419 
16420   // TR 18037 does not allow fields to be declared with address space
16421   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16422       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16423     Diag(Loc, diag::err_field_with_address_space);
16424     Record->setInvalidDecl();
16425     InvalidDecl = true;
16426   }
16427 
16428   if (LangOpts.OpenCL) {
16429     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16430     // used as structure or union field: image, sampler, event or block types.
16431     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16432         T->isBlockPointerType()) {
16433       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16434       Record->setInvalidDecl();
16435       InvalidDecl = true;
16436     }
16437     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16438     if (BitWidth) {
16439       Diag(Loc, diag::err_opencl_bitfields);
16440       InvalidDecl = true;
16441     }
16442   }
16443 
16444   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16445   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16446       T.hasQualifiers()) {
16447     InvalidDecl = true;
16448     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16449   }
16450 
16451   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16452   // than a variably modified type.
16453   if (!InvalidDecl && T->isVariablyModifiedType()) {
16454     bool SizeIsNegative;
16455     llvm::APSInt Oversized;
16456 
16457     TypeSourceInfo *FixedTInfo =
16458       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16459                                                     SizeIsNegative,
16460                                                     Oversized);
16461     if (FixedTInfo) {
16462       Diag(Loc, diag::warn_illegal_constant_array_size);
16463       TInfo = FixedTInfo;
16464       T = FixedTInfo->getType();
16465     } else {
16466       if (SizeIsNegative)
16467         Diag(Loc, diag::err_typecheck_negative_array_size);
16468       else if (Oversized.getBoolValue())
16469         Diag(Loc, diag::err_array_too_large)
16470           << Oversized.toString(10);
16471       else
16472         Diag(Loc, diag::err_typecheck_field_variable_size);
16473       InvalidDecl = true;
16474     }
16475   }
16476 
16477   // Fields can not have abstract class types
16478   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16479                                              diag::err_abstract_type_in_decl,
16480                                              AbstractFieldType))
16481     InvalidDecl = true;
16482 
16483   bool ZeroWidth = false;
16484   if (InvalidDecl)
16485     BitWidth = nullptr;
16486   // If this is declared as a bit-field, check the bit-field.
16487   if (BitWidth) {
16488     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16489                               &ZeroWidth).get();
16490     if (!BitWidth) {
16491       InvalidDecl = true;
16492       BitWidth = nullptr;
16493       ZeroWidth = false;
16494     }
16495   }
16496 
16497   // Check that 'mutable' is consistent with the type of the declaration.
16498   if (!InvalidDecl && Mutable) {
16499     unsigned DiagID = 0;
16500     if (T->isReferenceType())
16501       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16502                                         : diag::err_mutable_reference;
16503     else if (T.isConstQualified())
16504       DiagID = diag::err_mutable_const;
16505 
16506     if (DiagID) {
16507       SourceLocation ErrLoc = Loc;
16508       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16509         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16510       Diag(ErrLoc, DiagID);
16511       if (DiagID != diag::ext_mutable_reference) {
16512         Mutable = false;
16513         InvalidDecl = true;
16514       }
16515     }
16516   }
16517 
16518   // C++11 [class.union]p8 (DR1460):
16519   //   At most one variant member of a union may have a
16520   //   brace-or-equal-initializer.
16521   if (InitStyle != ICIS_NoInit)
16522     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16523 
16524   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16525                                        BitWidth, Mutable, InitStyle);
16526   if (InvalidDecl)
16527     NewFD->setInvalidDecl();
16528 
16529   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16530     Diag(Loc, diag::err_duplicate_member) << II;
16531     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16532     NewFD->setInvalidDecl();
16533   }
16534 
16535   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16536     if (Record->isUnion()) {
16537       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16538         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16539         if (RDecl->getDefinition()) {
16540           // C++ [class.union]p1: An object of a class with a non-trivial
16541           // constructor, a non-trivial copy constructor, a non-trivial
16542           // destructor, or a non-trivial copy assignment operator
16543           // cannot be a member of a union, nor can an array of such
16544           // objects.
16545           if (CheckNontrivialField(NewFD))
16546             NewFD->setInvalidDecl();
16547         }
16548       }
16549 
16550       // C++ [class.union]p1: If a union contains a member of reference type,
16551       // the program is ill-formed, except when compiling with MSVC extensions
16552       // enabled.
16553       if (EltTy->isReferenceType()) {
16554         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16555                                     diag::ext_union_member_of_reference_type :
16556                                     diag::err_union_member_of_reference_type)
16557           << NewFD->getDeclName() << EltTy;
16558         if (!getLangOpts().MicrosoftExt)
16559           NewFD->setInvalidDecl();
16560       }
16561     }
16562   }
16563 
16564   // FIXME: We need to pass in the attributes given an AST
16565   // representation, not a parser representation.
16566   if (D) {
16567     // FIXME: The current scope is almost... but not entirely... correct here.
16568     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16569 
16570     if (NewFD->hasAttrs())
16571       CheckAlignasUnderalignment(NewFD);
16572   }
16573 
16574   // In auto-retain/release, infer strong retension for fields of
16575   // retainable type.
16576   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16577     NewFD->setInvalidDecl();
16578 
16579   if (T.isObjCGCWeak())
16580     Diag(Loc, diag::warn_attribute_weak_on_field);
16581 
16582   NewFD->setAccess(AS);
16583   return NewFD;
16584 }
16585 
16586 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16587   assert(FD);
16588   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16589 
16590   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16591     return false;
16592 
16593   QualType EltTy = Context.getBaseElementType(FD->getType());
16594   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16595     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16596     if (RDecl->getDefinition()) {
16597       // We check for copy constructors before constructors
16598       // because otherwise we'll never get complaints about
16599       // copy constructors.
16600 
16601       CXXSpecialMember member = CXXInvalid;
16602       // We're required to check for any non-trivial constructors. Since the
16603       // implicit default constructor is suppressed if there are any
16604       // user-declared constructors, we just need to check that there is a
16605       // trivial default constructor and a trivial copy constructor. (We don't
16606       // worry about move constructors here, since this is a C++98 check.)
16607       if (RDecl->hasNonTrivialCopyConstructor())
16608         member = CXXCopyConstructor;
16609       else if (!RDecl->hasTrivialDefaultConstructor())
16610         member = CXXDefaultConstructor;
16611       else if (RDecl->hasNonTrivialCopyAssignment())
16612         member = CXXCopyAssignment;
16613       else if (RDecl->hasNonTrivialDestructor())
16614         member = CXXDestructor;
16615 
16616       if (member != CXXInvalid) {
16617         if (!getLangOpts().CPlusPlus11 &&
16618             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16619           // Objective-C++ ARC: it is an error to have a non-trivial field of
16620           // a union. However, system headers in Objective-C programs
16621           // occasionally have Objective-C lifetime objects within unions,
16622           // and rather than cause the program to fail, we make those
16623           // members unavailable.
16624           SourceLocation Loc = FD->getLocation();
16625           if (getSourceManager().isInSystemHeader(Loc)) {
16626             if (!FD->hasAttr<UnavailableAttr>())
16627               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16628                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16629             return false;
16630           }
16631         }
16632 
16633         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16634                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16635                diag::err_illegal_union_or_anon_struct_member)
16636           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16637         DiagnoseNontrivial(RDecl, member);
16638         return !getLangOpts().CPlusPlus11;
16639       }
16640     }
16641   }
16642 
16643   return false;
16644 }
16645 
16646 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16647 ///  AST enum value.
16648 static ObjCIvarDecl::AccessControl
16649 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16650   switch (ivarVisibility) {
16651   default: llvm_unreachable("Unknown visitibility kind");
16652   case tok::objc_private: return ObjCIvarDecl::Private;
16653   case tok::objc_public: return ObjCIvarDecl::Public;
16654   case tok::objc_protected: return ObjCIvarDecl::Protected;
16655   case tok::objc_package: return ObjCIvarDecl::Package;
16656   }
16657 }
16658 
16659 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16660 /// in order to create an IvarDecl object for it.
16661 Decl *Sema::ActOnIvar(Scope *S,
16662                                 SourceLocation DeclStart,
16663                                 Declarator &D, Expr *BitfieldWidth,
16664                                 tok::ObjCKeywordKind Visibility) {
16665 
16666   IdentifierInfo *II = D.getIdentifier();
16667   Expr *BitWidth = (Expr*)BitfieldWidth;
16668   SourceLocation Loc = DeclStart;
16669   if (II) Loc = D.getIdentifierLoc();
16670 
16671   // FIXME: Unnamed fields can be handled in various different ways, for
16672   // example, unnamed unions inject all members into the struct namespace!
16673 
16674   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16675   QualType T = TInfo->getType();
16676 
16677   if (BitWidth) {
16678     // 6.7.2.1p3, 6.7.2.1p4
16679     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16680     if (!BitWidth)
16681       D.setInvalidType();
16682   } else {
16683     // Not a bitfield.
16684 
16685     // validate II.
16686 
16687   }
16688   if (T->isReferenceType()) {
16689     Diag(Loc, diag::err_ivar_reference_type);
16690     D.setInvalidType();
16691   }
16692   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16693   // than a variably modified type.
16694   else if (T->isVariablyModifiedType()) {
16695     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16696     D.setInvalidType();
16697   }
16698 
16699   // Get the visibility (access control) for this ivar.
16700   ObjCIvarDecl::AccessControl ac =
16701     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16702                                         : ObjCIvarDecl::None;
16703   // Must set ivar's DeclContext to its enclosing interface.
16704   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16705   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16706     return nullptr;
16707   ObjCContainerDecl *EnclosingContext;
16708   if (ObjCImplementationDecl *IMPDecl =
16709       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16710     if (LangOpts.ObjCRuntime.isFragile()) {
16711     // Case of ivar declared in an implementation. Context is that of its class.
16712       EnclosingContext = IMPDecl->getClassInterface();
16713       assert(EnclosingContext && "Implementation has no class interface!");
16714     }
16715     else
16716       EnclosingContext = EnclosingDecl;
16717   } else {
16718     if (ObjCCategoryDecl *CDecl =
16719         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16720       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16721         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16722         return nullptr;
16723       }
16724     }
16725     EnclosingContext = EnclosingDecl;
16726   }
16727 
16728   // Construct the decl.
16729   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16730                                              DeclStart, Loc, II, T,
16731                                              TInfo, ac, (Expr *)BitfieldWidth);
16732 
16733   if (II) {
16734     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16735                                            ForVisibleRedeclaration);
16736     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16737         && !isa<TagDecl>(PrevDecl)) {
16738       Diag(Loc, diag::err_duplicate_member) << II;
16739       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16740       NewID->setInvalidDecl();
16741     }
16742   }
16743 
16744   // Process attributes attached to the ivar.
16745   ProcessDeclAttributes(S, NewID, D);
16746 
16747   if (D.isInvalidType())
16748     NewID->setInvalidDecl();
16749 
16750   // In ARC, infer 'retaining' for ivars of retainable type.
16751   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16752     NewID->setInvalidDecl();
16753 
16754   if (D.getDeclSpec().isModulePrivateSpecified())
16755     NewID->setModulePrivate();
16756 
16757   if (II) {
16758     // FIXME: When interfaces are DeclContexts, we'll need to add
16759     // these to the interface.
16760     S->AddDecl(NewID);
16761     IdResolver.AddDecl(NewID);
16762   }
16763 
16764   if (LangOpts.ObjCRuntime.isNonFragile() &&
16765       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16766     Diag(Loc, diag::warn_ivars_in_interface);
16767 
16768   return NewID;
16769 }
16770 
16771 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16772 /// class and class extensions. For every class \@interface and class
16773 /// extension \@interface, if the last ivar is a bitfield of any type,
16774 /// then add an implicit `char :0` ivar to the end of that interface.
16775 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16776                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16777   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16778     return;
16779 
16780   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16781   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16782 
16783   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16784     return;
16785   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16786   if (!ID) {
16787     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16788       if (!CD->IsClassExtension())
16789         return;
16790     }
16791     // No need to add this to end of @implementation.
16792     else
16793       return;
16794   }
16795   // All conditions are met. Add a new bitfield to the tail end of ivars.
16796   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16797   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16798 
16799   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16800                               DeclLoc, DeclLoc, nullptr,
16801                               Context.CharTy,
16802                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16803                                                                DeclLoc),
16804                               ObjCIvarDecl::Private, BW,
16805                               true);
16806   AllIvarDecls.push_back(Ivar);
16807 }
16808 
16809 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16810                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16811                        SourceLocation RBrac,
16812                        const ParsedAttributesView &Attrs) {
16813   assert(EnclosingDecl && "missing record or interface decl");
16814 
16815   // If this is an Objective-C @implementation or category and we have
16816   // new fields here we should reset the layout of the interface since
16817   // it will now change.
16818   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16819     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16820     switch (DC->getKind()) {
16821     default: break;
16822     case Decl::ObjCCategory:
16823       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16824       break;
16825     case Decl::ObjCImplementation:
16826       Context.
16827         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16828       break;
16829     }
16830   }
16831 
16832   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16833   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16834 
16835   // Start counting up the number of named members; make sure to include
16836   // members of anonymous structs and unions in the total.
16837   unsigned NumNamedMembers = 0;
16838   if (Record) {
16839     for (const auto *I : Record->decls()) {
16840       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16841         if (IFD->getDeclName())
16842           ++NumNamedMembers;
16843     }
16844   }
16845 
16846   // Verify that all the fields are okay.
16847   SmallVector<FieldDecl*, 32> RecFields;
16848 
16849   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16850        i != end; ++i) {
16851     FieldDecl *FD = cast<FieldDecl>(*i);
16852 
16853     // Get the type for the field.
16854     const Type *FDTy = FD->getType().getTypePtr();
16855 
16856     if (!FD->isAnonymousStructOrUnion()) {
16857       // Remember all fields written by the user.
16858       RecFields.push_back(FD);
16859     }
16860 
16861     // If the field is already invalid for some reason, don't emit more
16862     // diagnostics about it.
16863     if (FD->isInvalidDecl()) {
16864       EnclosingDecl->setInvalidDecl();
16865       continue;
16866     }
16867 
16868     // C99 6.7.2.1p2:
16869     //   A structure or union shall not contain a member with
16870     //   incomplete or function type (hence, a structure shall not
16871     //   contain an instance of itself, but may contain a pointer to
16872     //   an instance of itself), except that the last member of a
16873     //   structure with more than one named member may have incomplete
16874     //   array type; such a structure (and any union containing,
16875     //   possibly recursively, a member that is such a structure)
16876     //   shall not be a member of a structure or an element of an
16877     //   array.
16878     bool IsLastField = (i + 1 == Fields.end());
16879     if (FDTy->isFunctionType()) {
16880       // Field declared as a function.
16881       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16882         << FD->getDeclName();
16883       FD->setInvalidDecl();
16884       EnclosingDecl->setInvalidDecl();
16885       continue;
16886     } else if (FDTy->isIncompleteArrayType() &&
16887                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16888       if (Record) {
16889         // Flexible array member.
16890         // Microsoft and g++ is more permissive regarding flexible array.
16891         // It will accept flexible array in union and also
16892         // as the sole element of a struct/class.
16893         unsigned DiagID = 0;
16894         if (!Record->isUnion() && !IsLastField) {
16895           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16896             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16897           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16898           FD->setInvalidDecl();
16899           EnclosingDecl->setInvalidDecl();
16900           continue;
16901         } else if (Record->isUnion())
16902           DiagID = getLangOpts().MicrosoftExt
16903                        ? diag::ext_flexible_array_union_ms
16904                        : getLangOpts().CPlusPlus
16905                              ? diag::ext_flexible_array_union_gnu
16906                              : diag::err_flexible_array_union;
16907         else if (NumNamedMembers < 1)
16908           DiagID = getLangOpts().MicrosoftExt
16909                        ? diag::ext_flexible_array_empty_aggregate_ms
16910                        : getLangOpts().CPlusPlus
16911                              ? diag::ext_flexible_array_empty_aggregate_gnu
16912                              : diag::err_flexible_array_empty_aggregate;
16913 
16914         if (DiagID)
16915           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16916                                           << Record->getTagKind();
16917         // While the layout of types that contain virtual bases is not specified
16918         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16919         // virtual bases after the derived members.  This would make a flexible
16920         // array member declared at the end of an object not adjacent to the end
16921         // of the type.
16922         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16923           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16924               << FD->getDeclName() << Record->getTagKind();
16925         if (!getLangOpts().C99)
16926           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16927             << FD->getDeclName() << Record->getTagKind();
16928 
16929         // If the element type has a non-trivial destructor, we would not
16930         // implicitly destroy the elements, so disallow it for now.
16931         //
16932         // FIXME: GCC allows this. We should probably either implicitly delete
16933         // the destructor of the containing class, or just allow this.
16934         QualType BaseElem = Context.getBaseElementType(FD->getType());
16935         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16936           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16937             << FD->getDeclName() << FD->getType();
16938           FD->setInvalidDecl();
16939           EnclosingDecl->setInvalidDecl();
16940           continue;
16941         }
16942         // Okay, we have a legal flexible array member at the end of the struct.
16943         Record->setHasFlexibleArrayMember(true);
16944       } else {
16945         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16946         // unless they are followed by another ivar. That check is done
16947         // elsewhere, after synthesized ivars are known.
16948       }
16949     } else if (!FDTy->isDependentType() &&
16950                RequireCompleteSizedType(
16951                    FD->getLocation(), FD->getType(),
16952                    diag::err_field_incomplete_or_sizeless)) {
16953       // Incomplete type
16954       FD->setInvalidDecl();
16955       EnclosingDecl->setInvalidDecl();
16956       continue;
16957     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16958       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16959         // A type which contains a flexible array member is considered to be a
16960         // flexible array member.
16961         Record->setHasFlexibleArrayMember(true);
16962         if (!Record->isUnion()) {
16963           // If this is a struct/class and this is not the last element, reject
16964           // it.  Note that GCC supports variable sized arrays in the middle of
16965           // structures.
16966           if (!IsLastField)
16967             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16968               << FD->getDeclName() << FD->getType();
16969           else {
16970             // We support flexible arrays at the end of structs in
16971             // other structs as an extension.
16972             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16973               << FD->getDeclName();
16974           }
16975         }
16976       }
16977       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16978           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16979                                  diag::err_abstract_type_in_decl,
16980                                  AbstractIvarType)) {
16981         // Ivars can not have abstract class types
16982         FD->setInvalidDecl();
16983       }
16984       if (Record && FDTTy->getDecl()->hasObjectMember())
16985         Record->setHasObjectMember(true);
16986       if (Record && FDTTy->getDecl()->hasVolatileMember())
16987         Record->setHasVolatileMember(true);
16988     } else if (FDTy->isObjCObjectType()) {
16989       /// A field cannot be an Objective-c object
16990       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16991         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16992       QualType T = Context.getObjCObjectPointerType(FD->getType());
16993       FD->setType(T);
16994     } else if (Record && Record->isUnion() &&
16995                FD->getType().hasNonTrivialObjCLifetime() &&
16996                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16997                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16998                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16999                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17000       // For backward compatibility, fields of C unions declared in system
17001       // headers that have non-trivial ObjC ownership qualifications are marked
17002       // as unavailable unless the qualifier is explicit and __strong. This can
17003       // break ABI compatibility between programs compiled with ARC and MRR, but
17004       // is a better option than rejecting programs using those unions under
17005       // ARC.
17006       FD->addAttr(UnavailableAttr::CreateImplicit(
17007           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17008           FD->getLocation()));
17009     } else if (getLangOpts().ObjC &&
17010                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17011                !Record->hasObjectMember()) {
17012       if (FD->getType()->isObjCObjectPointerType() ||
17013           FD->getType().isObjCGCStrong())
17014         Record->setHasObjectMember(true);
17015       else if (Context.getAsArrayType(FD->getType())) {
17016         QualType BaseType = Context.getBaseElementType(FD->getType());
17017         if (BaseType->isRecordType() &&
17018             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17019           Record->setHasObjectMember(true);
17020         else if (BaseType->isObjCObjectPointerType() ||
17021                  BaseType.isObjCGCStrong())
17022                Record->setHasObjectMember(true);
17023       }
17024     }
17025 
17026     if (Record && !getLangOpts().CPlusPlus &&
17027         !shouldIgnoreForRecordTriviality(FD)) {
17028       QualType FT = FD->getType();
17029       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17030         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17031         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17032             Record->isUnion())
17033           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17034       }
17035       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17036       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17037         Record->setNonTrivialToPrimitiveCopy(true);
17038         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17039           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17040       }
17041       if (FT.isDestructedType()) {
17042         Record->setNonTrivialToPrimitiveDestroy(true);
17043         Record->setParamDestroyedInCallee(true);
17044         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17045           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17046       }
17047 
17048       if (const auto *RT = FT->getAs<RecordType>()) {
17049         if (RT->getDecl()->getArgPassingRestrictions() ==
17050             RecordDecl::APK_CanNeverPassInRegs)
17051           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17052       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17053         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17054     }
17055 
17056     if (Record && FD->getType().isVolatileQualified())
17057       Record->setHasVolatileMember(true);
17058     // Keep track of the number of named members.
17059     if (FD->getIdentifier())
17060       ++NumNamedMembers;
17061   }
17062 
17063   // Okay, we successfully defined 'Record'.
17064   if (Record) {
17065     bool Completed = false;
17066     if (CXXRecord) {
17067       if (!CXXRecord->isInvalidDecl()) {
17068         // Set access bits correctly on the directly-declared conversions.
17069         for (CXXRecordDecl::conversion_iterator
17070                I = CXXRecord->conversion_begin(),
17071                E = CXXRecord->conversion_end(); I != E; ++I)
17072           I.setAccess((*I)->getAccess());
17073       }
17074 
17075       if (!CXXRecord->isDependentType()) {
17076         // Add any implicitly-declared members to this class.
17077         AddImplicitlyDeclaredMembersToClass(CXXRecord);
17078 
17079         if (!CXXRecord->isInvalidDecl()) {
17080           // If we have virtual base classes, we may end up finding multiple
17081           // final overriders for a given virtual function. Check for this
17082           // problem now.
17083           if (CXXRecord->getNumVBases()) {
17084             CXXFinalOverriderMap FinalOverriders;
17085             CXXRecord->getFinalOverriders(FinalOverriders);
17086 
17087             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17088                                              MEnd = FinalOverriders.end();
17089                  M != MEnd; ++M) {
17090               for (OverridingMethods::iterator SO = M->second.begin(),
17091                                             SOEnd = M->second.end();
17092                    SO != SOEnd; ++SO) {
17093                 assert(SO->second.size() > 0 &&
17094                        "Virtual function without overriding functions?");
17095                 if (SO->second.size() == 1)
17096                   continue;
17097 
17098                 // C++ [class.virtual]p2:
17099                 //   In a derived class, if a virtual member function of a base
17100                 //   class subobject has more than one final overrider the
17101                 //   program is ill-formed.
17102                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17103                   << (const NamedDecl *)M->first << Record;
17104                 Diag(M->first->getLocation(),
17105                      diag::note_overridden_virtual_function);
17106                 for (OverridingMethods::overriding_iterator
17107                           OM = SO->second.begin(),
17108                        OMEnd = SO->second.end();
17109                      OM != OMEnd; ++OM)
17110                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17111                     << (const NamedDecl *)M->first << OM->Method->getParent();
17112 
17113                 Record->setInvalidDecl();
17114               }
17115             }
17116             CXXRecord->completeDefinition(&FinalOverriders);
17117             Completed = true;
17118           }
17119         }
17120       }
17121     }
17122 
17123     if (!Completed)
17124       Record->completeDefinition();
17125 
17126     // Handle attributes before checking the layout.
17127     ProcessDeclAttributeList(S, Record, Attrs);
17128 
17129     // We may have deferred checking for a deleted destructor. Check now.
17130     if (CXXRecord) {
17131       auto *Dtor = CXXRecord->getDestructor();
17132       if (Dtor && Dtor->isImplicit() &&
17133           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17134         CXXRecord->setImplicitDestructorIsDeleted();
17135         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17136       }
17137     }
17138 
17139     if (Record->hasAttrs()) {
17140       CheckAlignasUnderalignment(Record);
17141 
17142       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17143         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17144                                            IA->getRange(), IA->getBestCase(),
17145                                            IA->getInheritanceModel());
17146     }
17147 
17148     // Check if the structure/union declaration is a type that can have zero
17149     // size in C. For C this is a language extension, for C++ it may cause
17150     // compatibility problems.
17151     bool CheckForZeroSize;
17152     if (!getLangOpts().CPlusPlus) {
17153       CheckForZeroSize = true;
17154     } else {
17155       // For C++ filter out types that cannot be referenced in C code.
17156       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17157       CheckForZeroSize =
17158           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17159           !CXXRecord->isDependentType() &&
17160           CXXRecord->isCLike();
17161     }
17162     if (CheckForZeroSize) {
17163       bool ZeroSize = true;
17164       bool IsEmpty = true;
17165       unsigned NonBitFields = 0;
17166       for (RecordDecl::field_iterator I = Record->field_begin(),
17167                                       E = Record->field_end();
17168            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17169         IsEmpty = false;
17170         if (I->isUnnamedBitfield()) {
17171           if (!I->isZeroLengthBitField(Context))
17172             ZeroSize = false;
17173         } else {
17174           ++NonBitFields;
17175           QualType FieldType = I->getType();
17176           if (FieldType->isIncompleteType() ||
17177               !Context.getTypeSizeInChars(FieldType).isZero())
17178             ZeroSize = false;
17179         }
17180       }
17181 
17182       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17183       // allowed in C++, but warn if its declaration is inside
17184       // extern "C" block.
17185       if (ZeroSize) {
17186         Diag(RecLoc, getLangOpts().CPlusPlus ?
17187                          diag::warn_zero_size_struct_union_in_extern_c :
17188                          diag::warn_zero_size_struct_union_compat)
17189           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17190       }
17191 
17192       // Structs without named members are extension in C (C99 6.7.2.1p7),
17193       // but are accepted by GCC.
17194       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17195         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17196                                diag::ext_no_named_members_in_struct_union)
17197           << Record->isUnion();
17198       }
17199     }
17200   } else {
17201     ObjCIvarDecl **ClsFields =
17202       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17203     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17204       ID->setEndOfDefinitionLoc(RBrac);
17205       // Add ivar's to class's DeclContext.
17206       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17207         ClsFields[i]->setLexicalDeclContext(ID);
17208         ID->addDecl(ClsFields[i]);
17209       }
17210       // Must enforce the rule that ivars in the base classes may not be
17211       // duplicates.
17212       if (ID->getSuperClass())
17213         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17214     } else if (ObjCImplementationDecl *IMPDecl =
17215                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17216       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17217       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17218         // Ivar declared in @implementation never belongs to the implementation.
17219         // Only it is in implementation's lexical context.
17220         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17221       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17222       IMPDecl->setIvarLBraceLoc(LBrac);
17223       IMPDecl->setIvarRBraceLoc(RBrac);
17224     } else if (ObjCCategoryDecl *CDecl =
17225                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17226       // case of ivars in class extension; all other cases have been
17227       // reported as errors elsewhere.
17228       // FIXME. Class extension does not have a LocEnd field.
17229       // CDecl->setLocEnd(RBrac);
17230       // Add ivar's to class extension's DeclContext.
17231       // Diagnose redeclaration of private ivars.
17232       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17233       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17234         if (IDecl) {
17235           if (const ObjCIvarDecl *ClsIvar =
17236               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17237             Diag(ClsFields[i]->getLocation(),
17238                  diag::err_duplicate_ivar_declaration);
17239             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17240             continue;
17241           }
17242           for (const auto *Ext : IDecl->known_extensions()) {
17243             if (const ObjCIvarDecl *ClsExtIvar
17244                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17245               Diag(ClsFields[i]->getLocation(),
17246                    diag::err_duplicate_ivar_declaration);
17247               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17248               continue;
17249             }
17250           }
17251         }
17252         ClsFields[i]->setLexicalDeclContext(CDecl);
17253         CDecl->addDecl(ClsFields[i]);
17254       }
17255       CDecl->setIvarLBraceLoc(LBrac);
17256       CDecl->setIvarRBraceLoc(RBrac);
17257     }
17258   }
17259 }
17260 
17261 /// Determine whether the given integral value is representable within
17262 /// the given type T.
17263 static bool isRepresentableIntegerValue(ASTContext &Context,
17264                                         llvm::APSInt &Value,
17265                                         QualType T) {
17266   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17267          "Integral type required!");
17268   unsigned BitWidth = Context.getIntWidth(T);
17269 
17270   if (Value.isUnsigned() || Value.isNonNegative()) {
17271     if (T->isSignedIntegerOrEnumerationType())
17272       --BitWidth;
17273     return Value.getActiveBits() <= BitWidth;
17274   }
17275   return Value.getMinSignedBits() <= BitWidth;
17276 }
17277 
17278 // Given an integral type, return the next larger integral type
17279 // (or a NULL type of no such type exists).
17280 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17281   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17282   // enum checking below.
17283   assert((T->isIntegralType(Context) ||
17284          T->isEnumeralType()) && "Integral type required!");
17285   const unsigned NumTypes = 4;
17286   QualType SignedIntegralTypes[NumTypes] = {
17287     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17288   };
17289   QualType UnsignedIntegralTypes[NumTypes] = {
17290     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17291     Context.UnsignedLongLongTy
17292   };
17293 
17294   unsigned BitWidth = Context.getTypeSize(T);
17295   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17296                                                         : UnsignedIntegralTypes;
17297   for (unsigned I = 0; I != NumTypes; ++I)
17298     if (Context.getTypeSize(Types[I]) > BitWidth)
17299       return Types[I];
17300 
17301   return QualType();
17302 }
17303 
17304 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17305                                           EnumConstantDecl *LastEnumConst,
17306                                           SourceLocation IdLoc,
17307                                           IdentifierInfo *Id,
17308                                           Expr *Val) {
17309   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17310   llvm::APSInt EnumVal(IntWidth);
17311   QualType EltTy;
17312 
17313   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17314     Val = nullptr;
17315 
17316   if (Val)
17317     Val = DefaultLvalueConversion(Val).get();
17318 
17319   if (Val) {
17320     if (Enum->isDependentType() || Val->isTypeDependent())
17321       EltTy = Context.DependentTy;
17322     else {
17323       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17324         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17325         // constant-expression in the enumerator-definition shall be a converted
17326         // constant expression of the underlying type.
17327         EltTy = Enum->getIntegerType();
17328         ExprResult Converted =
17329           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17330                                            CCEK_Enumerator);
17331         if (Converted.isInvalid())
17332           Val = nullptr;
17333         else
17334           Val = Converted.get();
17335       } else if (!Val->isValueDependent() &&
17336                  !(Val = VerifyIntegerConstantExpression(Val,
17337                                                          &EnumVal).get())) {
17338         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17339       } else {
17340         if (Enum->isComplete()) {
17341           EltTy = Enum->getIntegerType();
17342 
17343           // In Obj-C and Microsoft mode, require the enumeration value to be
17344           // representable in the underlying type of the enumeration. In C++11,
17345           // we perform a non-narrowing conversion as part of converted constant
17346           // expression checking.
17347           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17348             if (Context.getTargetInfo()
17349                     .getTriple()
17350                     .isWindowsMSVCEnvironment()) {
17351               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17352             } else {
17353               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17354             }
17355           }
17356 
17357           // Cast to the underlying type.
17358           Val = ImpCastExprToType(Val, EltTy,
17359                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17360                                                          : CK_IntegralCast)
17361                     .get();
17362         } else if (getLangOpts().CPlusPlus) {
17363           // C++11 [dcl.enum]p5:
17364           //   If the underlying type is not fixed, the type of each enumerator
17365           //   is the type of its initializing value:
17366           //     - If an initializer is specified for an enumerator, the
17367           //       initializing value has the same type as the expression.
17368           EltTy = Val->getType();
17369         } else {
17370           // C99 6.7.2.2p2:
17371           //   The expression that defines the value of an enumeration constant
17372           //   shall be an integer constant expression that has a value
17373           //   representable as an int.
17374 
17375           // Complain if the value is not representable in an int.
17376           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17377             Diag(IdLoc, diag::ext_enum_value_not_int)
17378               << EnumVal.toString(10) << Val->getSourceRange()
17379               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17380           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17381             // Force the type of the expression to 'int'.
17382             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17383           }
17384           EltTy = Val->getType();
17385         }
17386       }
17387     }
17388   }
17389 
17390   if (!Val) {
17391     if (Enum->isDependentType())
17392       EltTy = Context.DependentTy;
17393     else if (!LastEnumConst) {
17394       // C++0x [dcl.enum]p5:
17395       //   If the underlying type is not fixed, the type of each enumerator
17396       //   is the type of its initializing value:
17397       //     - If no initializer is specified for the first enumerator, the
17398       //       initializing value has an unspecified integral type.
17399       //
17400       // GCC uses 'int' for its unspecified integral type, as does
17401       // C99 6.7.2.2p3.
17402       if (Enum->isFixed()) {
17403         EltTy = Enum->getIntegerType();
17404       }
17405       else {
17406         EltTy = Context.IntTy;
17407       }
17408     } else {
17409       // Assign the last value + 1.
17410       EnumVal = LastEnumConst->getInitVal();
17411       ++EnumVal;
17412       EltTy = LastEnumConst->getType();
17413 
17414       // Check for overflow on increment.
17415       if (EnumVal < LastEnumConst->getInitVal()) {
17416         // C++0x [dcl.enum]p5:
17417         //   If the underlying type is not fixed, the type of each enumerator
17418         //   is the type of its initializing value:
17419         //
17420         //     - Otherwise the type of the initializing value is the same as
17421         //       the type of the initializing value of the preceding enumerator
17422         //       unless the incremented value is not representable in that type,
17423         //       in which case the type is an unspecified integral type
17424         //       sufficient to contain the incremented value. If no such type
17425         //       exists, the program is ill-formed.
17426         QualType T = getNextLargerIntegralType(Context, EltTy);
17427         if (T.isNull() || Enum->isFixed()) {
17428           // There is no integral type larger enough to represent this
17429           // value. Complain, then allow the value to wrap around.
17430           EnumVal = LastEnumConst->getInitVal();
17431           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17432           ++EnumVal;
17433           if (Enum->isFixed())
17434             // When the underlying type is fixed, this is ill-formed.
17435             Diag(IdLoc, diag::err_enumerator_wrapped)
17436               << EnumVal.toString(10)
17437               << EltTy;
17438           else
17439             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17440               << EnumVal.toString(10);
17441         } else {
17442           EltTy = T;
17443         }
17444 
17445         // Retrieve the last enumerator's value, extent that type to the
17446         // type that is supposed to be large enough to represent the incremented
17447         // value, then increment.
17448         EnumVal = LastEnumConst->getInitVal();
17449         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17450         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17451         ++EnumVal;
17452 
17453         // If we're not in C++, diagnose the overflow of enumerator values,
17454         // which in C99 means that the enumerator value is not representable in
17455         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17456         // permits enumerator values that are representable in some larger
17457         // integral type.
17458         if (!getLangOpts().CPlusPlus && !T.isNull())
17459           Diag(IdLoc, diag::warn_enum_value_overflow);
17460       } else if (!getLangOpts().CPlusPlus &&
17461                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17462         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17463         Diag(IdLoc, diag::ext_enum_value_not_int)
17464           << EnumVal.toString(10) << 1;
17465       }
17466     }
17467   }
17468 
17469   if (!EltTy->isDependentType()) {
17470     // Make the enumerator value match the signedness and size of the
17471     // enumerator's type.
17472     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17473     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17474   }
17475 
17476   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17477                                   Val, EnumVal);
17478 }
17479 
17480 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17481                                                 SourceLocation IILoc) {
17482   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17483       !getLangOpts().CPlusPlus)
17484     return SkipBodyInfo();
17485 
17486   // We have an anonymous enum definition. Look up the first enumerator to
17487   // determine if we should merge the definition with an existing one and
17488   // skip the body.
17489   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17490                                          forRedeclarationInCurContext());
17491   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17492   if (!PrevECD)
17493     return SkipBodyInfo();
17494 
17495   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17496   NamedDecl *Hidden;
17497   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17498     SkipBodyInfo Skip;
17499     Skip.Previous = Hidden;
17500     return Skip;
17501   }
17502 
17503   return SkipBodyInfo();
17504 }
17505 
17506 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17507                               SourceLocation IdLoc, IdentifierInfo *Id,
17508                               const ParsedAttributesView &Attrs,
17509                               SourceLocation EqualLoc, Expr *Val) {
17510   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17511   EnumConstantDecl *LastEnumConst =
17512     cast_or_null<EnumConstantDecl>(lastEnumConst);
17513 
17514   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17515   // we find one that is.
17516   S = getNonFieldDeclScope(S);
17517 
17518   // Verify that there isn't already something declared with this name in this
17519   // scope.
17520   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17521   LookupName(R, S);
17522   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17523 
17524   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17525     // Maybe we will complain about the shadowed template parameter.
17526     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17527     // Just pretend that we didn't see the previous declaration.
17528     PrevDecl = nullptr;
17529   }
17530 
17531   // C++ [class.mem]p15:
17532   // If T is the name of a class, then each of the following shall have a name
17533   // different from T:
17534   // - every enumerator of every member of class T that is an unscoped
17535   // enumerated type
17536   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17537     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17538                             DeclarationNameInfo(Id, IdLoc));
17539 
17540   EnumConstantDecl *New =
17541     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17542   if (!New)
17543     return nullptr;
17544 
17545   if (PrevDecl) {
17546     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17547       // Check for other kinds of shadowing not already handled.
17548       CheckShadow(New, PrevDecl, R);
17549     }
17550 
17551     // When in C++, we may get a TagDecl with the same name; in this case the
17552     // enum constant will 'hide' the tag.
17553     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17554            "Received TagDecl when not in C++!");
17555     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17556       if (isa<EnumConstantDecl>(PrevDecl))
17557         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17558       else
17559         Diag(IdLoc, diag::err_redefinition) << Id;
17560       notePreviousDefinition(PrevDecl, IdLoc);
17561       return nullptr;
17562     }
17563   }
17564 
17565   // Process attributes.
17566   ProcessDeclAttributeList(S, New, Attrs);
17567   AddPragmaAttributes(S, New);
17568 
17569   // Register this decl in the current scope stack.
17570   New->setAccess(TheEnumDecl->getAccess());
17571   PushOnScopeChains(New, S);
17572 
17573   ActOnDocumentableDecl(New);
17574 
17575   return New;
17576 }
17577 
17578 // Returns true when the enum initial expression does not trigger the
17579 // duplicate enum warning.  A few common cases are exempted as follows:
17580 // Element2 = Element1
17581 // Element2 = Element1 + 1
17582 // Element2 = Element1 - 1
17583 // Where Element2 and Element1 are from the same enum.
17584 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17585   Expr *InitExpr = ECD->getInitExpr();
17586   if (!InitExpr)
17587     return true;
17588   InitExpr = InitExpr->IgnoreImpCasts();
17589 
17590   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17591     if (!BO->isAdditiveOp())
17592       return true;
17593     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17594     if (!IL)
17595       return true;
17596     if (IL->getValue() != 1)
17597       return true;
17598 
17599     InitExpr = BO->getLHS();
17600   }
17601 
17602   // This checks if the elements are from the same enum.
17603   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17604   if (!DRE)
17605     return true;
17606 
17607   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17608   if (!EnumConstant)
17609     return true;
17610 
17611   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17612       Enum)
17613     return true;
17614 
17615   return false;
17616 }
17617 
17618 // Emits a warning when an element is implicitly set a value that
17619 // a previous element has already been set to.
17620 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17621                                         EnumDecl *Enum, QualType EnumType) {
17622   // Avoid anonymous enums
17623   if (!Enum->getIdentifier())
17624     return;
17625 
17626   // Only check for small enums.
17627   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17628     return;
17629 
17630   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17631     return;
17632 
17633   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17634   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17635 
17636   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17637 
17638   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17639   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17640 
17641   // Use int64_t as a key to avoid needing special handling for map keys.
17642   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17643     llvm::APSInt Val = D->getInitVal();
17644     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17645   };
17646 
17647   DuplicatesVector DupVector;
17648   ValueToVectorMap EnumMap;
17649 
17650   // Populate the EnumMap with all values represented by enum constants without
17651   // an initializer.
17652   for (auto *Element : Elements) {
17653     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17654 
17655     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17656     // this constant.  Skip this enum since it may be ill-formed.
17657     if (!ECD) {
17658       return;
17659     }
17660 
17661     // Constants with initalizers are handled in the next loop.
17662     if (ECD->getInitExpr())
17663       continue;
17664 
17665     // Duplicate values are handled in the next loop.
17666     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17667   }
17668 
17669   if (EnumMap.size() == 0)
17670     return;
17671 
17672   // Create vectors for any values that has duplicates.
17673   for (auto *Element : Elements) {
17674     // The last loop returned if any constant was null.
17675     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17676     if (!ValidDuplicateEnum(ECD, Enum))
17677       continue;
17678 
17679     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17680     if (Iter == EnumMap.end())
17681       continue;
17682 
17683     DeclOrVector& Entry = Iter->second;
17684     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17685       // Ensure constants are different.
17686       if (D == ECD)
17687         continue;
17688 
17689       // Create new vector and push values onto it.
17690       auto Vec = std::make_unique<ECDVector>();
17691       Vec->push_back(D);
17692       Vec->push_back(ECD);
17693 
17694       // Update entry to point to the duplicates vector.
17695       Entry = Vec.get();
17696 
17697       // Store the vector somewhere we can consult later for quick emission of
17698       // diagnostics.
17699       DupVector.emplace_back(std::move(Vec));
17700       continue;
17701     }
17702 
17703     ECDVector *Vec = Entry.get<ECDVector*>();
17704     // Make sure constants are not added more than once.
17705     if (*Vec->begin() == ECD)
17706       continue;
17707 
17708     Vec->push_back(ECD);
17709   }
17710 
17711   // Emit diagnostics.
17712   for (const auto &Vec : DupVector) {
17713     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17714 
17715     // Emit warning for one enum constant.
17716     auto *FirstECD = Vec->front();
17717     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17718       << FirstECD << FirstECD->getInitVal().toString(10)
17719       << FirstECD->getSourceRange();
17720 
17721     // Emit one note for each of the remaining enum constants with
17722     // the same value.
17723     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17724       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17725         << ECD << ECD->getInitVal().toString(10)
17726         << ECD->getSourceRange();
17727   }
17728 }
17729 
17730 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17731                              bool AllowMask) const {
17732   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17733   assert(ED->isCompleteDefinition() && "expected enum definition");
17734 
17735   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17736   llvm::APInt &FlagBits = R.first->second;
17737 
17738   if (R.second) {
17739     for (auto *E : ED->enumerators()) {
17740       const auto &EVal = E->getInitVal();
17741       // Only single-bit enumerators introduce new flag values.
17742       if (EVal.isPowerOf2())
17743         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17744     }
17745   }
17746 
17747   // A value is in a flag enum if either its bits are a subset of the enum's
17748   // flag bits (the first condition) or we are allowing masks and the same is
17749   // true of its complement (the second condition). When masks are allowed, we
17750   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17751   //
17752   // While it's true that any value could be used as a mask, the assumption is
17753   // that a mask will have all of the insignificant bits set. Anything else is
17754   // likely a logic error.
17755   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17756   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17757 }
17758 
17759 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17760                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17761                          const ParsedAttributesView &Attrs) {
17762   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17763   QualType EnumType = Context.getTypeDeclType(Enum);
17764 
17765   ProcessDeclAttributeList(S, Enum, Attrs);
17766 
17767   if (Enum->isDependentType()) {
17768     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17769       EnumConstantDecl *ECD =
17770         cast_or_null<EnumConstantDecl>(Elements[i]);
17771       if (!ECD) continue;
17772 
17773       ECD->setType(EnumType);
17774     }
17775 
17776     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17777     return;
17778   }
17779 
17780   // TODO: If the result value doesn't fit in an int, it must be a long or long
17781   // long value.  ISO C does not support this, but GCC does as an extension,
17782   // emit a warning.
17783   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17784   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17785   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17786 
17787   // Verify that all the values are okay, compute the size of the values, and
17788   // reverse the list.
17789   unsigned NumNegativeBits = 0;
17790   unsigned NumPositiveBits = 0;
17791 
17792   // Keep track of whether all elements have type int.
17793   bool AllElementsInt = true;
17794 
17795   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17796     EnumConstantDecl *ECD =
17797       cast_or_null<EnumConstantDecl>(Elements[i]);
17798     if (!ECD) continue;  // Already issued a diagnostic.
17799 
17800     const llvm::APSInt &InitVal = ECD->getInitVal();
17801 
17802     // Keep track of the size of positive and negative values.
17803     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17804       NumPositiveBits = std::max(NumPositiveBits,
17805                                  (unsigned)InitVal.getActiveBits());
17806     else
17807       NumNegativeBits = std::max(NumNegativeBits,
17808                                  (unsigned)InitVal.getMinSignedBits());
17809 
17810     // Keep track of whether every enum element has type int (very common).
17811     if (AllElementsInt)
17812       AllElementsInt = ECD->getType() == Context.IntTy;
17813   }
17814 
17815   // Figure out the type that should be used for this enum.
17816   QualType BestType;
17817   unsigned BestWidth;
17818 
17819   // C++0x N3000 [conv.prom]p3:
17820   //   An rvalue of an unscoped enumeration type whose underlying
17821   //   type is not fixed can be converted to an rvalue of the first
17822   //   of the following types that can represent all the values of
17823   //   the enumeration: int, unsigned int, long int, unsigned long
17824   //   int, long long int, or unsigned long long int.
17825   // C99 6.4.4.3p2:
17826   //   An identifier declared as an enumeration constant has type int.
17827   // The C99 rule is modified by a gcc extension
17828   QualType BestPromotionType;
17829 
17830   bool Packed = Enum->hasAttr<PackedAttr>();
17831   // -fshort-enums is the equivalent to specifying the packed attribute on all
17832   // enum definitions.
17833   if (LangOpts.ShortEnums)
17834     Packed = true;
17835 
17836   // If the enum already has a type because it is fixed or dictated by the
17837   // target, promote that type instead of analyzing the enumerators.
17838   if (Enum->isComplete()) {
17839     BestType = Enum->getIntegerType();
17840     if (BestType->isPromotableIntegerType())
17841       BestPromotionType = Context.getPromotedIntegerType(BestType);
17842     else
17843       BestPromotionType = BestType;
17844 
17845     BestWidth = Context.getIntWidth(BestType);
17846   }
17847   else if (NumNegativeBits) {
17848     // If there is a negative value, figure out the smallest integer type (of
17849     // int/long/longlong) that fits.
17850     // If it's packed, check also if it fits a char or a short.
17851     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17852       BestType = Context.SignedCharTy;
17853       BestWidth = CharWidth;
17854     } else if (Packed && NumNegativeBits <= ShortWidth &&
17855                NumPositiveBits < ShortWidth) {
17856       BestType = Context.ShortTy;
17857       BestWidth = ShortWidth;
17858     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17859       BestType = Context.IntTy;
17860       BestWidth = IntWidth;
17861     } else {
17862       BestWidth = Context.getTargetInfo().getLongWidth();
17863 
17864       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17865         BestType = Context.LongTy;
17866       } else {
17867         BestWidth = Context.getTargetInfo().getLongLongWidth();
17868 
17869         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17870           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17871         BestType = Context.LongLongTy;
17872       }
17873     }
17874     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17875   } else {
17876     // If there is no negative value, figure out the smallest type that fits
17877     // all of the enumerator values.
17878     // If it's packed, check also if it fits a char or a short.
17879     if (Packed && NumPositiveBits <= CharWidth) {
17880       BestType = Context.UnsignedCharTy;
17881       BestPromotionType = Context.IntTy;
17882       BestWidth = CharWidth;
17883     } else if (Packed && NumPositiveBits <= ShortWidth) {
17884       BestType = Context.UnsignedShortTy;
17885       BestPromotionType = Context.IntTy;
17886       BestWidth = ShortWidth;
17887     } else if (NumPositiveBits <= IntWidth) {
17888       BestType = Context.UnsignedIntTy;
17889       BestWidth = IntWidth;
17890       BestPromotionType
17891         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17892                            ? Context.UnsignedIntTy : Context.IntTy;
17893     } else if (NumPositiveBits <=
17894                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17895       BestType = Context.UnsignedLongTy;
17896       BestPromotionType
17897         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17898                            ? Context.UnsignedLongTy : Context.LongTy;
17899     } else {
17900       BestWidth = Context.getTargetInfo().getLongLongWidth();
17901       assert(NumPositiveBits <= BestWidth &&
17902              "How could an initializer get larger than ULL?");
17903       BestType = Context.UnsignedLongLongTy;
17904       BestPromotionType
17905         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17906                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17907     }
17908   }
17909 
17910   // Loop over all of the enumerator constants, changing their types to match
17911   // the type of the enum if needed.
17912   for (auto *D : Elements) {
17913     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17914     if (!ECD) continue;  // Already issued a diagnostic.
17915 
17916     // Standard C says the enumerators have int type, but we allow, as an
17917     // extension, the enumerators to be larger than int size.  If each
17918     // enumerator value fits in an int, type it as an int, otherwise type it the
17919     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17920     // that X has type 'int', not 'unsigned'.
17921 
17922     // Determine whether the value fits into an int.
17923     llvm::APSInt InitVal = ECD->getInitVal();
17924 
17925     // If it fits into an integer type, force it.  Otherwise force it to match
17926     // the enum decl type.
17927     QualType NewTy;
17928     unsigned NewWidth;
17929     bool NewSign;
17930     if (!getLangOpts().CPlusPlus &&
17931         !Enum->isFixed() &&
17932         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17933       NewTy = Context.IntTy;
17934       NewWidth = IntWidth;
17935       NewSign = true;
17936     } else if (ECD->getType() == BestType) {
17937       // Already the right type!
17938       if (getLangOpts().CPlusPlus)
17939         // C++ [dcl.enum]p4: Following the closing brace of an
17940         // enum-specifier, each enumerator has the type of its
17941         // enumeration.
17942         ECD->setType(EnumType);
17943       continue;
17944     } else {
17945       NewTy = BestType;
17946       NewWidth = BestWidth;
17947       NewSign = BestType->isSignedIntegerOrEnumerationType();
17948     }
17949 
17950     // Adjust the APSInt value.
17951     InitVal = InitVal.extOrTrunc(NewWidth);
17952     InitVal.setIsSigned(NewSign);
17953     ECD->setInitVal(InitVal);
17954 
17955     // Adjust the Expr initializer and type.
17956     if (ECD->getInitExpr() &&
17957         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17958       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17959                                                 CK_IntegralCast,
17960                                                 ECD->getInitExpr(),
17961                                                 /*base paths*/ nullptr,
17962                                                 VK_RValue));
17963     if (getLangOpts().CPlusPlus)
17964       // C++ [dcl.enum]p4: Following the closing brace of an
17965       // enum-specifier, each enumerator has the type of its
17966       // enumeration.
17967       ECD->setType(EnumType);
17968     else
17969       ECD->setType(NewTy);
17970   }
17971 
17972   Enum->completeDefinition(BestType, BestPromotionType,
17973                            NumPositiveBits, NumNegativeBits);
17974 
17975   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17976 
17977   if (Enum->isClosedFlag()) {
17978     for (Decl *D : Elements) {
17979       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17980       if (!ECD) continue;  // Already issued a diagnostic.
17981 
17982       llvm::APSInt InitVal = ECD->getInitVal();
17983       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17984           !IsValueInFlagEnum(Enum, InitVal, true))
17985         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17986           << ECD << Enum;
17987     }
17988   }
17989 
17990   // Now that the enum type is defined, ensure it's not been underaligned.
17991   if (Enum->hasAttrs())
17992     CheckAlignasUnderalignment(Enum);
17993 }
17994 
17995 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17996                                   SourceLocation StartLoc,
17997                                   SourceLocation EndLoc) {
17998   StringLiteral *AsmString = cast<StringLiteral>(expr);
17999 
18000   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18001                                                    AsmString, StartLoc,
18002                                                    EndLoc);
18003   CurContext->addDecl(New);
18004   return New;
18005 }
18006 
18007 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18008                                       IdentifierInfo* AliasName,
18009                                       SourceLocation PragmaLoc,
18010                                       SourceLocation NameLoc,
18011                                       SourceLocation AliasNameLoc) {
18012   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18013                                          LookupOrdinaryName);
18014   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18015                            AttributeCommonInfo::AS_Pragma);
18016   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18017       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18018 
18019   // If a declaration that:
18020   // 1) declares a function or a variable
18021   // 2) has external linkage
18022   // already exists, add a label attribute to it.
18023   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18024     if (isDeclExternC(PrevDecl))
18025       PrevDecl->addAttr(Attr);
18026     else
18027       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18028           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18029   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18030   } else
18031     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18032 }
18033 
18034 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18035                              SourceLocation PragmaLoc,
18036                              SourceLocation NameLoc) {
18037   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18038 
18039   if (PrevDecl) {
18040     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18041   } else {
18042     (void)WeakUndeclaredIdentifiers.insert(
18043       std::pair<IdentifierInfo*,WeakInfo>
18044         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18045   }
18046 }
18047 
18048 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18049                                 IdentifierInfo* AliasName,
18050                                 SourceLocation PragmaLoc,
18051                                 SourceLocation NameLoc,
18052                                 SourceLocation AliasNameLoc) {
18053   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18054                                     LookupOrdinaryName);
18055   WeakInfo W = WeakInfo(Name, NameLoc);
18056 
18057   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18058     if (!PrevDecl->hasAttr<AliasAttr>())
18059       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18060         DeclApplyPragmaWeak(TUScope, ND, W);
18061   } else {
18062     (void)WeakUndeclaredIdentifiers.insert(
18063       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18064   }
18065 }
18066 
18067 Decl *Sema::getObjCDeclContext() const {
18068   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18069 }
18070 
18071 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18072                                                      bool Final) {
18073   // Templates are emitted when they're instantiated.
18074   if (FD->isDependentContext())
18075     return FunctionEmissionStatus::TemplateDiscarded;
18076 
18077   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18078   if (LangOpts.OpenMPIsDevice) {
18079     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18080         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18081     if (DevTy.hasValue()) {
18082       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18083         OMPES = FunctionEmissionStatus::OMPDiscarded;
18084       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18085                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18086         OMPES = FunctionEmissionStatus::Emitted;
18087       }
18088     }
18089   } else if (LangOpts.OpenMP) {
18090     // In OpenMP 4.5 all the functions are host functions.
18091     if (LangOpts.OpenMP <= 45) {
18092       OMPES = FunctionEmissionStatus::Emitted;
18093     } else {
18094       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18095           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18096       // In OpenMP 5.0 or above, DevTy may be changed later by
18097       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18098       // having no value does not imply host. The emission status will be
18099       // checked again at the end of compilation unit.
18100       if (DevTy.hasValue()) {
18101         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18102           OMPES = FunctionEmissionStatus::OMPDiscarded;
18103         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18104                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18105           OMPES = FunctionEmissionStatus::Emitted;
18106       } else if (Final)
18107         OMPES = FunctionEmissionStatus::Emitted;
18108     }
18109   }
18110   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18111       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18112     return OMPES;
18113 
18114   if (LangOpts.CUDA) {
18115     // When compiling for device, host functions are never emitted.  Similarly,
18116     // when compiling for host, device and global functions are never emitted.
18117     // (Technically, we do emit a host-side stub for global functions, but this
18118     // doesn't count for our purposes here.)
18119     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18120     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18121       return FunctionEmissionStatus::CUDADiscarded;
18122     if (!LangOpts.CUDAIsDevice &&
18123         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18124       return FunctionEmissionStatus::CUDADiscarded;
18125 
18126     // Check whether this function is externally visible -- if so, it's
18127     // known-emitted.
18128     //
18129     // We have to check the GVA linkage of the function's *definition* -- if we
18130     // only have a declaration, we don't know whether or not the function will
18131     // be emitted, because (say) the definition could include "inline".
18132     FunctionDecl *Def = FD->getDefinition();
18133 
18134     if (Def &&
18135         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18136         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18137       return FunctionEmissionStatus::Emitted;
18138   }
18139 
18140   // Otherwise, the function is known-emitted if it's in our set of
18141   // known-emitted functions.
18142   return FunctionEmissionStatus::Unknown;
18143 }
18144 
18145 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18146   // Host-side references to a __global__ function refer to the stub, so the
18147   // function itself is never emitted and therefore should not be marked.
18148   // If we have host fn calls kernel fn calls host+device, the HD function
18149   // does not get instantiated on the host. We model this by omitting at the
18150   // call to the kernel from the callgraph. This ensures that, when compiling
18151   // for host, only HD functions actually called from the host get marked as
18152   // known-emitted.
18153   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18154          IdentifyCUDATarget(Callee) == CFT_Global;
18155 }
18156