xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw___ibm128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   UsingShadowDecl *FoundUsingShadow = nullptr;
376   switch (Result.getResultKind()) {
377   case LookupResult::NotFound:
378   case LookupResult::NotFoundInCurrentInstantiation:
379     if (CorrectedII) {
380       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381                                AllowDeducedTemplate);
382       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383                                               S, SS, CCC, CTK_ErrorRecovery);
384       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385       TemplateTy Template;
386       bool MemberOfUnknownSpecialization;
387       UnqualifiedId TemplateName;
388       TemplateName.setIdentifier(NewII, NameLoc);
389       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390       CXXScopeSpec NewSS, *NewSSPtr = SS;
391       if (SS && NNS) {
392         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393         NewSSPtr = &NewSS;
394       }
395       if (Correction && (NNS || NewII != &II) &&
396           // Ignore a correction to a template type as the to-be-corrected
397           // identifier is not a template (typo correction for template names
398           // is handled elsewhere).
399           !(getLangOpts().CPlusPlus && NewSSPtr &&
400             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401                            Template, MemberOfUnknownSpecialization))) {
402         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403                                     isClassName, HasTrailingDot, ObjectTypePtr,
404                                     IsCtorOrDtorName,
405                                     WantNontrivialTypeSourceInfo,
406                                     IsClassTemplateDeductionContext);
407         if (Ty) {
408           diagnoseTypo(Correction,
409                        PDiag(diag::err_unknown_type_or_class_name_suggest)
410                          << Result.getLookupName() << isClassName);
411           if (SS && NNS)
412             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413           *CorrectedII = NewII;
414           return Ty;
415         }
416       }
417     }
418     // If typo correction failed or was not performed, fall through
419     LLVM_FALLTHROUGH;
420   case LookupResult::FoundOverloaded:
421   case LookupResult::FoundUnresolvedValue:
422     Result.suppressDiagnostics();
423     return nullptr;
424 
425   case LookupResult::Ambiguous:
426     // Recover from type-hiding ambiguities by hiding the type.  We'll
427     // do the lookup again when looking for an object, and we can
428     // diagnose the error then.  If we don't do this, then the error
429     // about hiding the type will be immediately followed by an error
430     // that only makes sense if the identifier was treated like a type.
431     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432       Result.suppressDiagnostics();
433       return nullptr;
434     }
435 
436     // Look to see if we have a type anywhere in the list of results.
437     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438          Res != ResEnd; ++Res) {
439       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441               RealRes) ||
442           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
443         if (!IIDecl ||
444             // Make the selection of the recovery decl deterministic.
445             RealRes->getLocation() < IIDecl->getLocation()) {
446           IIDecl = RealRes;
447           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448         }
449       }
450     }
451 
452     if (!IIDecl) {
453       // None of the entities we found is a type, so there is no way
454       // to even assume that the result is a type. In this case, don't
455       // complain about the ambiguity. The parser will either try to
456       // perform this lookup again (e.g., as an object name), which
457       // will produce the ambiguity, or will complain that it expected
458       // a type name.
459       Result.suppressDiagnostics();
460       return nullptr;
461     }
462 
463     // We found a type within the ambiguous lookup; diagnose the
464     // ambiguity and then return that type. This might be the right
465     // answer, or it might not be, but it suppresses any attempt to
466     // perform the name lookup again.
467     break;
468 
469   case LookupResult::Found:
470     IIDecl = Result.getFoundDecl();
471     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472     break;
473   }
474 
475   assert(IIDecl && "Didn't find decl");
476 
477   QualType T;
478   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479     // C++ [class.qual]p2: A lookup that would find the injected-class-name
480     // instead names the constructors of the class, except when naming a class.
481     // This is ill-formed when we're not actually forming a ctor or dtor name.
482     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485         FoundRD->isInjectedClassName() &&
486         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
487       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488           << &II << /*Type*/1;
489 
490     DiagnoseUseOfDecl(IIDecl, NameLoc);
491 
492     T = Context.getTypeDeclType(TD);
493     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496     if (!HasTrailingDot)
497       T = Context.getObjCInterfaceType(IDecl);
498     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500     (void)DiagnoseUseOfDecl(UD, NameLoc);
501     // Recover with 'int'
502     T = Context.IntTy;
503     FoundUsingShadow = nullptr;
504   } else if (AllowDeducedTemplate) {
505     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506       // FIXME: TemplateName should include FoundUsingShadow sugar.
507       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
508                                                        QualType(), false);
509       // Don't wrap in a further UsingType.
510       FoundUsingShadow = nullptr;
511     }
512   }
513 
514   if (T.isNull()) {
515     // If it's not plausibly a type, suppress diagnostics.
516     Result.suppressDiagnostics();
517     return nullptr;
518   }
519 
520   if (FoundUsingShadow)
521     T = Context.getUsingType(FoundUsingShadow, T);
522 
523   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524   // constructor or destructor name (in such a case, the scope specifier
525   // will be attached to the enclosing Expr or Decl node).
526   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
527       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528     if (WantNontrivialTypeSourceInfo) {
529       // Construct a type with type-source information.
530       TypeLocBuilder Builder;
531       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532 
533       T = getElaboratedType(ETK_None, *SS, T);
534       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
535       ElabTL.setElaboratedKeywordLoc(SourceLocation());
536       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538     } else {
539       T = getElaboratedType(ETK_None, *SS, T);
540     }
541   }
542 
543   return ParsedType::make(T);
544 }
545 
546 // Builds a fake NNS for the given decl context.
547 static NestedNameSpecifier *
548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
549   for (;; DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     auto *ND = dyn_cast<NamespaceDecl>(DC);
552     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
553       return NestedNameSpecifier::Create(Context, nullptr, ND);
554     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556                                          RD->getTypeForDecl());
557     else if (isa<TranslationUnitDecl>(DC))
558       return NestedNameSpecifier::GlobalSpecifier(Context);
559   }
560   llvm_unreachable("something isn't in TU scope?");
561 }
562 
563 /// Find the parent class with dependent bases of the innermost enclosing method
564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565 /// up allowing unqualified dependent type names at class-level, which MSVC
566 /// correctly rejects.
567 static const CXXRecordDecl *
568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
569   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
570     DC = DC->getPrimaryContext();
571     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572       if (MD->getParent()->hasAnyDependentBases())
573         return MD->getParent();
574   }
575   return nullptr;
576 }
577 
578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
579                                           SourceLocation NameLoc,
580                                           bool IsTemplateTypeArg) {
581   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582 
583   NestedNameSpecifier *NNS = nullptr;
584   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
585     // If we weren't able to parse a default template argument, delay lookup
586     // until instantiation time by making a non-dependent DependentTypeName. We
587     // pretend we saw a NestedNameSpecifier referring to the current scope, and
588     // lookup is retried.
589     // FIXME: This hurts our diagnostic quality, since we get errors like "no
590     // type named 'Foo' in 'current_namespace'" when the user didn't write any
591     // name specifiers.
592     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594   } else if (const CXXRecordDecl *RD =
595                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
596     // Build a DependentNameType that will perform lookup into RD at
597     // instantiation time.
598     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599                                       RD->getTypeForDecl());
600 
601     // Diagnose that this identifier was undeclared, and retry the lookup during
602     // template instantiation.
603     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604                                                                       << RD;
605   } else {
606     // This is not a situation that we should recover from.
607     return ParsedType();
608   }
609 
610   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611 
612   // Build type location information.  We synthesized the qualifier, so we have
613   // to build a fake NestedNameSpecifierLoc.
614   NestedNameSpecifierLocBuilder NNSLocBuilder;
615   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617 
618   TypeLocBuilder Builder;
619   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620   DepTL.setNameLoc(NameLoc);
621   DepTL.setElaboratedKeywordLoc(SourceLocation());
622   DepTL.setQualifierLoc(QualifierLoc);
623   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624 }
625 
626 /// isTagName() - This method is called *for error recovery purposes only*
627 /// to determine if the specified name is a valid tag name ("struct foo").  If
628 /// so, this returns the TST for the tag corresponding to it (TST_enum,
629 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
630 /// cases in C where the user forgot to specify the tag.
631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
632   // Do a tag name lookup in this scope.
633   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634   LookupName(R, S, false);
635   R.suppressDiagnostics();
636   if (R.getResultKind() == LookupResult::Found)
637     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638       switch (TD->getTagKind()) {
639       case TTK_Struct: return DeclSpec::TST_struct;
640       case TTK_Interface: return DeclSpec::TST_interface;
641       case TTK_Union:  return DeclSpec::TST_union;
642       case TTK_Class:  return DeclSpec::TST_class;
643       case TTK_Enum:   return DeclSpec::TST_enum;
644       }
645     }
646 
647   return DeclSpec::TST_unspecified;
648 }
649 
650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
652 /// then downgrade the missing typename error to a warning.
653 /// This is needed for MSVC compatibility; Example:
654 /// @code
655 /// template<class T> class A {
656 /// public:
657 ///   typedef int TYPE;
658 /// };
659 /// template<class T> class B : public A<T> {
660 /// public:
661 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
662 /// };
663 /// @endcode
664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
665   if (CurContext->isRecord()) {
666     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
667       return true;
668 
669     const Type *Ty = SS->getScopeRep()->getAsType();
670 
671     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672     for (const auto &Base : RD->bases())
673       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674         return true;
675     return S->isFunctionPrototypeScope();
676   }
677   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678 }
679 
680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
681                                    SourceLocation IILoc,
682                                    Scope *S,
683                                    CXXScopeSpec *SS,
684                                    ParsedType &SuggestedType,
685                                    bool IsTemplateName) {
686   // Don't report typename errors for editor placeholders.
687   if (II->isEditorPlaceholder())
688     return;
689   // We don't have anything to suggest (yet).
690   SuggestedType = nullptr;
691 
692   // There may have been a typo in the name of the type. Look up typo
693   // results, in case we have something that we can suggest.
694   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695                            /*AllowTemplates=*/IsTemplateName,
696                            /*AllowNonTemplates=*/!IsTemplateName);
697   if (TypoCorrection Corrected =
698           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699                       CCC, CTK_ErrorRecovery)) {
700     // FIXME: Support error recovery for the template-name case.
701     bool CanRecover = !IsTemplateName;
702     if (Corrected.isKeyword()) {
703       // We corrected to a keyword.
704       diagnoseTypo(Corrected,
705                    PDiag(IsTemplateName ? diag::err_no_template_suggest
706                                         : diag::err_unknown_typename_suggest)
707                        << II);
708       II = Corrected.getCorrectionAsIdentifierInfo();
709     } else {
710       // We found a similarly-named type or interface; suggest that.
711       if (!SS || !SS->isSet()) {
712         diagnoseTypo(Corrected,
713                      PDiag(IsTemplateName ? diag::err_no_template_suggest
714                                           : diag::err_unknown_typename_suggest)
715                          << II, CanRecover);
716       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719                                 II->getName().equals(CorrectedStr);
720         diagnoseTypo(Corrected,
721                      PDiag(IsTemplateName
722                                ? diag::err_no_member_template_suggest
723                                : diag::err_unknown_nested_typename_suggest)
724                          << II << DC << DroppedSpecifier << SS->getRange(),
725                      CanRecover);
726       } else {
727         llvm_unreachable("could not have corrected a typo here");
728       }
729 
730       if (!CanRecover)
731         return;
732 
733       CXXScopeSpec tmpSS;
734       if (Corrected.getCorrectionSpecifier())
735         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736                           SourceRange(IILoc));
737       // FIXME: Support class template argument deduction here.
738       SuggestedType =
739           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741                       /*IsCtorOrDtorName=*/false,
742                       /*WantNontrivialTypeSourceInfo=*/true);
743     }
744     return;
745   }
746 
747   if (getLangOpts().CPlusPlus && !IsTemplateName) {
748     // See if II is a class template that the user forgot to pass arguments to.
749     UnqualifiedId Name;
750     Name.setIdentifier(II, IILoc);
751     CXXScopeSpec EmptySS;
752     TemplateTy TemplateResult;
753     bool MemberOfUnknownSpecialization;
754     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755                        Name, nullptr, true, TemplateResult,
756                        MemberOfUnknownSpecialization) == TNK_Type_template) {
757       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758       return;
759     }
760   }
761 
762   // FIXME: Should we move the logic that tries to recover from a missing tag
763   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764 
765   if (!SS || (!SS->isSet() && !SS->isInvalid()))
766     Diag(IILoc, IsTemplateName ? diag::err_no_template
767                                : diag::err_unknown_typename)
768         << II;
769   else if (DeclContext *DC = computeDeclContext(*SS, false))
770     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771                                : diag::err_typename_nested_not_found)
772         << II << DC << SS->getRange();
773   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774     SuggestedType =
775         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776   } else if (isDependentScopeSpecifier(*SS)) {
777     unsigned DiagID = diag::err_typename_missing;
778     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779       DiagID = diag::ext_typename_missing;
780 
781     Diag(SS->getRange().getBegin(), DiagID)
782       << SS->getScopeRep() << II->getName()
783       << SourceRange(SS->getRange().getBegin(), IILoc)
784       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785     SuggestedType = ActOnTypenameType(S, SourceLocation(),
786                                       *SS, *II, IILoc).get();
787   } else {
788     assert(SS && SS->isInvalid() &&
789            "Invalid scope specifier has already been diagnosed");
790   }
791 }
792 
793 /// Determine whether the given result set contains either a type name
794 /// or
795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797                        NextToken.is(tok::less);
798 
799   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801       return true;
802 
803     if (CheckTemplate && isa<TemplateDecl>(*I))
804       return true;
805   }
806 
807   return false;
808 }
809 
810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811                                     Scope *S, CXXScopeSpec &SS,
812                                     IdentifierInfo *&Name,
813                                     SourceLocation NameLoc) {
814   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815   SemaRef.LookupParsedName(R, S, &SS);
816   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817     StringRef FixItTagName;
818     switch (Tag->getTagKind()) {
819       case TTK_Class:
820         FixItTagName = "class ";
821         break;
822 
823       case TTK_Enum:
824         FixItTagName = "enum ";
825         break;
826 
827       case TTK_Struct:
828         FixItTagName = "struct ";
829         break;
830 
831       case TTK_Interface:
832         FixItTagName = "__interface ";
833         break;
834 
835       case TTK_Union:
836         FixItTagName = "union ";
837         break;
838     }
839 
840     StringRef TagName = FixItTagName.drop_back();
841     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844 
845     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846          I != IEnd; ++I)
847       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848         << Name << TagName;
849 
850     // Replace lookup results with just the tag decl.
851     Result.clear(Sema::LookupTagName);
852     SemaRef.LookupParsedName(Result, S, &SS);
853     return true;
854   }
855 
856   return false;
857 }
858 
859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
860                                             IdentifierInfo *&Name,
861                                             SourceLocation NameLoc,
862                                             const Token &NextToken,
863                                             CorrectionCandidateCallback *CCC) {
864   DeclarationNameInfo NameInfo(Name, NameLoc);
865   ObjCMethodDecl *CurMethod = getCurMethodDecl();
866 
867   assert(NextToken.isNot(tok::coloncolon) &&
868          "parse nested name specifiers before calling ClassifyName");
869   if (getLangOpts().CPlusPlus && SS.isSet() &&
870       isCurrentClassName(*Name, S, &SS)) {
871     // Per [class.qual]p2, this names the constructors of SS, not the
872     // injected-class-name. We don't have a classification for that.
873     // There's not much point caching this result, since the parser
874     // will reject it later.
875     return NameClassification::Unknown();
876   }
877 
878   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879   LookupParsedName(Result, S, &SS, !CurMethod);
880 
881   if (SS.isInvalid())
882     return NameClassification::Error();
883 
884   // For unqualified lookup in a class template in MSVC mode, look into
885   // dependent base classes where the primary class template is known.
886   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887     if (ParsedType TypeInBase =
888             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889       return TypeInBase;
890   }
891 
892   // Perform lookup for Objective-C instance variables (including automatically
893   // synthesized instance variables), if we're in an Objective-C method.
894   // FIXME: This lookup really, really needs to be folded in to the normal
895   // unqualified lookup mechanism.
896   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898     if (Ivar.isInvalid())
899       return NameClassification::Error();
900     if (Ivar.isUsable())
901       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902 
903     // We defer builtin creation until after ivar lookup inside ObjC methods.
904     if (Result.empty())
905       LookupBuiltin(Result);
906   }
907 
908   bool SecondTry = false;
909   bool IsFilteredTemplateName = false;
910 
911 Corrected:
912   switch (Result.getResultKind()) {
913   case LookupResult::NotFound:
914     // If an unqualified-id is followed by a '(', then we have a function
915     // call.
916     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917       // In C++, this is an ADL-only call.
918       // FIXME: Reference?
919       if (getLangOpts().CPlusPlus)
920         return NameClassification::UndeclaredNonType();
921 
922       // C90 6.3.2.2:
923       //   If the expression that precedes the parenthesized argument list in a
924       //   function call consists solely of an identifier, and if no
925       //   declaration is visible for this identifier, the identifier is
926       //   implicitly declared exactly as if, in the innermost block containing
927       //   the function call, the declaration
928       //
929       //     extern int identifier ();
930       //
931       //   appeared.
932       //
933       // We also allow this in C99 as an extension.
934       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935         return NameClassification::NonType(D);
936     }
937 
938     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
939       // In C++20 onwards, this could be an ADL-only call to a function
940       // template, and we're required to assume that this is a template name.
941       //
942       // FIXME: Find a way to still do typo correction in this case.
943       TemplateName Template =
944           Context.getAssumedTemplateName(NameInfo.getName());
945       return NameClassification::UndeclaredTemplate(Template);
946     }
947 
948     // In C, we first see whether there is a tag type by the same name, in
949     // which case it's likely that the user just forgot to write "enum",
950     // "struct", or "union".
951     if (!getLangOpts().CPlusPlus && !SecondTry &&
952         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
953       break;
954     }
955 
956     // Perform typo correction to determine if there is another name that is
957     // close to this name.
958     if (!SecondTry && CCC) {
959       SecondTry = true;
960       if (TypoCorrection Corrected =
961               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962                           &SS, *CCC, CTK_ErrorRecovery)) {
963         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964         unsigned QualifiedDiag = diag::err_no_member_suggest;
965 
966         NamedDecl *FirstDecl = Corrected.getFoundDecl();
967         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
969             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970           UnqualifiedDiag = diag::err_no_template_suggest;
971           QualifiedDiag = diag::err_no_member_template_suggest;
972         } else if (UnderlyingFirstDecl &&
973                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
974                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976           UnqualifiedDiag = diag::err_unknown_typename_suggest;
977           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978         }
979 
980         if (SS.isEmpty()) {
981           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982         } else {// FIXME: is this even reachable? Test it.
983           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985                                   Name->getName().equals(CorrectedStr);
986           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987                                     << Name << computeDeclContext(SS, false)
988                                     << DroppedSpecifier << SS.getRange());
989         }
990 
991         // Update the name, so that the caller has the new name.
992         Name = Corrected.getCorrectionAsIdentifierInfo();
993 
994         // Typo correction corrected to a keyword.
995         if (Corrected.isKeyword())
996           return Name;
997 
998         // Also update the LookupResult...
999         // FIXME: This should probably go away at some point
1000         Result.clear();
1001         Result.setLookupName(Corrected.getCorrection());
1002         if (FirstDecl)
1003           Result.addDecl(FirstDecl);
1004 
1005         // If we found an Objective-C instance variable, let
1006         // LookupInObjCMethod build the appropriate expression to
1007         // reference the ivar.
1008         // FIXME: This is a gross hack.
1009         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010           DeclResult R =
1011               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012           if (R.isInvalid())
1013             return NameClassification::Error();
1014           if (R.isUsable())
1015             return NameClassification::NonType(Ivar);
1016         }
1017 
1018         goto Corrected;
1019       }
1020     }
1021 
1022     // We failed to correct; just fall through and let the parser deal with it.
1023     Result.suppressDiagnostics();
1024     return NameClassification::Unknown();
1025 
1026   case LookupResult::NotFoundInCurrentInstantiation: {
1027     // We performed name lookup into the current instantiation, and there were
1028     // dependent bases, so we treat this result the same way as any other
1029     // dependent nested-name-specifier.
1030 
1031     // C++ [temp.res]p2:
1032     //   A name used in a template declaration or definition and that is
1033     //   dependent on a template-parameter is assumed not to name a type
1034     //   unless the applicable name lookup finds a type name or the name is
1035     //   qualified by the keyword typename.
1036     //
1037     // FIXME: If the next token is '<', we might want to ask the parser to
1038     // perform some heroics to see if we actually have a
1039     // template-argument-list, which would indicate a missing 'template'
1040     // keyword here.
1041     return NameClassification::DependentNonType();
1042   }
1043 
1044   case LookupResult::Found:
1045   case LookupResult::FoundOverloaded:
1046   case LookupResult::FoundUnresolvedValue:
1047     break;
1048 
1049   case LookupResult::Ambiguous:
1050     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1051         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052                                       /*AllowDependent=*/false)) {
1053       // C++ [temp.local]p3:
1054       //   A lookup that finds an injected-class-name (10.2) can result in an
1055       //   ambiguity in certain cases (for example, if it is found in more than
1056       //   one base class). If all of the injected-class-names that are found
1057       //   refer to specializations of the same class template, and if the name
1058       //   is followed by a template-argument-list, the reference refers to the
1059       //   class template itself and not a specialization thereof, and is not
1060       //   ambiguous.
1061       //
1062       // This filtering can make an ambiguous result into an unambiguous one,
1063       // so try again after filtering out template names.
1064       FilterAcceptableTemplateNames(Result);
1065       if (!Result.isAmbiguous()) {
1066         IsFilteredTemplateName = true;
1067         break;
1068       }
1069     }
1070 
1071     // Diagnose the ambiguity and return an error.
1072     return NameClassification::Error();
1073   }
1074 
1075   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076       (IsFilteredTemplateName ||
1077        hasAnyAcceptableTemplateNames(
1078            Result, /*AllowFunctionTemplates=*/true,
1079            /*AllowDependent=*/false,
1080            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081                getLangOpts().CPlusPlus20))) {
1082     // C++ [temp.names]p3:
1083     //   After name lookup (3.4) finds that a name is a template-name or that
1084     //   an operator-function-id or a literal- operator-id refers to a set of
1085     //   overloaded functions any member of which is a function template if
1086     //   this is followed by a <, the < is always taken as the delimiter of a
1087     //   template-argument-list and never as the less-than operator.
1088     // C++2a [temp.names]p2:
1089     //   A name is also considered to refer to a template if it is an
1090     //   unqualified-id followed by a < and name lookup finds either one
1091     //   or more functions or finds nothing.
1092     if (!IsFilteredTemplateName)
1093       FilterAcceptableTemplateNames(Result);
1094 
1095     bool IsFunctionTemplate;
1096     bool IsVarTemplate;
1097     TemplateName Template;
1098     if (Result.end() - Result.begin() > 1) {
1099       IsFunctionTemplate = true;
1100       Template = Context.getOverloadedTemplateName(Result.begin(),
1101                                                    Result.end());
1102     } else if (!Result.empty()) {
1103       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104           *Result.begin(), /*AllowFunctionTemplates=*/true,
1105           /*AllowDependent=*/false));
1106       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107       IsVarTemplate = isa<VarTemplateDecl>(TD);
1108 
1109       if (SS.isNotEmpty())
1110         Template =
1111             Context.getQualifiedTemplateName(SS.getScopeRep(),
1112                                              /*TemplateKeyword=*/false, TD);
1113       else
1114         Template = TemplateName(TD);
1115     } else {
1116       // All results were non-template functions. This is a function template
1117       // name.
1118       IsFunctionTemplate = true;
1119       Template = Context.getAssumedTemplateName(NameInfo.getName());
1120     }
1121 
1122     if (IsFunctionTemplate) {
1123       // Function templates always go through overload resolution, at which
1124       // point we'll perform the various checks (e.g., accessibility) we need
1125       // to based on which function we selected.
1126       Result.suppressDiagnostics();
1127 
1128       return NameClassification::FunctionTemplate(Template);
1129     }
1130 
1131     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132                          : NameClassification::TypeTemplate(Template);
1133   }
1134 
1135   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136     QualType T = Context.getTypeDeclType(Type);
1137     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138       T = Context.getUsingType(USD, T);
1139 
1140     if (SS.isEmpty()) // No elaborated type, trivial location info
1141       return ParsedType::make(T);
1142 
1143     TypeLocBuilder Builder;
1144     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145     T = getElaboratedType(ETK_None, SS, T);
1146     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1147     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1148     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150   };
1151 
1152   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154     DiagnoseUseOfDecl(Type, NameLoc);
1155     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156     return BuildTypeFor(Type, *Result.begin());
1157   }
1158 
1159   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160   if (!Class) {
1161     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162     if (ObjCCompatibleAliasDecl *Alias =
1163             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164       Class = Alias->getClassInterface();
1165   }
1166 
1167   if (Class) {
1168     DiagnoseUseOfDecl(Class, NameLoc);
1169 
1170     if (NextToken.is(tok::period)) {
1171       // Interface. <something> is parsed as a property reference expression.
1172       // Just return "unknown" as a fall-through for now.
1173       Result.suppressDiagnostics();
1174       return NameClassification::Unknown();
1175     }
1176 
1177     QualType T = Context.getObjCInterfaceType(Class);
1178     return ParsedType::make(T);
1179   }
1180 
1181   if (isa<ConceptDecl>(FirstDecl))
1182     return NameClassification::Concept(
1183         TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 
1185   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187     return NameClassification::Error();
1188   }
1189 
1190   // We can have a type template here if we're classifying a template argument.
1191   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192       !isa<VarTemplateDecl>(FirstDecl))
1193     return NameClassification::TypeTemplate(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   // Check for a tag type hidden by a non-type decl in a few cases where it
1197   // seems likely a type is wanted instead of the non-type that was found.
1198   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199   if ((NextToken.is(tok::identifier) ||
1200        (NextIsOp &&
1201         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204     DiagnoseUseOfDecl(Type, NameLoc);
1205     return BuildTypeFor(Type, *Result.begin());
1206   }
1207 
1208   // If we already know which single declaration is referenced, just annotate
1209   // that declaration directly. Defer resolving even non-overloaded class
1210   // member accesses, as we need to defer certain access checks until we know
1211   // the context.
1212   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1214     return NameClassification::NonType(Result.getRepresentativeDecl());
1215 
1216   // Otherwise, this is an overload set that we will need to resolve later.
1217   Result.suppressDiagnostics();
1218   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221       Result.begin(), Result.end()));
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1226                                              SourceLocation NameLoc) {
1227   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228   CXXScopeSpec SS;
1229   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231 }
1232 
1233 ExprResult
1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1235                                             IdentifierInfo *Name,
1236                                             SourceLocation NameLoc,
1237                                             bool IsAddressOfOperand) {
1238   DeclarationNameInfo NameInfo(Name, NameLoc);
1239   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240                                     NameInfo, IsAddressOfOperand,
1241                                     /*TemplateArgs=*/nullptr);
1242 }
1243 
1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1245                                               NamedDecl *Found,
1246                                               SourceLocation NameLoc,
1247                                               const Token &NextToken) {
1248   if (getCurMethodDecl() && SS.isEmpty())
1249     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250       return BuildIvarRefExpr(S, NameLoc, Ivar);
1251 
1252   // Reconstruct the lookup result.
1253   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254   Result.addDecl(Found);
1255   Result.resolveKind();
1256 
1257   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258   return BuildDeclarationNameExpr(SS, Result, ADL);
1259 }
1260 
1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1262   // For an implicit class member access, transform the result into a member
1263   // access expression if necessary.
1264   auto *ULE = cast<UnresolvedLookupExpr>(E);
1265   if ((*ULE->decls_begin())->isCXXClassMember()) {
1266     CXXScopeSpec SS;
1267     SS.Adopt(ULE->getQualifierLoc());
1268 
1269     // Reconstruct the lookup result.
1270     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271                         LookupOrdinaryName);
1272     Result.setNamingClass(ULE->getNamingClass());
1273     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274       Result.addDecl(*I, I.getAccess());
1275     Result.resolveKind();
1276     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277                                            nullptr, S);
1278   }
1279 
1280   // Otherwise, this is already in the form we needed, and no further checks
1281   // are necessary.
1282   return ULE;
1283 }
1284 
1285 Sema::TemplateNameKindForDiagnostics
1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1287   auto *TD = Name.getAsTemplateDecl();
1288   if (!TD)
1289     return TemplateNameKindForDiagnostics::DependentTemplate;
1290   if (isa<ClassTemplateDecl>(TD))
1291     return TemplateNameKindForDiagnostics::ClassTemplate;
1292   if (isa<FunctionTemplateDecl>(TD))
1293     return TemplateNameKindForDiagnostics::FunctionTemplate;
1294   if (isa<VarTemplateDecl>(TD))
1295     return TemplateNameKindForDiagnostics::VarTemplate;
1296   if (isa<TypeAliasTemplateDecl>(TD))
1297     return TemplateNameKindForDiagnostics::AliasTemplate;
1298   if (isa<TemplateTemplateParmDecl>(TD))
1299     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300   if (isa<ConceptDecl>(TD))
1301     return TemplateNameKindForDiagnostics::Concept;
1302   return TemplateNameKindForDiagnostics::DependentTemplate;
1303 }
1304 
1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1306   assert(DC->getLexicalParent() == CurContext &&
1307       "The next DeclContext should be lexically contained in the current one.");
1308   CurContext = DC;
1309   S->setEntity(DC);
1310 }
1311 
1312 void Sema::PopDeclContext() {
1313   assert(CurContext && "DeclContext imbalance!");
1314 
1315   CurContext = CurContext->getLexicalParent();
1316   assert(CurContext && "Popped translation unit!");
1317 }
1318 
1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1320                                                                     Decl *D) {
1321   // Unlike PushDeclContext, the context to which we return is not necessarily
1322   // the containing DC of TD, because the new context will be some pre-existing
1323   // TagDecl definition instead of a fresh one.
1324   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325   CurContext = cast<TagDecl>(D)->getDefinition();
1326   assert(CurContext && "skipping definition of undefined tag");
1327   // Start lookups from the parent of the current context; we don't want to look
1328   // into the pre-existing complete definition.
1329   S->setEntity(CurContext->getLookupParent());
1330   return Result;
1331 }
1332 
1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1334   CurContext = static_cast<decltype(CurContext)>(Context);
1335 }
1336 
1337 /// EnterDeclaratorContext - Used when we must lookup names in the context
1338 /// of a declarator's nested name specifier.
1339 ///
1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1341   // C++0x [basic.lookup.unqual]p13:
1342   //   A name used in the definition of a static data member of class
1343   //   X (after the qualified-id of the static member) is looked up as
1344   //   if the name was used in a member function of X.
1345   // C++0x [basic.lookup.unqual]p14:
1346   //   If a variable member of a namespace is defined outside of the
1347   //   scope of its namespace then any name used in the definition of
1348   //   the variable member (after the declarator-id) is looked up as
1349   //   if the definition of the variable member occurred in its
1350   //   namespace.
1351   // Both of these imply that we should push a scope whose context
1352   // is the semantic context of the declaration.  We can't use
1353   // PushDeclContext here because that context is not necessarily
1354   // lexically contained in the current context.  Fortunately,
1355   // the containing scope should have the appropriate information.
1356 
1357   assert(!S->getEntity() && "scope already has entity");
1358 
1359 #ifndef NDEBUG
1360   Scope *Ancestor = S->getParent();
1361   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363 #endif
1364 
1365   CurContext = DC;
1366   S->setEntity(DC);
1367 
1368   if (S->getParent()->isTemplateParamScope()) {
1369     // Also set the corresponding entities for all immediately-enclosing
1370     // template parameter scopes.
1371     EnterTemplatedContext(S->getParent(), DC);
1372   }
1373 }
1374 
1375 void Sema::ExitDeclaratorContext(Scope *S) {
1376   assert(S->getEntity() == CurContext && "Context imbalance!");
1377 
1378   // Switch back to the lexical context.  The safety of this is
1379   // enforced by an assert in EnterDeclaratorContext.
1380   Scope *Ancestor = S->getParent();
1381   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382   CurContext = Ancestor->getEntity();
1383 
1384   // We don't need to do anything with the scope, which is going to
1385   // disappear.
1386 }
1387 
1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1389   assert(S->isTemplateParamScope() &&
1390          "expected to be initializing a template parameter scope");
1391 
1392   // C++20 [temp.local]p7:
1393   //   In the definition of a member of a class template that appears outside
1394   //   of the class template definition, the name of a member of the class
1395   //   template hides the name of a template-parameter of any enclosing class
1396   //   templates (but not a template-parameter of the member if the member is a
1397   //   class or function template).
1398   // C++20 [temp.local]p9:
1399   //   In the definition of a class template or in the definition of a member
1400   //   of such a template that appears outside of the template definition, for
1401   //   each non-dependent base class (13.8.2.1), if the name of the base class
1402   //   or the name of a member of the base class is the same as the name of a
1403   //   template-parameter, the base class name or member name hides the
1404   //   template-parameter name (6.4.10).
1405   //
1406   // This means that a template parameter scope should be searched immediately
1407   // after searching the DeclContext for which it is a template parameter
1408   // scope. For example, for
1409   //   template<typename T> template<typename U> template<typename V>
1410   //     void N::A<T>::B<U>::f(...)
1411   // we search V then B<U> (and base classes) then U then A<T> (and base
1412   // classes) then T then N then ::.
1413   unsigned ScopeDepth = getTemplateDepth(S);
1414   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415     DeclContext *SearchDCAfterScope = DC;
1416     for (; DC; DC = DC->getLookupParent()) {
1417       if (const TemplateParameterList *TPL =
1418               cast<Decl>(DC)->getDescribedTemplateParams()) {
1419         unsigned DCDepth = TPL->getDepth() + 1;
1420         if (DCDepth > ScopeDepth)
1421           continue;
1422         if (ScopeDepth == DCDepth)
1423           SearchDCAfterScope = DC = DC->getLookupParent();
1424         break;
1425       }
1426     }
1427     S->setLookupEntity(SearchDCAfterScope);
1428   }
1429 }
1430 
1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1432   // We assume that the caller has already called
1433   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434   FunctionDecl *FD = D->getAsFunction();
1435   if (!FD)
1436     return;
1437 
1438   // Same implementation as PushDeclContext, but enters the context
1439   // from the lexical parent, rather than the top-level class.
1440   assert(CurContext == FD->getLexicalParent() &&
1441     "The next DeclContext should be lexically contained in the current one.");
1442   CurContext = FD;
1443   S->setEntity(CurContext);
1444 
1445   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446     ParmVarDecl *Param = FD->getParamDecl(P);
1447     // If the parameter has an identifier, then add it to the scope
1448     if (Param->getIdentifier()) {
1449       S->AddDecl(Param);
1450       IdResolver.AddDecl(Param);
1451     }
1452   }
1453 }
1454 
1455 void Sema::ActOnExitFunctionContext() {
1456   // Same implementation as PopDeclContext, but returns to the lexical parent,
1457   // rather than the top-level class.
1458   assert(CurContext && "DeclContext imbalance!");
1459   CurContext = CurContext->getLexicalParent();
1460   assert(CurContext && "Popped translation unit!");
1461 }
1462 
1463 /// Determine whether we allow overloading of the function
1464 /// PrevDecl with another declaration.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether some new function is actually an overload. It will return
1468 /// true in C++ (where we can always provide overloads) or, as an
1469 /// extension, in C when the previous function is already an
1470 /// overloaded function declaration or has the "overloadable"
1471 /// attribute.
1472 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1473                                        ASTContext &Context,
1474                                        const FunctionDecl *New) {
1475   if (Context.getLangOpts().CPlusPlus)
1476     return true;
1477 
1478   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1479     return true;
1480 
1481   return Previous.getResultKind() == LookupResult::Found &&
1482          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1483           New->hasAttr<OverloadableAttr>());
1484 }
1485 
1486 /// Add this decl to the scope shadowed decl chains.
1487 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1488   // Move up the scope chain until we find the nearest enclosing
1489   // non-transparent context. The declaration will be introduced into this
1490   // scope.
1491   while (S->getEntity() && S->getEntity()->isTransparentContext())
1492     S = S->getParent();
1493 
1494   // Add scoped declarations into their context, so that they can be
1495   // found later. Declarations without a context won't be inserted
1496   // into any context.
1497   if (AddToContext)
1498     CurContext->addDecl(D);
1499 
1500   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1501   // are function-local declarations.
1502   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1503     return;
1504 
1505   // Template instantiations should also not be pushed into scope.
1506   if (isa<FunctionDecl>(D) &&
1507       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1508     return;
1509 
1510   // If this replaces anything in the current scope,
1511   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1512                                IEnd = IdResolver.end();
1513   for (; I != IEnd; ++I) {
1514     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1515       S->RemoveDecl(*I);
1516       IdResolver.RemoveDecl(*I);
1517 
1518       // Should only need to replace one decl.
1519       break;
1520     }
1521   }
1522 
1523   S->AddDecl(D);
1524 
1525   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1526     // Implicitly-generated labels may end up getting generated in an order that
1527     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1528     // the label at the appropriate place in the identifier chain.
1529     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1530       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1531       if (IDC == CurContext) {
1532         if (!S->isDeclScope(*I))
1533           continue;
1534       } else if (IDC->Encloses(CurContext))
1535         break;
1536     }
1537 
1538     IdResolver.InsertDeclAfter(I, D);
1539   } else {
1540     IdResolver.AddDecl(D);
1541   }
1542   warnOnReservedIdentifier(D);
1543 }
1544 
1545 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1546                          bool AllowInlineNamespace) {
1547   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1548 }
1549 
1550 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1551   DeclContext *TargetDC = DC->getPrimaryContext();
1552   do {
1553     if (DeclContext *ScopeDC = S->getEntity())
1554       if (ScopeDC->getPrimaryContext() == TargetDC)
1555         return S;
1556   } while ((S = S->getParent()));
1557 
1558   return nullptr;
1559 }
1560 
1561 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1562                                             DeclContext*,
1563                                             ASTContext&);
1564 
1565 /// Filters out lookup results that don't fall within the given scope
1566 /// as determined by isDeclInScope.
1567 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1568                                 bool ConsiderLinkage,
1569                                 bool AllowInlineNamespace) {
1570   LookupResult::Filter F = R.makeFilter();
1571   while (F.hasNext()) {
1572     NamedDecl *D = F.next();
1573 
1574     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1575       continue;
1576 
1577     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1578       continue;
1579 
1580     F.erase();
1581   }
1582 
1583   F.done();
1584 }
1585 
1586 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1587 /// have compatible owning modules.
1588 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1589   // [module.interface]p7:
1590   // A declaration is attached to a module as follows:
1591   // - If the declaration is a non-dependent friend declaration that nominates a
1592   // function with a declarator-id that is a qualified-id or template-id or that
1593   // nominates a class other than with an elaborated-type-specifier with neither
1594   // a nested-name-specifier nor a simple-template-id, it is attached to the
1595   // module to which the friend is attached ([basic.link]).
1596   if (New->getFriendObjectKind() &&
1597       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1598     New->setLocalOwningModule(Old->getOwningModule());
1599     makeMergedDefinitionVisible(New);
1600     return false;
1601   }
1602 
1603   Module *NewM = New->getOwningModule();
1604   Module *OldM = Old->getOwningModule();
1605 
1606   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1607     NewM = NewM->Parent;
1608   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1609     OldM = OldM->Parent;
1610 
1611   if (NewM == OldM)
1612     return false;
1613 
1614   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1615   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1616   if (NewIsModuleInterface || OldIsModuleInterface) {
1617     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1618     //   if a declaration of D [...] appears in the purview of a module, all
1619     //   other such declarations shall appear in the purview of the same module
1620     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1621       << New
1622       << NewIsModuleInterface
1623       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1624       << OldIsModuleInterface
1625       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1626     Diag(Old->getLocation(), diag::note_previous_declaration);
1627     New->setInvalidDecl();
1628     return true;
1629   }
1630 
1631   return false;
1632 }
1633 
1634 // [module.interface]p6:
1635 // A redeclaration of an entity X is implicitly exported if X was introduced by
1636 // an exported declaration; otherwise it shall not be exported.
1637 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1638   // [module.interface]p1:
1639   // An export-declaration shall inhabit a namespace scope.
1640   //
1641   // So it is meaningless to talk about redeclaration which is not at namespace
1642   // scope.
1643   if (!New->getLexicalDeclContext()
1644            ->getNonTransparentContext()
1645            ->isFileContext() ||
1646       !Old->getLexicalDeclContext()
1647            ->getNonTransparentContext()
1648            ->isFileContext())
1649     return false;
1650 
1651   bool IsNewExported = New->isInExportDeclContext();
1652   bool IsOldExported = Old->isInExportDeclContext();
1653 
1654   // It should be irrevelant if both of them are not exported.
1655   if (!IsNewExported && !IsOldExported)
1656     return false;
1657 
1658   if (IsOldExported)
1659     return false;
1660 
1661   assert(IsNewExported);
1662 
1663   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
1664   Diag(Old->getLocation(), diag::note_previous_declaration);
1665   return true;
1666 }
1667 
1668 // A wrapper function for checking the semantic restrictions of
1669 // a redeclaration within a module.
1670 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1671   if (CheckRedeclarationModuleOwnership(New, Old))
1672     return true;
1673 
1674   if (CheckRedeclarationExported(New, Old))
1675     return true;
1676 
1677   return false;
1678 }
1679 
1680 static bool isUsingDecl(NamedDecl *D) {
1681   return isa<UsingShadowDecl>(D) ||
1682          isa<UnresolvedUsingTypenameDecl>(D) ||
1683          isa<UnresolvedUsingValueDecl>(D);
1684 }
1685 
1686 /// Removes using shadow declarations from the lookup results.
1687 static void RemoveUsingDecls(LookupResult &R) {
1688   LookupResult::Filter F = R.makeFilter();
1689   while (F.hasNext())
1690     if (isUsingDecl(F.next()))
1691       F.erase();
1692 
1693   F.done();
1694 }
1695 
1696 /// Check for this common pattern:
1697 /// @code
1698 /// class S {
1699 ///   S(const S&); // DO NOT IMPLEMENT
1700 ///   void operator=(const S&); // DO NOT IMPLEMENT
1701 /// };
1702 /// @endcode
1703 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1704   // FIXME: Should check for private access too but access is set after we get
1705   // the decl here.
1706   if (D->doesThisDeclarationHaveABody())
1707     return false;
1708 
1709   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1710     return CD->isCopyConstructor();
1711   return D->isCopyAssignmentOperator();
1712 }
1713 
1714 // We need this to handle
1715 //
1716 // typedef struct {
1717 //   void *foo() { return 0; }
1718 // } A;
1719 //
1720 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1721 // for example. If 'A', foo will have external linkage. If we have '*A',
1722 // foo will have no linkage. Since we can't know until we get to the end
1723 // of the typedef, this function finds out if D might have non-external linkage.
1724 // Callers should verify at the end of the TU if it D has external linkage or
1725 // not.
1726 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1727   const DeclContext *DC = D->getDeclContext();
1728   while (!DC->isTranslationUnit()) {
1729     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1730       if (!RD->hasNameForLinkage())
1731         return true;
1732     }
1733     DC = DC->getParent();
1734   }
1735 
1736   return !D->isExternallyVisible();
1737 }
1738 
1739 // FIXME: This needs to be refactored; some other isInMainFile users want
1740 // these semantics.
1741 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1742   if (S.TUKind != TU_Complete)
1743     return false;
1744   return S.SourceMgr.isInMainFile(Loc);
1745 }
1746 
1747 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1748   assert(D);
1749 
1750   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1751     return false;
1752 
1753   // Ignore all entities declared within templates, and out-of-line definitions
1754   // of members of class templates.
1755   if (D->getDeclContext()->isDependentContext() ||
1756       D->getLexicalDeclContext()->isDependentContext())
1757     return false;
1758 
1759   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1760     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1761       return false;
1762     // A non-out-of-line declaration of a member specialization was implicitly
1763     // instantiated; it's the out-of-line declaration that we're interested in.
1764     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1765         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1766       return false;
1767 
1768     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1769       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1770         return false;
1771     } else {
1772       // 'static inline' functions are defined in headers; don't warn.
1773       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1774         return false;
1775     }
1776 
1777     if (FD->doesThisDeclarationHaveABody() &&
1778         Context.DeclMustBeEmitted(FD))
1779       return false;
1780   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1781     // Constants and utility variables are defined in headers with internal
1782     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1783     // like "inline".)
1784     if (!isMainFileLoc(*this, VD->getLocation()))
1785       return false;
1786 
1787     if (Context.DeclMustBeEmitted(VD))
1788       return false;
1789 
1790     if (VD->isStaticDataMember() &&
1791         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1792       return false;
1793     if (VD->isStaticDataMember() &&
1794         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1795         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1796       return false;
1797 
1798     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1799       return false;
1800   } else {
1801     return false;
1802   }
1803 
1804   // Only warn for unused decls internal to the translation unit.
1805   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1806   // for inline functions defined in the main source file, for instance.
1807   return mightHaveNonExternalLinkage(D);
1808 }
1809 
1810 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1811   if (!D)
1812     return;
1813 
1814   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1815     const FunctionDecl *First = FD->getFirstDecl();
1816     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1817       return; // First should already be in the vector.
1818   }
1819 
1820   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1821     const VarDecl *First = VD->getFirstDecl();
1822     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1823       return; // First should already be in the vector.
1824   }
1825 
1826   if (ShouldWarnIfUnusedFileScopedDecl(D))
1827     UnusedFileScopedDecls.push_back(D);
1828 }
1829 
1830 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1831   if (D->isInvalidDecl())
1832     return false;
1833 
1834   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1835     // For a decomposition declaration, warn if none of the bindings are
1836     // referenced, instead of if the variable itself is referenced (which
1837     // it is, by the bindings' expressions).
1838     for (auto *BD : DD->bindings())
1839       if (BD->isReferenced())
1840         return false;
1841   } else if (!D->getDeclName()) {
1842     return false;
1843   } else if (D->isReferenced() || D->isUsed()) {
1844     return false;
1845   }
1846 
1847   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1848     return false;
1849 
1850   if (isa<LabelDecl>(D))
1851     return true;
1852 
1853   // Except for labels, we only care about unused decls that are local to
1854   // functions.
1855   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1856   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1857     // For dependent types, the diagnostic is deferred.
1858     WithinFunction =
1859         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1860   if (!WithinFunction)
1861     return false;
1862 
1863   if (isa<TypedefNameDecl>(D))
1864     return true;
1865 
1866   // White-list anything that isn't a local variable.
1867   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1868     return false;
1869 
1870   // Types of valid local variables should be complete, so this should succeed.
1871   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1872 
1873     // White-list anything with an __attribute__((unused)) type.
1874     const auto *Ty = VD->getType().getTypePtr();
1875 
1876     // Only look at the outermost level of typedef.
1877     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1878       if (TT->getDecl()->hasAttr<UnusedAttr>())
1879         return false;
1880     }
1881 
1882     // If we failed to complete the type for some reason, or if the type is
1883     // dependent, don't diagnose the variable.
1884     if (Ty->isIncompleteType() || Ty->isDependentType())
1885       return false;
1886 
1887     // Look at the element type to ensure that the warning behaviour is
1888     // consistent for both scalars and arrays.
1889     Ty = Ty->getBaseElementTypeUnsafe();
1890 
1891     if (const TagType *TT = Ty->getAs<TagType>()) {
1892       const TagDecl *Tag = TT->getDecl();
1893       if (Tag->hasAttr<UnusedAttr>())
1894         return false;
1895 
1896       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1897         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1898           return false;
1899 
1900         if (const Expr *Init = VD->getInit()) {
1901           if (const ExprWithCleanups *Cleanups =
1902                   dyn_cast<ExprWithCleanups>(Init))
1903             Init = Cleanups->getSubExpr();
1904           const CXXConstructExpr *Construct =
1905             dyn_cast<CXXConstructExpr>(Init);
1906           if (Construct && !Construct->isElidable()) {
1907             CXXConstructorDecl *CD = Construct->getConstructor();
1908             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1909                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1910               return false;
1911           }
1912 
1913           // Suppress the warning if we don't know how this is constructed, and
1914           // it could possibly be non-trivial constructor.
1915           if (Init->isTypeDependent())
1916             for (const CXXConstructorDecl *Ctor : RD->ctors())
1917               if (!Ctor->isTrivial())
1918                 return false;
1919         }
1920       }
1921     }
1922 
1923     // TODO: __attribute__((unused)) templates?
1924   }
1925 
1926   return true;
1927 }
1928 
1929 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1930                                      FixItHint &Hint) {
1931   if (isa<LabelDecl>(D)) {
1932     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1933         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1934         true);
1935     if (AfterColon.isInvalid())
1936       return;
1937     Hint = FixItHint::CreateRemoval(
1938         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1939   }
1940 }
1941 
1942 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1943   if (D->getTypeForDecl()->isDependentType())
1944     return;
1945 
1946   for (auto *TmpD : D->decls()) {
1947     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1948       DiagnoseUnusedDecl(T);
1949     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1950       DiagnoseUnusedNestedTypedefs(R);
1951   }
1952 }
1953 
1954 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1955 /// unless they are marked attr(unused).
1956 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1957   if (!ShouldDiagnoseUnusedDecl(D))
1958     return;
1959 
1960   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1961     // typedefs can be referenced later on, so the diagnostics are emitted
1962     // at end-of-translation-unit.
1963     UnusedLocalTypedefNameCandidates.insert(TD);
1964     return;
1965   }
1966 
1967   FixItHint Hint;
1968   GenerateFixForUnusedDecl(D, Context, Hint);
1969 
1970   unsigned DiagID;
1971   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1972     DiagID = diag::warn_unused_exception_param;
1973   else if (isa<LabelDecl>(D))
1974     DiagID = diag::warn_unused_label;
1975   else
1976     DiagID = diag::warn_unused_variable;
1977 
1978   Diag(D->getLocation(), DiagID) << D << Hint;
1979 }
1980 
1981 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1982   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1983   // it's not really unused.
1984   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
1985       VD->hasAttr<CleanupAttr>())
1986     return;
1987 
1988   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1989 
1990   if (Ty->isReferenceType() || Ty->isDependentType())
1991     return;
1992 
1993   if (const TagType *TT = Ty->getAs<TagType>()) {
1994     const TagDecl *Tag = TT->getDecl();
1995     if (Tag->hasAttr<UnusedAttr>())
1996       return;
1997     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1998     // mimic gcc's behavior.
1999     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2000       if (!RD->hasAttr<WarnUnusedAttr>())
2001         return;
2002     }
2003   }
2004 
2005   // Don't warn about __block Objective-C pointer variables, as they might
2006   // be assigned in the block but not used elsewhere for the purpose of lifetime
2007   // extension.
2008   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2009     return;
2010 
2011   auto iter = RefsMinusAssignments.find(VD);
2012   if (iter == RefsMinusAssignments.end())
2013     return;
2014 
2015   assert(iter->getSecond() >= 0 &&
2016          "Found a negative number of references to a VarDecl");
2017   if (iter->getSecond() != 0)
2018     return;
2019   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2020                                          : diag::warn_unused_but_set_variable;
2021   Diag(VD->getLocation(), DiagID) << VD;
2022 }
2023 
2024 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2025   // Verify that we have no forward references left.  If so, there was a goto
2026   // or address of a label taken, but no definition of it.  Label fwd
2027   // definitions are indicated with a null substmt which is also not a resolved
2028   // MS inline assembly label name.
2029   bool Diagnose = false;
2030   if (L->isMSAsmLabel())
2031     Diagnose = !L->isResolvedMSAsmLabel();
2032   else
2033     Diagnose = L->getStmt() == nullptr;
2034   if (Diagnose)
2035     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2036 }
2037 
2038 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2039   S->mergeNRVOIntoParent();
2040 
2041   if (S->decl_empty()) return;
2042   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2043          "Scope shouldn't contain decls!");
2044 
2045   for (auto *TmpD : S->decls()) {
2046     assert(TmpD && "This decl didn't get pushed??");
2047 
2048     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2049     NamedDecl *D = cast<NamedDecl>(TmpD);
2050 
2051     // Diagnose unused variables in this scope.
2052     if (!S->hasUnrecoverableErrorOccurred()) {
2053       DiagnoseUnusedDecl(D);
2054       if (const auto *RD = dyn_cast<RecordDecl>(D))
2055         DiagnoseUnusedNestedTypedefs(RD);
2056       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2057         DiagnoseUnusedButSetDecl(VD);
2058         RefsMinusAssignments.erase(VD);
2059       }
2060     }
2061 
2062     if (!D->getDeclName()) continue;
2063 
2064     // If this was a forward reference to a label, verify it was defined.
2065     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2066       CheckPoppedLabel(LD, *this);
2067 
2068     // Remove this name from our lexical scope, and warn on it if we haven't
2069     // already.
2070     IdResolver.RemoveDecl(D);
2071     auto ShadowI = ShadowingDecls.find(D);
2072     if (ShadowI != ShadowingDecls.end()) {
2073       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2074         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2075             << D << FD << FD->getParent();
2076         Diag(FD->getLocation(), diag::note_previous_declaration);
2077       }
2078       ShadowingDecls.erase(ShadowI);
2079     }
2080   }
2081 }
2082 
2083 /// Look for an Objective-C class in the translation unit.
2084 ///
2085 /// \param Id The name of the Objective-C class we're looking for. If
2086 /// typo-correction fixes this name, the Id will be updated
2087 /// to the fixed name.
2088 ///
2089 /// \param IdLoc The location of the name in the translation unit.
2090 ///
2091 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2092 /// if there is no class with the given name.
2093 ///
2094 /// \returns The declaration of the named Objective-C class, or NULL if the
2095 /// class could not be found.
2096 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2097                                               SourceLocation IdLoc,
2098                                               bool DoTypoCorrection) {
2099   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2100   // creation from this context.
2101   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2102 
2103   if (!IDecl && DoTypoCorrection) {
2104     // Perform typo correction at the given location, but only if we
2105     // find an Objective-C class name.
2106     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2107     if (TypoCorrection C =
2108             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2109                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2110       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2111       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2112       Id = IDecl->getIdentifier();
2113     }
2114   }
2115   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2116   // This routine must always return a class definition, if any.
2117   if (Def && Def->getDefinition())
2118       Def = Def->getDefinition();
2119   return Def;
2120 }
2121 
2122 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2123 /// from S, where a non-field would be declared. This routine copes
2124 /// with the difference between C and C++ scoping rules in structs and
2125 /// unions. For example, the following code is well-formed in C but
2126 /// ill-formed in C++:
2127 /// @code
2128 /// struct S6 {
2129 ///   enum { BAR } e;
2130 /// };
2131 ///
2132 /// void test_S6() {
2133 ///   struct S6 a;
2134 ///   a.e = BAR;
2135 /// }
2136 /// @endcode
2137 /// For the declaration of BAR, this routine will return a different
2138 /// scope. The scope S will be the scope of the unnamed enumeration
2139 /// within S6. In C++, this routine will return the scope associated
2140 /// with S6, because the enumeration's scope is a transparent
2141 /// context but structures can contain non-field names. In C, this
2142 /// routine will return the translation unit scope, since the
2143 /// enumeration's scope is a transparent context and structures cannot
2144 /// contain non-field names.
2145 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2146   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2147          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2148          (S->isClassScope() && !getLangOpts().CPlusPlus))
2149     S = S->getParent();
2150   return S;
2151 }
2152 
2153 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2154                                ASTContext::GetBuiltinTypeError Error) {
2155   switch (Error) {
2156   case ASTContext::GE_None:
2157     return "";
2158   case ASTContext::GE_Missing_type:
2159     return BuiltinInfo.getHeaderName(ID);
2160   case ASTContext::GE_Missing_stdio:
2161     return "stdio.h";
2162   case ASTContext::GE_Missing_setjmp:
2163     return "setjmp.h";
2164   case ASTContext::GE_Missing_ucontext:
2165     return "ucontext.h";
2166   }
2167   llvm_unreachable("unhandled error kind");
2168 }
2169 
2170 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2171                                   unsigned ID, SourceLocation Loc) {
2172   DeclContext *Parent = Context.getTranslationUnitDecl();
2173 
2174   if (getLangOpts().CPlusPlus) {
2175     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2176         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2177     CLinkageDecl->setImplicit();
2178     Parent->addDecl(CLinkageDecl);
2179     Parent = CLinkageDecl;
2180   }
2181 
2182   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2183                                            /*TInfo=*/nullptr, SC_Extern,
2184                                            getCurFPFeatures().isFPConstrained(),
2185                                            false, Type->isFunctionProtoType());
2186   New->setImplicit();
2187   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2188 
2189   // Create Decl objects for each parameter, adding them to the
2190   // FunctionDecl.
2191   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2192     SmallVector<ParmVarDecl *, 16> Params;
2193     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2194       ParmVarDecl *parm = ParmVarDecl::Create(
2195           Context, New, SourceLocation(), SourceLocation(), nullptr,
2196           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2197       parm->setScopeInfo(0, i);
2198       Params.push_back(parm);
2199     }
2200     New->setParams(Params);
2201   }
2202 
2203   AddKnownFunctionAttributes(New);
2204   return New;
2205 }
2206 
2207 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2208 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2209 /// if we're creating this built-in in anticipation of redeclaring the
2210 /// built-in.
2211 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2212                                      Scope *S, bool ForRedeclaration,
2213                                      SourceLocation Loc) {
2214   LookupNecessaryTypesForBuiltin(S, ID);
2215 
2216   ASTContext::GetBuiltinTypeError Error;
2217   QualType R = Context.GetBuiltinType(ID, Error);
2218   if (Error) {
2219     if (!ForRedeclaration)
2220       return nullptr;
2221 
2222     // If we have a builtin without an associated type we should not emit a
2223     // warning when we were not able to find a type for it.
2224     if (Error == ASTContext::GE_Missing_type ||
2225         Context.BuiltinInfo.allowTypeMismatch(ID))
2226       return nullptr;
2227 
2228     // If we could not find a type for setjmp it is because the jmp_buf type was
2229     // not defined prior to the setjmp declaration.
2230     if (Error == ASTContext::GE_Missing_setjmp) {
2231       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2232           << Context.BuiltinInfo.getName(ID);
2233       return nullptr;
2234     }
2235 
2236     // Generally, we emit a warning that the declaration requires the
2237     // appropriate header.
2238     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2239         << getHeaderName(Context.BuiltinInfo, ID, Error)
2240         << Context.BuiltinInfo.getName(ID);
2241     return nullptr;
2242   }
2243 
2244   if (!ForRedeclaration &&
2245       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2246        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2247     Diag(Loc, diag::ext_implicit_lib_function_decl)
2248         << Context.BuiltinInfo.getName(ID) << R;
2249     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2250       Diag(Loc, diag::note_include_header_or_declare)
2251           << Header << Context.BuiltinInfo.getName(ID);
2252   }
2253 
2254   if (R.isNull())
2255     return nullptr;
2256 
2257   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2258   RegisterLocallyScopedExternCDecl(New, S);
2259 
2260   // TUScope is the translation-unit scope to insert this function into.
2261   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2262   // relate Scopes to DeclContexts, and probably eliminate CurContext
2263   // entirely, but we're not there yet.
2264   DeclContext *SavedContext = CurContext;
2265   CurContext = New->getDeclContext();
2266   PushOnScopeChains(New, TUScope);
2267   CurContext = SavedContext;
2268   return New;
2269 }
2270 
2271 /// Typedef declarations don't have linkage, but they still denote the same
2272 /// entity if their types are the same.
2273 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2274 /// isSameEntity.
2275 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2276                                                      TypedefNameDecl *Decl,
2277                                                      LookupResult &Previous) {
2278   // This is only interesting when modules are enabled.
2279   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2280     return;
2281 
2282   // Empty sets are uninteresting.
2283   if (Previous.empty())
2284     return;
2285 
2286   LookupResult::Filter Filter = Previous.makeFilter();
2287   while (Filter.hasNext()) {
2288     NamedDecl *Old = Filter.next();
2289 
2290     // Non-hidden declarations are never ignored.
2291     if (S.isVisible(Old))
2292       continue;
2293 
2294     // Declarations of the same entity are not ignored, even if they have
2295     // different linkages.
2296     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2297       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2298                                 Decl->getUnderlyingType()))
2299         continue;
2300 
2301       // If both declarations give a tag declaration a typedef name for linkage
2302       // purposes, then they declare the same entity.
2303       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2304           Decl->getAnonDeclWithTypedefName())
2305         continue;
2306     }
2307 
2308     Filter.erase();
2309   }
2310 
2311   Filter.done();
2312 }
2313 
2314 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2315   QualType OldType;
2316   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2317     OldType = OldTypedef->getUnderlyingType();
2318   else
2319     OldType = Context.getTypeDeclType(Old);
2320   QualType NewType = New->getUnderlyingType();
2321 
2322   if (NewType->isVariablyModifiedType()) {
2323     // Must not redefine a typedef with a variably-modified type.
2324     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2325     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2326       << Kind << NewType;
2327     if (Old->getLocation().isValid())
2328       notePreviousDefinition(Old, New->getLocation());
2329     New->setInvalidDecl();
2330     return true;
2331   }
2332 
2333   if (OldType != NewType &&
2334       !OldType->isDependentType() &&
2335       !NewType->isDependentType() &&
2336       !Context.hasSameType(OldType, NewType)) {
2337     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2338     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2339       << Kind << NewType << OldType;
2340     if (Old->getLocation().isValid())
2341       notePreviousDefinition(Old, New->getLocation());
2342     New->setInvalidDecl();
2343     return true;
2344   }
2345   return false;
2346 }
2347 
2348 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2349 /// same name and scope as a previous declaration 'Old'.  Figure out
2350 /// how to resolve this situation, merging decls or emitting
2351 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2352 ///
2353 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2354                                 LookupResult &OldDecls) {
2355   // If the new decl is known invalid already, don't bother doing any
2356   // merging checks.
2357   if (New->isInvalidDecl()) return;
2358 
2359   // Allow multiple definitions for ObjC built-in typedefs.
2360   // FIXME: Verify the underlying types are equivalent!
2361   if (getLangOpts().ObjC) {
2362     const IdentifierInfo *TypeID = New->getIdentifier();
2363     switch (TypeID->getLength()) {
2364     default: break;
2365     case 2:
2366       {
2367         if (!TypeID->isStr("id"))
2368           break;
2369         QualType T = New->getUnderlyingType();
2370         if (!T->isPointerType())
2371           break;
2372         if (!T->isVoidPointerType()) {
2373           QualType PT = T->castAs<PointerType>()->getPointeeType();
2374           if (!PT->isStructureType())
2375             break;
2376         }
2377         Context.setObjCIdRedefinitionType(T);
2378         // Install the built-in type for 'id', ignoring the current definition.
2379         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2380         return;
2381       }
2382     case 5:
2383       if (!TypeID->isStr("Class"))
2384         break;
2385       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2386       // Install the built-in type for 'Class', ignoring the current definition.
2387       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2388       return;
2389     case 3:
2390       if (!TypeID->isStr("SEL"))
2391         break;
2392       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2393       // Install the built-in type for 'SEL', ignoring the current definition.
2394       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2395       return;
2396     }
2397     // Fall through - the typedef name was not a builtin type.
2398   }
2399 
2400   // Verify the old decl was also a type.
2401   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2402   if (!Old) {
2403     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2404       << New->getDeclName();
2405 
2406     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2407     if (OldD->getLocation().isValid())
2408       notePreviousDefinition(OldD, New->getLocation());
2409 
2410     return New->setInvalidDecl();
2411   }
2412 
2413   // If the old declaration is invalid, just give up here.
2414   if (Old->isInvalidDecl())
2415     return New->setInvalidDecl();
2416 
2417   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2418     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2419     auto *NewTag = New->getAnonDeclWithTypedefName();
2420     NamedDecl *Hidden = nullptr;
2421     if (OldTag && NewTag &&
2422         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2423         !hasVisibleDefinition(OldTag, &Hidden)) {
2424       // There is a definition of this tag, but it is not visible. Use it
2425       // instead of our tag.
2426       New->setTypeForDecl(OldTD->getTypeForDecl());
2427       if (OldTD->isModed())
2428         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2429                                     OldTD->getUnderlyingType());
2430       else
2431         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2432 
2433       // Make the old tag definition visible.
2434       makeMergedDefinitionVisible(Hidden);
2435 
2436       // If this was an unscoped enumeration, yank all of its enumerators
2437       // out of the scope.
2438       if (isa<EnumDecl>(NewTag)) {
2439         Scope *EnumScope = getNonFieldDeclScope(S);
2440         for (auto *D : NewTag->decls()) {
2441           auto *ED = cast<EnumConstantDecl>(D);
2442           assert(EnumScope->isDeclScope(ED));
2443           EnumScope->RemoveDecl(ED);
2444           IdResolver.RemoveDecl(ED);
2445           ED->getLexicalDeclContext()->removeDecl(ED);
2446         }
2447       }
2448     }
2449   }
2450 
2451   // If the typedef types are not identical, reject them in all languages and
2452   // with any extensions enabled.
2453   if (isIncompatibleTypedef(Old, New))
2454     return;
2455 
2456   // The types match.  Link up the redeclaration chain and merge attributes if
2457   // the old declaration was a typedef.
2458   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2459     New->setPreviousDecl(Typedef);
2460     mergeDeclAttributes(New, Old);
2461   }
2462 
2463   if (getLangOpts().MicrosoftExt)
2464     return;
2465 
2466   if (getLangOpts().CPlusPlus) {
2467     // C++ [dcl.typedef]p2:
2468     //   In a given non-class scope, a typedef specifier can be used to
2469     //   redefine the name of any type declared in that scope to refer
2470     //   to the type to which it already refers.
2471     if (!isa<CXXRecordDecl>(CurContext))
2472       return;
2473 
2474     // C++0x [dcl.typedef]p4:
2475     //   In a given class scope, a typedef specifier can be used to redefine
2476     //   any class-name declared in that scope that is not also a typedef-name
2477     //   to refer to the type to which it already refers.
2478     //
2479     // This wording came in via DR424, which was a correction to the
2480     // wording in DR56, which accidentally banned code like:
2481     //
2482     //   struct S {
2483     //     typedef struct A { } A;
2484     //   };
2485     //
2486     // in the C++03 standard. We implement the C++0x semantics, which
2487     // allow the above but disallow
2488     //
2489     //   struct S {
2490     //     typedef int I;
2491     //     typedef int I;
2492     //   };
2493     //
2494     // since that was the intent of DR56.
2495     if (!isa<TypedefNameDecl>(Old))
2496       return;
2497 
2498     Diag(New->getLocation(), diag::err_redefinition)
2499       << New->getDeclName();
2500     notePreviousDefinition(Old, New->getLocation());
2501     return New->setInvalidDecl();
2502   }
2503 
2504   // Modules always permit redefinition of typedefs, as does C11.
2505   if (getLangOpts().Modules || getLangOpts().C11)
2506     return;
2507 
2508   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2509   // is normally mapped to an error, but can be controlled with
2510   // -Wtypedef-redefinition.  If either the original or the redefinition is
2511   // in a system header, don't emit this for compatibility with GCC.
2512   if (getDiagnostics().getSuppressSystemWarnings() &&
2513       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2514       (Old->isImplicit() ||
2515        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2516        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2517     return;
2518 
2519   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2520     << New->getDeclName();
2521   notePreviousDefinition(Old, New->getLocation());
2522 }
2523 
2524 /// DeclhasAttr - returns true if decl Declaration already has the target
2525 /// attribute.
2526 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2527   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2528   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2529   for (const auto *i : D->attrs())
2530     if (i->getKind() == A->getKind()) {
2531       if (Ann) {
2532         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2533           return true;
2534         continue;
2535       }
2536       // FIXME: Don't hardcode this check
2537       if (OA && isa<OwnershipAttr>(i))
2538         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2539       return true;
2540     }
2541 
2542   return false;
2543 }
2544 
2545 static bool isAttributeTargetADefinition(Decl *D) {
2546   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2547     return VD->isThisDeclarationADefinition();
2548   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2549     return TD->isCompleteDefinition() || TD->isBeingDefined();
2550   return true;
2551 }
2552 
2553 /// Merge alignment attributes from \p Old to \p New, taking into account the
2554 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2555 ///
2556 /// \return \c true if any attributes were added to \p New.
2557 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2558   // Look for alignas attributes on Old, and pick out whichever attribute
2559   // specifies the strictest alignment requirement.
2560   AlignedAttr *OldAlignasAttr = nullptr;
2561   AlignedAttr *OldStrictestAlignAttr = nullptr;
2562   unsigned OldAlign = 0;
2563   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2564     // FIXME: We have no way of representing inherited dependent alignments
2565     // in a case like:
2566     //   template<int A, int B> struct alignas(A) X;
2567     //   template<int A, int B> struct alignas(B) X {};
2568     // For now, we just ignore any alignas attributes which are not on the
2569     // definition in such a case.
2570     if (I->isAlignmentDependent())
2571       return false;
2572 
2573     if (I->isAlignas())
2574       OldAlignasAttr = I;
2575 
2576     unsigned Align = I->getAlignment(S.Context);
2577     if (Align > OldAlign) {
2578       OldAlign = Align;
2579       OldStrictestAlignAttr = I;
2580     }
2581   }
2582 
2583   // Look for alignas attributes on New.
2584   AlignedAttr *NewAlignasAttr = nullptr;
2585   unsigned NewAlign = 0;
2586   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2587     if (I->isAlignmentDependent())
2588       return false;
2589 
2590     if (I->isAlignas())
2591       NewAlignasAttr = I;
2592 
2593     unsigned Align = I->getAlignment(S.Context);
2594     if (Align > NewAlign)
2595       NewAlign = Align;
2596   }
2597 
2598   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2599     // Both declarations have 'alignas' attributes. We require them to match.
2600     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2601     // fall short. (If two declarations both have alignas, they must both match
2602     // every definition, and so must match each other if there is a definition.)
2603 
2604     // If either declaration only contains 'alignas(0)' specifiers, then it
2605     // specifies the natural alignment for the type.
2606     if (OldAlign == 0 || NewAlign == 0) {
2607       QualType Ty;
2608       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2609         Ty = VD->getType();
2610       else
2611         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2612 
2613       if (OldAlign == 0)
2614         OldAlign = S.Context.getTypeAlign(Ty);
2615       if (NewAlign == 0)
2616         NewAlign = S.Context.getTypeAlign(Ty);
2617     }
2618 
2619     if (OldAlign != NewAlign) {
2620       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2621         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2622         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2623       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2624     }
2625   }
2626 
2627   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2628     // C++11 [dcl.align]p6:
2629     //   if any declaration of an entity has an alignment-specifier,
2630     //   every defining declaration of that entity shall specify an
2631     //   equivalent alignment.
2632     // C11 6.7.5/7:
2633     //   If the definition of an object does not have an alignment
2634     //   specifier, any other declaration of that object shall also
2635     //   have no alignment specifier.
2636     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2637       << OldAlignasAttr;
2638     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2639       << OldAlignasAttr;
2640   }
2641 
2642   bool AnyAdded = false;
2643 
2644   // Ensure we have an attribute representing the strictest alignment.
2645   if (OldAlign > NewAlign) {
2646     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2647     Clone->setInherited(true);
2648     New->addAttr(Clone);
2649     AnyAdded = true;
2650   }
2651 
2652   // Ensure we have an alignas attribute if the old declaration had one.
2653   if (OldAlignasAttr && !NewAlignasAttr &&
2654       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2655     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2656     Clone->setInherited(true);
2657     New->addAttr(Clone);
2658     AnyAdded = true;
2659   }
2660 
2661   return AnyAdded;
2662 }
2663 
2664 #define WANT_DECL_MERGE_LOGIC
2665 #include "clang/Sema/AttrParsedAttrImpl.inc"
2666 #undef WANT_DECL_MERGE_LOGIC
2667 
2668 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2669                                const InheritableAttr *Attr,
2670                                Sema::AvailabilityMergeKind AMK) {
2671   // Diagnose any mutual exclusions between the attribute that we want to add
2672   // and attributes that already exist on the declaration.
2673   if (!DiagnoseMutualExclusions(S, D, Attr))
2674     return false;
2675 
2676   // This function copies an attribute Attr from a previous declaration to the
2677   // new declaration D if the new declaration doesn't itself have that attribute
2678   // yet or if that attribute allows duplicates.
2679   // If you're adding a new attribute that requires logic different from
2680   // "use explicit attribute on decl if present, else use attribute from
2681   // previous decl", for example if the attribute needs to be consistent
2682   // between redeclarations, you need to call a custom merge function here.
2683   InheritableAttr *NewAttr = nullptr;
2684   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2685     NewAttr = S.mergeAvailabilityAttr(
2686         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2687         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2688         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2689         AA->getPriority());
2690   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2691     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2692   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2693     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2694   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2695     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2696   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2697     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2698   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2699     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2700   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2701     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2702                                 FA->getFirstArg());
2703   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2704     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2705   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2706     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2707   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2708     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2709                                        IA->getInheritanceModel());
2710   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2711     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2712                                       &S.Context.Idents.get(AA->getSpelling()));
2713   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2714            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2715             isa<CUDAGlobalAttr>(Attr))) {
2716     // CUDA target attributes are part of function signature for
2717     // overloading purposes and must not be merged.
2718     return false;
2719   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2720     NewAttr = S.mergeMinSizeAttr(D, *MA);
2721   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2722     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2723   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2724     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2725   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2726     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2727   else if (isa<AlignedAttr>(Attr))
2728     // AlignedAttrs are handled separately, because we need to handle all
2729     // such attributes on a declaration at the same time.
2730     NewAttr = nullptr;
2731   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2732            (AMK == Sema::AMK_Override ||
2733             AMK == Sema::AMK_ProtocolImplementation ||
2734             AMK == Sema::AMK_OptionalProtocolImplementation))
2735     NewAttr = nullptr;
2736   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2737     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2738   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2739     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2740   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2741     NewAttr = S.mergeImportNameAttr(D, *INA);
2742   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2743     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2744   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2745     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2746   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2747     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2748   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2749     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2750 
2751   if (NewAttr) {
2752     NewAttr->setInherited(true);
2753     D->addAttr(NewAttr);
2754     if (isa<MSInheritanceAttr>(NewAttr))
2755       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2756     return true;
2757   }
2758 
2759   return false;
2760 }
2761 
2762 static const NamedDecl *getDefinition(const Decl *D) {
2763   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2764     return TD->getDefinition();
2765   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2766     const VarDecl *Def = VD->getDefinition();
2767     if (Def)
2768       return Def;
2769     return VD->getActingDefinition();
2770   }
2771   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2772     const FunctionDecl *Def = nullptr;
2773     if (FD->isDefined(Def, true))
2774       return Def;
2775   }
2776   return nullptr;
2777 }
2778 
2779 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2780   for (const auto *Attribute : D->attrs())
2781     if (Attribute->getKind() == Kind)
2782       return true;
2783   return false;
2784 }
2785 
2786 /// checkNewAttributesAfterDef - If we already have a definition, check that
2787 /// there are no new attributes in this declaration.
2788 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2789   if (!New->hasAttrs())
2790     return;
2791 
2792   const NamedDecl *Def = getDefinition(Old);
2793   if (!Def || Def == New)
2794     return;
2795 
2796   AttrVec &NewAttributes = New->getAttrs();
2797   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2798     const Attr *NewAttribute = NewAttributes[I];
2799 
2800     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2801       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2802         Sema::SkipBodyInfo SkipBody;
2803         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2804 
2805         // If we're skipping this definition, drop the "alias" attribute.
2806         if (SkipBody.ShouldSkip) {
2807           NewAttributes.erase(NewAttributes.begin() + I);
2808           --E;
2809           continue;
2810         }
2811       } else {
2812         VarDecl *VD = cast<VarDecl>(New);
2813         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2814                                 VarDecl::TentativeDefinition
2815                             ? diag::err_alias_after_tentative
2816                             : diag::err_redefinition;
2817         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2818         if (Diag == diag::err_redefinition)
2819           S.notePreviousDefinition(Def, VD->getLocation());
2820         else
2821           S.Diag(Def->getLocation(), diag::note_previous_definition);
2822         VD->setInvalidDecl();
2823       }
2824       ++I;
2825       continue;
2826     }
2827 
2828     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2829       // Tentative definitions are only interesting for the alias check above.
2830       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2831         ++I;
2832         continue;
2833       }
2834     }
2835 
2836     if (hasAttribute(Def, NewAttribute->getKind())) {
2837       ++I;
2838       continue; // regular attr merging will take care of validating this.
2839     }
2840 
2841     if (isa<C11NoReturnAttr>(NewAttribute)) {
2842       // C's _Noreturn is allowed to be added to a function after it is defined.
2843       ++I;
2844       continue;
2845     } else if (isa<UuidAttr>(NewAttribute)) {
2846       // msvc will allow a subsequent definition to add an uuid to a class
2847       ++I;
2848       continue;
2849     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2850       if (AA->isAlignas()) {
2851         // C++11 [dcl.align]p6:
2852         //   if any declaration of an entity has an alignment-specifier,
2853         //   every defining declaration of that entity shall specify an
2854         //   equivalent alignment.
2855         // C11 6.7.5/7:
2856         //   If the definition of an object does not have an alignment
2857         //   specifier, any other declaration of that object shall also
2858         //   have no alignment specifier.
2859         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2860           << AA;
2861         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2862           << AA;
2863         NewAttributes.erase(NewAttributes.begin() + I);
2864         --E;
2865         continue;
2866       }
2867     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2868       // If there is a C definition followed by a redeclaration with this
2869       // attribute then there are two different definitions. In C++, prefer the
2870       // standard diagnostics.
2871       if (!S.getLangOpts().CPlusPlus) {
2872         S.Diag(NewAttribute->getLocation(),
2873                diag::err_loader_uninitialized_redeclaration);
2874         S.Diag(Def->getLocation(), diag::note_previous_definition);
2875         NewAttributes.erase(NewAttributes.begin() + I);
2876         --E;
2877         continue;
2878       }
2879     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2880                cast<VarDecl>(New)->isInline() &&
2881                !cast<VarDecl>(New)->isInlineSpecified()) {
2882       // Don't warn about applying selectany to implicitly inline variables.
2883       // Older compilers and language modes would require the use of selectany
2884       // to make such variables inline, and it would have no effect if we
2885       // honored it.
2886       ++I;
2887       continue;
2888     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2889       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2890       // declarations after defintions.
2891       ++I;
2892       continue;
2893     }
2894 
2895     S.Diag(NewAttribute->getLocation(),
2896            diag::warn_attribute_precede_definition);
2897     S.Diag(Def->getLocation(), diag::note_previous_definition);
2898     NewAttributes.erase(NewAttributes.begin() + I);
2899     --E;
2900   }
2901 }
2902 
2903 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2904                                      const ConstInitAttr *CIAttr,
2905                                      bool AttrBeforeInit) {
2906   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2907 
2908   // Figure out a good way to write this specifier on the old declaration.
2909   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2910   // enough of the attribute list spelling information to extract that without
2911   // heroics.
2912   std::string SuitableSpelling;
2913   if (S.getLangOpts().CPlusPlus20)
2914     SuitableSpelling = std::string(
2915         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2916   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2917     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2918         InsertLoc, {tok::l_square, tok::l_square,
2919                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2920                     S.PP.getIdentifierInfo("require_constant_initialization"),
2921                     tok::r_square, tok::r_square}));
2922   if (SuitableSpelling.empty())
2923     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2924         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2925                     S.PP.getIdentifierInfo("require_constant_initialization"),
2926                     tok::r_paren, tok::r_paren}));
2927   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2928     SuitableSpelling = "constinit";
2929   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2930     SuitableSpelling = "[[clang::require_constant_initialization]]";
2931   if (SuitableSpelling.empty())
2932     SuitableSpelling = "__attribute__((require_constant_initialization))";
2933   SuitableSpelling += " ";
2934 
2935   if (AttrBeforeInit) {
2936     // extern constinit int a;
2937     // int a = 0; // error (missing 'constinit'), accepted as extension
2938     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2939     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2940         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2941     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2942   } else {
2943     // int a = 0;
2944     // constinit extern int a; // error (missing 'constinit')
2945     S.Diag(CIAttr->getLocation(),
2946            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2947                                  : diag::warn_require_const_init_added_too_late)
2948         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2949     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2950         << CIAttr->isConstinit()
2951         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2952   }
2953 }
2954 
2955 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2956 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2957                                AvailabilityMergeKind AMK) {
2958   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2959     UsedAttr *NewAttr = OldAttr->clone(Context);
2960     NewAttr->setInherited(true);
2961     New->addAttr(NewAttr);
2962   }
2963   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2964     RetainAttr *NewAttr = OldAttr->clone(Context);
2965     NewAttr->setInherited(true);
2966     New->addAttr(NewAttr);
2967   }
2968 
2969   if (!Old->hasAttrs() && !New->hasAttrs())
2970     return;
2971 
2972   // [dcl.constinit]p1:
2973   //   If the [constinit] specifier is applied to any declaration of a
2974   //   variable, it shall be applied to the initializing declaration.
2975   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2976   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2977   if (bool(OldConstInit) != bool(NewConstInit)) {
2978     const auto *OldVD = cast<VarDecl>(Old);
2979     auto *NewVD = cast<VarDecl>(New);
2980 
2981     // Find the initializing declaration. Note that we might not have linked
2982     // the new declaration into the redeclaration chain yet.
2983     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2984     if (!InitDecl &&
2985         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2986       InitDecl = NewVD;
2987 
2988     if (InitDecl == NewVD) {
2989       // This is the initializing declaration. If it would inherit 'constinit',
2990       // that's ill-formed. (Note that we do not apply this to the attribute
2991       // form).
2992       if (OldConstInit && OldConstInit->isConstinit())
2993         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2994                                  /*AttrBeforeInit=*/true);
2995     } else if (NewConstInit) {
2996       // This is the first time we've been told that this declaration should
2997       // have a constant initializer. If we already saw the initializing
2998       // declaration, this is too late.
2999       if (InitDecl && InitDecl != NewVD) {
3000         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3001                                  /*AttrBeforeInit=*/false);
3002         NewVD->dropAttr<ConstInitAttr>();
3003       }
3004     }
3005   }
3006 
3007   // Attributes declared post-definition are currently ignored.
3008   checkNewAttributesAfterDef(*this, New, Old);
3009 
3010   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3011     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3012       if (!OldA->isEquivalent(NewA)) {
3013         // This redeclaration changes __asm__ label.
3014         Diag(New->getLocation(), diag::err_different_asm_label);
3015         Diag(OldA->getLocation(), diag::note_previous_declaration);
3016       }
3017     } else if (Old->isUsed()) {
3018       // This redeclaration adds an __asm__ label to a declaration that has
3019       // already been ODR-used.
3020       Diag(New->getLocation(), diag::err_late_asm_label_name)
3021         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3022     }
3023   }
3024 
3025   // Re-declaration cannot add abi_tag's.
3026   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3027     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3028       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3029         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3030           Diag(NewAbiTagAttr->getLocation(),
3031                diag::err_new_abi_tag_on_redeclaration)
3032               << NewTag;
3033           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3034         }
3035       }
3036     } else {
3037       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3038       Diag(Old->getLocation(), diag::note_previous_declaration);
3039     }
3040   }
3041 
3042   // This redeclaration adds a section attribute.
3043   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3044     if (auto *VD = dyn_cast<VarDecl>(New)) {
3045       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3046         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3047         Diag(Old->getLocation(), diag::note_previous_declaration);
3048       }
3049     }
3050   }
3051 
3052   // Redeclaration adds code-seg attribute.
3053   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3054   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3055       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3056     Diag(New->getLocation(), diag::warn_mismatched_section)
3057          << 0 /*codeseg*/;
3058     Diag(Old->getLocation(), diag::note_previous_declaration);
3059   }
3060 
3061   if (!Old->hasAttrs())
3062     return;
3063 
3064   bool foundAny = New->hasAttrs();
3065 
3066   // Ensure that any moving of objects within the allocated map is done before
3067   // we process them.
3068   if (!foundAny) New->setAttrs(AttrVec());
3069 
3070   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3071     // Ignore deprecated/unavailable/availability attributes if requested.
3072     AvailabilityMergeKind LocalAMK = AMK_None;
3073     if (isa<DeprecatedAttr>(I) ||
3074         isa<UnavailableAttr>(I) ||
3075         isa<AvailabilityAttr>(I)) {
3076       switch (AMK) {
3077       case AMK_None:
3078         continue;
3079 
3080       case AMK_Redeclaration:
3081       case AMK_Override:
3082       case AMK_ProtocolImplementation:
3083       case AMK_OptionalProtocolImplementation:
3084         LocalAMK = AMK;
3085         break;
3086       }
3087     }
3088 
3089     // Already handled.
3090     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3091       continue;
3092 
3093     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3094       foundAny = true;
3095   }
3096 
3097   if (mergeAlignedAttrs(*this, New, Old))
3098     foundAny = true;
3099 
3100   if (!foundAny) New->dropAttrs();
3101 }
3102 
3103 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3104 /// to the new one.
3105 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3106                                      const ParmVarDecl *oldDecl,
3107                                      Sema &S) {
3108   // C++11 [dcl.attr.depend]p2:
3109   //   The first declaration of a function shall specify the
3110   //   carries_dependency attribute for its declarator-id if any declaration
3111   //   of the function specifies the carries_dependency attribute.
3112   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3113   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3114     S.Diag(CDA->getLocation(),
3115            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3116     // Find the first declaration of the parameter.
3117     // FIXME: Should we build redeclaration chains for function parameters?
3118     const FunctionDecl *FirstFD =
3119       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3120     const ParmVarDecl *FirstVD =
3121       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3122     S.Diag(FirstVD->getLocation(),
3123            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3124   }
3125 
3126   if (!oldDecl->hasAttrs())
3127     return;
3128 
3129   bool foundAny = newDecl->hasAttrs();
3130 
3131   // Ensure that any moving of objects within the allocated map is
3132   // done before we process them.
3133   if (!foundAny) newDecl->setAttrs(AttrVec());
3134 
3135   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3136     if (!DeclHasAttr(newDecl, I)) {
3137       InheritableAttr *newAttr =
3138         cast<InheritableParamAttr>(I->clone(S.Context));
3139       newAttr->setInherited(true);
3140       newDecl->addAttr(newAttr);
3141       foundAny = true;
3142     }
3143   }
3144 
3145   if (!foundAny) newDecl->dropAttrs();
3146 }
3147 
3148 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3149                                 const ParmVarDecl *OldParam,
3150                                 Sema &S) {
3151   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3152     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3153       if (*Oldnullability != *Newnullability) {
3154         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3155           << DiagNullabilityKind(
3156                *Newnullability,
3157                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3158                 != 0))
3159           << DiagNullabilityKind(
3160                *Oldnullability,
3161                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3162                 != 0));
3163         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3164       }
3165     } else {
3166       QualType NewT = NewParam->getType();
3167       NewT = S.Context.getAttributedType(
3168                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3169                          NewT, NewT);
3170       NewParam->setType(NewT);
3171     }
3172   }
3173 }
3174 
3175 namespace {
3176 
3177 /// Used in MergeFunctionDecl to keep track of function parameters in
3178 /// C.
3179 struct GNUCompatibleParamWarning {
3180   ParmVarDecl *OldParm;
3181   ParmVarDecl *NewParm;
3182   QualType PromotedType;
3183 };
3184 
3185 } // end anonymous namespace
3186 
3187 // Determine whether the previous declaration was a definition, implicit
3188 // declaration, or a declaration.
3189 template <typename T>
3190 static std::pair<diag::kind, SourceLocation>
3191 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3192   diag::kind PrevDiag;
3193   SourceLocation OldLocation = Old->getLocation();
3194   if (Old->isThisDeclarationADefinition())
3195     PrevDiag = diag::note_previous_definition;
3196   else if (Old->isImplicit()) {
3197     PrevDiag = diag::note_previous_implicit_declaration;
3198     if (OldLocation.isInvalid())
3199       OldLocation = New->getLocation();
3200   } else
3201     PrevDiag = diag::note_previous_declaration;
3202   return std::make_pair(PrevDiag, OldLocation);
3203 }
3204 
3205 /// canRedefineFunction - checks if a function can be redefined. Currently,
3206 /// only extern inline functions can be redefined, and even then only in
3207 /// GNU89 mode.
3208 static bool canRedefineFunction(const FunctionDecl *FD,
3209                                 const LangOptions& LangOpts) {
3210   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3211           !LangOpts.CPlusPlus &&
3212           FD->isInlineSpecified() &&
3213           FD->getStorageClass() == SC_Extern);
3214 }
3215 
3216 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3217   const AttributedType *AT = T->getAs<AttributedType>();
3218   while (AT && !AT->isCallingConv())
3219     AT = AT->getModifiedType()->getAs<AttributedType>();
3220   return AT;
3221 }
3222 
3223 template <typename T>
3224 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3225   const DeclContext *DC = Old->getDeclContext();
3226   if (DC->isRecord())
3227     return false;
3228 
3229   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3230   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3231     return true;
3232   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3233     return true;
3234   return false;
3235 }
3236 
3237 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3238 static bool isExternC(VarTemplateDecl *) { return false; }
3239 static bool isExternC(FunctionTemplateDecl *) { return false; }
3240 
3241 /// Check whether a redeclaration of an entity introduced by a
3242 /// using-declaration is valid, given that we know it's not an overload
3243 /// (nor a hidden tag declaration).
3244 template<typename ExpectedDecl>
3245 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3246                                    ExpectedDecl *New) {
3247   // C++11 [basic.scope.declarative]p4:
3248   //   Given a set of declarations in a single declarative region, each of
3249   //   which specifies the same unqualified name,
3250   //   -- they shall all refer to the same entity, or all refer to functions
3251   //      and function templates; or
3252   //   -- exactly one declaration shall declare a class name or enumeration
3253   //      name that is not a typedef name and the other declarations shall all
3254   //      refer to the same variable or enumerator, or all refer to functions
3255   //      and function templates; in this case the class name or enumeration
3256   //      name is hidden (3.3.10).
3257 
3258   // C++11 [namespace.udecl]p14:
3259   //   If a function declaration in namespace scope or block scope has the
3260   //   same name and the same parameter-type-list as a function introduced
3261   //   by a using-declaration, and the declarations do not declare the same
3262   //   function, the program is ill-formed.
3263 
3264   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3265   if (Old &&
3266       !Old->getDeclContext()->getRedeclContext()->Equals(
3267           New->getDeclContext()->getRedeclContext()) &&
3268       !(isExternC(Old) && isExternC(New)))
3269     Old = nullptr;
3270 
3271   if (!Old) {
3272     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3273     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3274     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3275     return true;
3276   }
3277   return false;
3278 }
3279 
3280 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3281                                             const FunctionDecl *B) {
3282   assert(A->getNumParams() == B->getNumParams());
3283 
3284   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3285     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3286     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3287     if (AttrA == AttrB)
3288       return true;
3289     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3290            AttrA->isDynamic() == AttrB->isDynamic();
3291   };
3292 
3293   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3294 }
3295 
3296 /// If necessary, adjust the semantic declaration context for a qualified
3297 /// declaration to name the correct inline namespace within the qualifier.
3298 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3299                                                DeclaratorDecl *OldD) {
3300   // The only case where we need to update the DeclContext is when
3301   // redeclaration lookup for a qualified name finds a declaration
3302   // in an inline namespace within the context named by the qualifier:
3303   //
3304   //   inline namespace N { int f(); }
3305   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3306   //
3307   // For unqualified declarations, the semantic context *can* change
3308   // along the redeclaration chain (for local extern declarations,
3309   // extern "C" declarations, and friend declarations in particular).
3310   if (!NewD->getQualifier())
3311     return;
3312 
3313   // NewD is probably already in the right context.
3314   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3315   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3316   if (NamedDC->Equals(SemaDC))
3317     return;
3318 
3319   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3320           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3321          "unexpected context for redeclaration");
3322 
3323   auto *LexDC = NewD->getLexicalDeclContext();
3324   auto FixSemaDC = [=](NamedDecl *D) {
3325     if (!D)
3326       return;
3327     D->setDeclContext(SemaDC);
3328     D->setLexicalDeclContext(LexDC);
3329   };
3330 
3331   FixSemaDC(NewD);
3332   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3333     FixSemaDC(FD->getDescribedFunctionTemplate());
3334   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3335     FixSemaDC(VD->getDescribedVarTemplate());
3336 }
3337 
3338 /// MergeFunctionDecl - We just parsed a function 'New' from
3339 /// declarator D which has the same name and scope as a previous
3340 /// declaration 'Old'.  Figure out how to resolve this situation,
3341 /// merging decls or emitting diagnostics as appropriate.
3342 ///
3343 /// In C++, New and Old must be declarations that are not
3344 /// overloaded. Use IsOverload to determine whether New and Old are
3345 /// overloaded, and to select the Old declaration that New should be
3346 /// merged with.
3347 ///
3348 /// Returns true if there was an error, false otherwise.
3349 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3350                              Scope *S, bool MergeTypeWithOld) {
3351   // Verify the old decl was also a function.
3352   FunctionDecl *Old = OldD->getAsFunction();
3353   if (!Old) {
3354     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3355       if (New->getFriendObjectKind()) {
3356         Diag(New->getLocation(), diag::err_using_decl_friend);
3357         Diag(Shadow->getTargetDecl()->getLocation(),
3358              diag::note_using_decl_target);
3359         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3360             << 0;
3361         return true;
3362       }
3363 
3364       // Check whether the two declarations might declare the same function or
3365       // function template.
3366       if (FunctionTemplateDecl *NewTemplate =
3367               New->getDescribedFunctionTemplate()) {
3368         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3369                                                          NewTemplate))
3370           return true;
3371         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3372                          ->getAsFunction();
3373       } else {
3374         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3375           return true;
3376         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3377       }
3378     } else {
3379       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3380         << New->getDeclName();
3381       notePreviousDefinition(OldD, New->getLocation());
3382       return true;
3383     }
3384   }
3385 
3386   // If the old declaration was found in an inline namespace and the new
3387   // declaration was qualified, update the DeclContext to match.
3388   adjustDeclContextForDeclaratorDecl(New, Old);
3389 
3390   // If the old declaration is invalid, just give up here.
3391   if (Old->isInvalidDecl())
3392     return true;
3393 
3394   // Disallow redeclaration of some builtins.
3395   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3396     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3397     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3398         << Old << Old->getType();
3399     return true;
3400   }
3401 
3402   diag::kind PrevDiag;
3403   SourceLocation OldLocation;
3404   std::tie(PrevDiag, OldLocation) =
3405       getNoteDiagForInvalidRedeclaration(Old, New);
3406 
3407   // Don't complain about this if we're in GNU89 mode and the old function
3408   // is an extern inline function.
3409   // Don't complain about specializations. They are not supposed to have
3410   // storage classes.
3411   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3412       New->getStorageClass() == SC_Static &&
3413       Old->hasExternalFormalLinkage() &&
3414       !New->getTemplateSpecializationInfo() &&
3415       !canRedefineFunction(Old, getLangOpts())) {
3416     if (getLangOpts().MicrosoftExt) {
3417       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3418       Diag(OldLocation, PrevDiag);
3419     } else {
3420       Diag(New->getLocation(), diag::err_static_non_static) << New;
3421       Diag(OldLocation, PrevDiag);
3422       return true;
3423     }
3424   }
3425 
3426   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3427     if (!Old->hasAttr<InternalLinkageAttr>()) {
3428       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3429           << ILA;
3430       Diag(Old->getLocation(), diag::note_previous_declaration);
3431       New->dropAttr<InternalLinkageAttr>();
3432     }
3433 
3434   if (auto *EA = New->getAttr<ErrorAttr>()) {
3435     if (!Old->hasAttr<ErrorAttr>()) {
3436       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3437       Diag(Old->getLocation(), diag::note_previous_declaration);
3438       New->dropAttr<ErrorAttr>();
3439     }
3440   }
3441 
3442   if (CheckRedeclarationInModule(New, Old))
3443     return true;
3444 
3445   if (!getLangOpts().CPlusPlus) {
3446     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3447     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3448       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3449         << New << OldOvl;
3450 
3451       // Try our best to find a decl that actually has the overloadable
3452       // attribute for the note. In most cases (e.g. programs with only one
3453       // broken declaration/definition), this won't matter.
3454       //
3455       // FIXME: We could do this if we juggled some extra state in
3456       // OverloadableAttr, rather than just removing it.
3457       const Decl *DiagOld = Old;
3458       if (OldOvl) {
3459         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3460           const auto *A = D->getAttr<OverloadableAttr>();
3461           return A && !A->isImplicit();
3462         });
3463         // If we've implicitly added *all* of the overloadable attrs to this
3464         // chain, emitting a "previous redecl" note is pointless.
3465         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3466       }
3467 
3468       if (DiagOld)
3469         Diag(DiagOld->getLocation(),
3470              diag::note_attribute_overloadable_prev_overload)
3471           << OldOvl;
3472 
3473       if (OldOvl)
3474         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3475       else
3476         New->dropAttr<OverloadableAttr>();
3477     }
3478   }
3479 
3480   // If a function is first declared with a calling convention, but is later
3481   // declared or defined without one, all following decls assume the calling
3482   // convention of the first.
3483   //
3484   // It's OK if a function is first declared without a calling convention,
3485   // but is later declared or defined with the default calling convention.
3486   //
3487   // To test if either decl has an explicit calling convention, we look for
3488   // AttributedType sugar nodes on the type as written.  If they are missing or
3489   // were canonicalized away, we assume the calling convention was implicit.
3490   //
3491   // Note also that we DO NOT return at this point, because we still have
3492   // other tests to run.
3493   QualType OldQType = Context.getCanonicalType(Old->getType());
3494   QualType NewQType = Context.getCanonicalType(New->getType());
3495   const FunctionType *OldType = cast<FunctionType>(OldQType);
3496   const FunctionType *NewType = cast<FunctionType>(NewQType);
3497   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3498   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3499   bool RequiresAdjustment = false;
3500 
3501   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3502     FunctionDecl *First = Old->getFirstDecl();
3503     const FunctionType *FT =
3504         First->getType().getCanonicalType()->castAs<FunctionType>();
3505     FunctionType::ExtInfo FI = FT->getExtInfo();
3506     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3507     if (!NewCCExplicit) {
3508       // Inherit the CC from the previous declaration if it was specified
3509       // there but not here.
3510       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3511       RequiresAdjustment = true;
3512     } else if (Old->getBuiltinID()) {
3513       // Builtin attribute isn't propagated to the new one yet at this point,
3514       // so we check if the old one is a builtin.
3515 
3516       // Calling Conventions on a Builtin aren't really useful and setting a
3517       // default calling convention and cdecl'ing some builtin redeclarations is
3518       // common, so warn and ignore the calling convention on the redeclaration.
3519       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3520           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3521           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3522       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3523       RequiresAdjustment = true;
3524     } else {
3525       // Calling conventions aren't compatible, so complain.
3526       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3527       Diag(New->getLocation(), diag::err_cconv_change)
3528         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3529         << !FirstCCExplicit
3530         << (!FirstCCExplicit ? "" :
3531             FunctionType::getNameForCallConv(FI.getCC()));
3532 
3533       // Put the note on the first decl, since it is the one that matters.
3534       Diag(First->getLocation(), diag::note_previous_declaration);
3535       return true;
3536     }
3537   }
3538 
3539   // FIXME: diagnose the other way around?
3540   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3541     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3542     RequiresAdjustment = true;
3543   }
3544 
3545   // Merge regparm attribute.
3546   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3547       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3548     if (NewTypeInfo.getHasRegParm()) {
3549       Diag(New->getLocation(), diag::err_regparm_mismatch)
3550         << NewType->getRegParmType()
3551         << OldType->getRegParmType();
3552       Diag(OldLocation, diag::note_previous_declaration);
3553       return true;
3554     }
3555 
3556     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3557     RequiresAdjustment = true;
3558   }
3559 
3560   // Merge ns_returns_retained attribute.
3561   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3562     if (NewTypeInfo.getProducesResult()) {
3563       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3564           << "'ns_returns_retained'";
3565       Diag(OldLocation, diag::note_previous_declaration);
3566       return true;
3567     }
3568 
3569     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3570     RequiresAdjustment = true;
3571   }
3572 
3573   if (OldTypeInfo.getNoCallerSavedRegs() !=
3574       NewTypeInfo.getNoCallerSavedRegs()) {
3575     if (NewTypeInfo.getNoCallerSavedRegs()) {
3576       AnyX86NoCallerSavedRegistersAttr *Attr =
3577         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3578       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3579       Diag(OldLocation, diag::note_previous_declaration);
3580       return true;
3581     }
3582 
3583     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3584     RequiresAdjustment = true;
3585   }
3586 
3587   if (RequiresAdjustment) {
3588     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3589     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3590     New->setType(QualType(AdjustedType, 0));
3591     NewQType = Context.getCanonicalType(New->getType());
3592   }
3593 
3594   // If this redeclaration makes the function inline, we may need to add it to
3595   // UndefinedButUsed.
3596   if (!Old->isInlined() && New->isInlined() &&
3597       !New->hasAttr<GNUInlineAttr>() &&
3598       !getLangOpts().GNUInline &&
3599       Old->isUsed(false) &&
3600       !Old->isDefined() && !New->isThisDeclarationADefinition())
3601     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3602                                            SourceLocation()));
3603 
3604   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3605   // about it.
3606   if (New->hasAttr<GNUInlineAttr>() &&
3607       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3608     UndefinedButUsed.erase(Old->getCanonicalDecl());
3609   }
3610 
3611   // If pass_object_size params don't match up perfectly, this isn't a valid
3612   // redeclaration.
3613   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3614       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3615     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3616         << New->getDeclName();
3617     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3618     return true;
3619   }
3620 
3621   if (getLangOpts().CPlusPlus) {
3622     // C++1z [over.load]p2
3623     //   Certain function declarations cannot be overloaded:
3624     //     -- Function declarations that differ only in the return type,
3625     //        the exception specification, or both cannot be overloaded.
3626 
3627     // Check the exception specifications match. This may recompute the type of
3628     // both Old and New if it resolved exception specifications, so grab the
3629     // types again after this. Because this updates the type, we do this before
3630     // any of the other checks below, which may update the "de facto" NewQType
3631     // but do not necessarily update the type of New.
3632     if (CheckEquivalentExceptionSpec(Old, New))
3633       return true;
3634     OldQType = Context.getCanonicalType(Old->getType());
3635     NewQType = Context.getCanonicalType(New->getType());
3636 
3637     // Go back to the type source info to compare the declared return types,
3638     // per C++1y [dcl.type.auto]p13:
3639     //   Redeclarations or specializations of a function or function template
3640     //   with a declared return type that uses a placeholder type shall also
3641     //   use that placeholder, not a deduced type.
3642     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3643     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3644     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3645         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3646                                        OldDeclaredReturnType)) {
3647       QualType ResQT;
3648       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3649           OldDeclaredReturnType->isObjCObjectPointerType())
3650         // FIXME: This does the wrong thing for a deduced return type.
3651         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3652       if (ResQT.isNull()) {
3653         if (New->isCXXClassMember() && New->isOutOfLine())
3654           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3655               << New << New->getReturnTypeSourceRange();
3656         else
3657           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3658               << New->getReturnTypeSourceRange();
3659         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3660                                     << Old->getReturnTypeSourceRange();
3661         return true;
3662       }
3663       else
3664         NewQType = ResQT;
3665     }
3666 
3667     QualType OldReturnType = OldType->getReturnType();
3668     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3669     if (OldReturnType != NewReturnType) {
3670       // If this function has a deduced return type and has already been
3671       // defined, copy the deduced value from the old declaration.
3672       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3673       if (OldAT && OldAT->isDeduced()) {
3674         QualType DT = OldAT->getDeducedType();
3675         if (DT.isNull()) {
3676           New->setType(SubstAutoTypeDependent(New->getType()));
3677           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3678         } else {
3679           New->setType(SubstAutoType(New->getType(), DT));
3680           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3681         }
3682       }
3683     }
3684 
3685     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3686     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3687     if (OldMethod && NewMethod) {
3688       // Preserve triviality.
3689       NewMethod->setTrivial(OldMethod->isTrivial());
3690 
3691       // MSVC allows explicit template specialization at class scope:
3692       // 2 CXXMethodDecls referring to the same function will be injected.
3693       // We don't want a redeclaration error.
3694       bool IsClassScopeExplicitSpecialization =
3695                               OldMethod->isFunctionTemplateSpecialization() &&
3696                               NewMethod->isFunctionTemplateSpecialization();
3697       bool isFriend = NewMethod->getFriendObjectKind();
3698 
3699       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3700           !IsClassScopeExplicitSpecialization) {
3701         //    -- Member function declarations with the same name and the
3702         //       same parameter types cannot be overloaded if any of them
3703         //       is a static member function declaration.
3704         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3705           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3706           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3707           return true;
3708         }
3709 
3710         // C++ [class.mem]p1:
3711         //   [...] A member shall not be declared twice in the
3712         //   member-specification, except that a nested class or member
3713         //   class template can be declared and then later defined.
3714         if (!inTemplateInstantiation()) {
3715           unsigned NewDiag;
3716           if (isa<CXXConstructorDecl>(OldMethod))
3717             NewDiag = diag::err_constructor_redeclared;
3718           else if (isa<CXXDestructorDecl>(NewMethod))
3719             NewDiag = diag::err_destructor_redeclared;
3720           else if (isa<CXXConversionDecl>(NewMethod))
3721             NewDiag = diag::err_conv_function_redeclared;
3722           else
3723             NewDiag = diag::err_member_redeclared;
3724 
3725           Diag(New->getLocation(), NewDiag);
3726         } else {
3727           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3728             << New << New->getType();
3729         }
3730         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3731         return true;
3732 
3733       // Complain if this is an explicit declaration of a special
3734       // member that was initially declared implicitly.
3735       //
3736       // As an exception, it's okay to befriend such methods in order
3737       // to permit the implicit constructor/destructor/operator calls.
3738       } else if (OldMethod->isImplicit()) {
3739         if (isFriend) {
3740           NewMethod->setImplicit();
3741         } else {
3742           Diag(NewMethod->getLocation(),
3743                diag::err_definition_of_implicitly_declared_member)
3744             << New << getSpecialMember(OldMethod);
3745           return true;
3746         }
3747       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3748         Diag(NewMethod->getLocation(),
3749              diag::err_definition_of_explicitly_defaulted_member)
3750           << getSpecialMember(OldMethod);
3751         return true;
3752       }
3753     }
3754 
3755     // C++11 [dcl.attr.noreturn]p1:
3756     //   The first declaration of a function shall specify the noreturn
3757     //   attribute if any declaration of that function specifies the noreturn
3758     //   attribute.
3759     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3760       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3761         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3762             << NRA;
3763         Diag(Old->getLocation(), diag::note_previous_declaration);
3764       }
3765 
3766     // C++11 [dcl.attr.depend]p2:
3767     //   The first declaration of a function shall specify the
3768     //   carries_dependency attribute for its declarator-id if any declaration
3769     //   of the function specifies the carries_dependency attribute.
3770     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3771     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3772       Diag(CDA->getLocation(),
3773            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3774       Diag(Old->getFirstDecl()->getLocation(),
3775            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3776     }
3777 
3778     // (C++98 8.3.5p3):
3779     //   All declarations for a function shall agree exactly in both the
3780     //   return type and the parameter-type-list.
3781     // We also want to respect all the extended bits except noreturn.
3782 
3783     // noreturn should now match unless the old type info didn't have it.
3784     QualType OldQTypeForComparison = OldQType;
3785     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3786       auto *OldType = OldQType->castAs<FunctionProtoType>();
3787       const FunctionType *OldTypeForComparison
3788         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3789       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3790       assert(OldQTypeForComparison.isCanonical());
3791     }
3792 
3793     if (haveIncompatibleLanguageLinkages(Old, New)) {
3794       // As a special case, retain the language linkage from previous
3795       // declarations of a friend function as an extension.
3796       //
3797       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3798       // and is useful because there's otherwise no way to specify language
3799       // linkage within class scope.
3800       //
3801       // Check cautiously as the friend object kind isn't yet complete.
3802       if (New->getFriendObjectKind() != Decl::FOK_None) {
3803         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3804         Diag(OldLocation, PrevDiag);
3805       } else {
3806         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3807         Diag(OldLocation, PrevDiag);
3808         return true;
3809       }
3810     }
3811 
3812     // If the function types are compatible, merge the declarations. Ignore the
3813     // exception specifier because it was already checked above in
3814     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3815     // about incompatible types under -fms-compatibility.
3816     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3817                                                          NewQType))
3818       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3819 
3820     // If the types are imprecise (due to dependent constructs in friends or
3821     // local extern declarations), it's OK if they differ. We'll check again
3822     // during instantiation.
3823     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3824       return false;
3825 
3826     // Fall through for conflicting redeclarations and redefinitions.
3827   }
3828 
3829   // C: Function types need to be compatible, not identical. This handles
3830   // duplicate function decls like "void f(int); void f(enum X);" properly.
3831   if (!getLangOpts().CPlusPlus &&
3832       Context.typesAreCompatible(OldQType, NewQType)) {
3833     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3834     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3835     const FunctionProtoType *OldProto = nullptr;
3836     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3837         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3838       // The old declaration provided a function prototype, but the
3839       // new declaration does not. Merge in the prototype.
3840       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3841       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3842       NewQType =
3843           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3844                                   OldProto->getExtProtoInfo());
3845       New->setType(NewQType);
3846       New->setHasInheritedPrototype();
3847 
3848       // Synthesize parameters with the same types.
3849       SmallVector<ParmVarDecl*, 16> Params;
3850       for (const auto &ParamType : OldProto->param_types()) {
3851         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3852                                                  SourceLocation(), nullptr,
3853                                                  ParamType, /*TInfo=*/nullptr,
3854                                                  SC_None, nullptr);
3855         Param->setScopeInfo(0, Params.size());
3856         Param->setImplicit();
3857         Params.push_back(Param);
3858       }
3859 
3860       New->setParams(Params);
3861     }
3862 
3863     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3864   }
3865 
3866   // Check if the function types are compatible when pointer size address
3867   // spaces are ignored.
3868   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3869     return false;
3870 
3871   // GNU C permits a K&R definition to follow a prototype declaration
3872   // if the declared types of the parameters in the K&R definition
3873   // match the types in the prototype declaration, even when the
3874   // promoted types of the parameters from the K&R definition differ
3875   // from the types in the prototype. GCC then keeps the types from
3876   // the prototype.
3877   //
3878   // If a variadic prototype is followed by a non-variadic K&R definition,
3879   // the K&R definition becomes variadic.  This is sort of an edge case, but
3880   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3881   // C99 6.9.1p8.
3882   if (!getLangOpts().CPlusPlus &&
3883       Old->hasPrototype() && !New->hasPrototype() &&
3884       New->getType()->getAs<FunctionProtoType>() &&
3885       Old->getNumParams() == New->getNumParams()) {
3886     SmallVector<QualType, 16> ArgTypes;
3887     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3888     const FunctionProtoType *OldProto
3889       = Old->getType()->getAs<FunctionProtoType>();
3890     const FunctionProtoType *NewProto
3891       = New->getType()->getAs<FunctionProtoType>();
3892 
3893     // Determine whether this is the GNU C extension.
3894     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3895                                                NewProto->getReturnType());
3896     bool LooseCompatible = !MergedReturn.isNull();
3897     for (unsigned Idx = 0, End = Old->getNumParams();
3898          LooseCompatible && Idx != End; ++Idx) {
3899       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3900       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3901       if (Context.typesAreCompatible(OldParm->getType(),
3902                                      NewProto->getParamType(Idx))) {
3903         ArgTypes.push_back(NewParm->getType());
3904       } else if (Context.typesAreCompatible(OldParm->getType(),
3905                                             NewParm->getType(),
3906                                             /*CompareUnqualified=*/true)) {
3907         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3908                                            NewProto->getParamType(Idx) };
3909         Warnings.push_back(Warn);
3910         ArgTypes.push_back(NewParm->getType());
3911       } else
3912         LooseCompatible = false;
3913     }
3914 
3915     if (LooseCompatible) {
3916       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3917         Diag(Warnings[Warn].NewParm->getLocation(),
3918              diag::ext_param_promoted_not_compatible_with_prototype)
3919           << Warnings[Warn].PromotedType
3920           << Warnings[Warn].OldParm->getType();
3921         if (Warnings[Warn].OldParm->getLocation().isValid())
3922           Diag(Warnings[Warn].OldParm->getLocation(),
3923                diag::note_previous_declaration);
3924       }
3925 
3926       if (MergeTypeWithOld)
3927         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3928                                              OldProto->getExtProtoInfo()));
3929       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3930     }
3931 
3932     // Fall through to diagnose conflicting types.
3933   }
3934 
3935   // A function that has already been declared has been redeclared or
3936   // defined with a different type; show an appropriate diagnostic.
3937 
3938   // If the previous declaration was an implicitly-generated builtin
3939   // declaration, then at the very least we should use a specialized note.
3940   unsigned BuiltinID;
3941   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3942     // If it's actually a library-defined builtin function like 'malloc'
3943     // or 'printf', just warn about the incompatible redeclaration.
3944     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3945       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3946       Diag(OldLocation, diag::note_previous_builtin_declaration)
3947         << Old << Old->getType();
3948       return false;
3949     }
3950 
3951     PrevDiag = diag::note_previous_builtin_declaration;
3952   }
3953 
3954   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3955   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3956   return true;
3957 }
3958 
3959 /// Completes the merge of two function declarations that are
3960 /// known to be compatible.
3961 ///
3962 /// This routine handles the merging of attributes and other
3963 /// properties of function declarations from the old declaration to
3964 /// the new declaration, once we know that New is in fact a
3965 /// redeclaration of Old.
3966 ///
3967 /// \returns false
3968 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3969                                         Scope *S, bool MergeTypeWithOld) {
3970   // Merge the attributes
3971   mergeDeclAttributes(New, Old);
3972 
3973   // Merge "pure" flag.
3974   if (Old->isPure())
3975     New->setPure();
3976 
3977   // Merge "used" flag.
3978   if (Old->getMostRecentDecl()->isUsed(false))
3979     New->setIsUsed();
3980 
3981   // Merge attributes from the parameters.  These can mismatch with K&R
3982   // declarations.
3983   if (New->getNumParams() == Old->getNumParams())
3984       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3985         ParmVarDecl *NewParam = New->getParamDecl(i);
3986         ParmVarDecl *OldParam = Old->getParamDecl(i);
3987         mergeParamDeclAttributes(NewParam, OldParam, *this);
3988         mergeParamDeclTypes(NewParam, OldParam, *this);
3989       }
3990 
3991   if (getLangOpts().CPlusPlus)
3992     return MergeCXXFunctionDecl(New, Old, S);
3993 
3994   // Merge the function types so the we get the composite types for the return
3995   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3996   // was visible.
3997   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3998   if (!Merged.isNull() && MergeTypeWithOld)
3999     New->setType(Merged);
4000 
4001   return false;
4002 }
4003 
4004 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4005                                 ObjCMethodDecl *oldMethod) {
4006   // Merge the attributes, including deprecated/unavailable
4007   AvailabilityMergeKind MergeKind =
4008       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4009           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4010                                      : AMK_ProtocolImplementation)
4011           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4012                                                            : AMK_Override;
4013 
4014   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4015 
4016   // Merge attributes from the parameters.
4017   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4018                                        oe = oldMethod->param_end();
4019   for (ObjCMethodDecl::param_iterator
4020          ni = newMethod->param_begin(), ne = newMethod->param_end();
4021        ni != ne && oi != oe; ++ni, ++oi)
4022     mergeParamDeclAttributes(*ni, *oi, *this);
4023 
4024   CheckObjCMethodOverride(newMethod, oldMethod);
4025 }
4026 
4027 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4028   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4029 
4030   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4031          ? diag::err_redefinition_different_type
4032          : diag::err_redeclaration_different_type)
4033     << New->getDeclName() << New->getType() << Old->getType();
4034 
4035   diag::kind PrevDiag;
4036   SourceLocation OldLocation;
4037   std::tie(PrevDiag, OldLocation)
4038     = getNoteDiagForInvalidRedeclaration(Old, New);
4039   S.Diag(OldLocation, PrevDiag);
4040   New->setInvalidDecl();
4041 }
4042 
4043 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4044 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4045 /// emitting diagnostics as appropriate.
4046 ///
4047 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4048 /// to here in AddInitializerToDecl. We can't check them before the initializer
4049 /// is attached.
4050 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4051                              bool MergeTypeWithOld) {
4052   if (New->isInvalidDecl() || Old->isInvalidDecl())
4053     return;
4054 
4055   QualType MergedT;
4056   if (getLangOpts().CPlusPlus) {
4057     if (New->getType()->isUndeducedType()) {
4058       // We don't know what the new type is until the initializer is attached.
4059       return;
4060     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4061       // These could still be something that needs exception specs checked.
4062       return MergeVarDeclExceptionSpecs(New, Old);
4063     }
4064     // C++ [basic.link]p10:
4065     //   [...] the types specified by all declarations referring to a given
4066     //   object or function shall be identical, except that declarations for an
4067     //   array object can specify array types that differ by the presence or
4068     //   absence of a major array bound (8.3.4).
4069     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4070       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4071       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4072 
4073       // We are merging a variable declaration New into Old. If it has an array
4074       // bound, and that bound differs from Old's bound, we should diagnose the
4075       // mismatch.
4076       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4077         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4078              PrevVD = PrevVD->getPreviousDecl()) {
4079           QualType PrevVDTy = PrevVD->getType();
4080           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4081             continue;
4082 
4083           if (!Context.hasSameType(New->getType(), PrevVDTy))
4084             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4085         }
4086       }
4087 
4088       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4089         if (Context.hasSameType(OldArray->getElementType(),
4090                                 NewArray->getElementType()))
4091           MergedT = New->getType();
4092       }
4093       // FIXME: Check visibility. New is hidden but has a complete type. If New
4094       // has no array bound, it should not inherit one from Old, if Old is not
4095       // visible.
4096       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4097         if (Context.hasSameType(OldArray->getElementType(),
4098                                 NewArray->getElementType()))
4099           MergedT = Old->getType();
4100       }
4101     }
4102     else if (New->getType()->isObjCObjectPointerType() &&
4103                Old->getType()->isObjCObjectPointerType()) {
4104       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4105                                               Old->getType());
4106     }
4107   } else {
4108     // C 6.2.7p2:
4109     //   All declarations that refer to the same object or function shall have
4110     //   compatible type.
4111     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4112   }
4113   if (MergedT.isNull()) {
4114     // It's OK if we couldn't merge types if either type is dependent, for a
4115     // block-scope variable. In other cases (static data members of class
4116     // templates, variable templates, ...), we require the types to be
4117     // equivalent.
4118     // FIXME: The C++ standard doesn't say anything about this.
4119     if ((New->getType()->isDependentType() ||
4120          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4121       // If the old type was dependent, we can't merge with it, so the new type
4122       // becomes dependent for now. We'll reproduce the original type when we
4123       // instantiate the TypeSourceInfo for the variable.
4124       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4125         New->setType(Context.DependentTy);
4126       return;
4127     }
4128     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4129   }
4130 
4131   // Don't actually update the type on the new declaration if the old
4132   // declaration was an extern declaration in a different scope.
4133   if (MergeTypeWithOld)
4134     New->setType(MergedT);
4135 }
4136 
4137 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4138                                   LookupResult &Previous) {
4139   // C11 6.2.7p4:
4140   //   For an identifier with internal or external linkage declared
4141   //   in a scope in which a prior declaration of that identifier is
4142   //   visible, if the prior declaration specifies internal or
4143   //   external linkage, the type of the identifier at the later
4144   //   declaration becomes the composite type.
4145   //
4146   // If the variable isn't visible, we do not merge with its type.
4147   if (Previous.isShadowed())
4148     return false;
4149 
4150   if (S.getLangOpts().CPlusPlus) {
4151     // C++11 [dcl.array]p3:
4152     //   If there is a preceding declaration of the entity in the same
4153     //   scope in which the bound was specified, an omitted array bound
4154     //   is taken to be the same as in that earlier declaration.
4155     return NewVD->isPreviousDeclInSameBlockScope() ||
4156            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4157             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4158   } else {
4159     // If the old declaration was function-local, don't merge with its
4160     // type unless we're in the same function.
4161     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4162            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4163   }
4164 }
4165 
4166 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4167 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4168 /// situation, merging decls or emitting diagnostics as appropriate.
4169 ///
4170 /// Tentative definition rules (C99 6.9.2p2) are checked by
4171 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4172 /// definitions here, since the initializer hasn't been attached.
4173 ///
4174 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4175   // If the new decl is already invalid, don't do any other checking.
4176   if (New->isInvalidDecl())
4177     return;
4178 
4179   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4180     return;
4181 
4182   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4183 
4184   // Verify the old decl was also a variable or variable template.
4185   VarDecl *Old = nullptr;
4186   VarTemplateDecl *OldTemplate = nullptr;
4187   if (Previous.isSingleResult()) {
4188     if (NewTemplate) {
4189       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4190       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4191 
4192       if (auto *Shadow =
4193               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4194         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4195           return New->setInvalidDecl();
4196     } else {
4197       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4198 
4199       if (auto *Shadow =
4200               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4201         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4202           return New->setInvalidDecl();
4203     }
4204   }
4205   if (!Old) {
4206     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4207         << New->getDeclName();
4208     notePreviousDefinition(Previous.getRepresentativeDecl(),
4209                            New->getLocation());
4210     return New->setInvalidDecl();
4211   }
4212 
4213   // If the old declaration was found in an inline namespace and the new
4214   // declaration was qualified, update the DeclContext to match.
4215   adjustDeclContextForDeclaratorDecl(New, Old);
4216 
4217   // Ensure the template parameters are compatible.
4218   if (NewTemplate &&
4219       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4220                                       OldTemplate->getTemplateParameters(),
4221                                       /*Complain=*/true, TPL_TemplateMatch))
4222     return New->setInvalidDecl();
4223 
4224   // C++ [class.mem]p1:
4225   //   A member shall not be declared twice in the member-specification [...]
4226   //
4227   // Here, we need only consider static data members.
4228   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4229     Diag(New->getLocation(), diag::err_duplicate_member)
4230       << New->getIdentifier();
4231     Diag(Old->getLocation(), diag::note_previous_declaration);
4232     New->setInvalidDecl();
4233   }
4234 
4235   mergeDeclAttributes(New, Old);
4236   // Warn if an already-declared variable is made a weak_import in a subsequent
4237   // declaration
4238   if (New->hasAttr<WeakImportAttr>() &&
4239       Old->getStorageClass() == SC_None &&
4240       !Old->hasAttr<WeakImportAttr>()) {
4241     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4242     Diag(Old->getLocation(), diag::note_previous_declaration);
4243     // Remove weak_import attribute on new declaration.
4244     New->dropAttr<WeakImportAttr>();
4245   }
4246 
4247   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4248     if (!Old->hasAttr<InternalLinkageAttr>()) {
4249       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4250           << ILA;
4251       Diag(Old->getLocation(), diag::note_previous_declaration);
4252       New->dropAttr<InternalLinkageAttr>();
4253     }
4254 
4255   // Merge the types.
4256   VarDecl *MostRecent = Old->getMostRecentDecl();
4257   if (MostRecent != Old) {
4258     MergeVarDeclTypes(New, MostRecent,
4259                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4260     if (New->isInvalidDecl())
4261       return;
4262   }
4263 
4264   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4265   if (New->isInvalidDecl())
4266     return;
4267 
4268   diag::kind PrevDiag;
4269   SourceLocation OldLocation;
4270   std::tie(PrevDiag, OldLocation) =
4271       getNoteDiagForInvalidRedeclaration(Old, New);
4272 
4273   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4274   if (New->getStorageClass() == SC_Static &&
4275       !New->isStaticDataMember() &&
4276       Old->hasExternalFormalLinkage()) {
4277     if (getLangOpts().MicrosoftExt) {
4278       Diag(New->getLocation(), diag::ext_static_non_static)
4279           << New->getDeclName();
4280       Diag(OldLocation, PrevDiag);
4281     } else {
4282       Diag(New->getLocation(), diag::err_static_non_static)
4283           << New->getDeclName();
4284       Diag(OldLocation, PrevDiag);
4285       return New->setInvalidDecl();
4286     }
4287   }
4288   // C99 6.2.2p4:
4289   //   For an identifier declared with the storage-class specifier
4290   //   extern in a scope in which a prior declaration of that
4291   //   identifier is visible,23) if the prior declaration specifies
4292   //   internal or external linkage, the linkage of the identifier at
4293   //   the later declaration is the same as the linkage specified at
4294   //   the prior declaration. If no prior declaration is visible, or
4295   //   if the prior declaration specifies no linkage, then the
4296   //   identifier has external linkage.
4297   if (New->hasExternalStorage() && Old->hasLinkage())
4298     /* Okay */;
4299   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4300            !New->isStaticDataMember() &&
4301            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4302     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4303     Diag(OldLocation, PrevDiag);
4304     return New->setInvalidDecl();
4305   }
4306 
4307   // Check if extern is followed by non-extern and vice-versa.
4308   if (New->hasExternalStorage() &&
4309       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4310     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4311     Diag(OldLocation, PrevDiag);
4312     return New->setInvalidDecl();
4313   }
4314   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4315       !New->hasExternalStorage()) {
4316     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4317     Diag(OldLocation, PrevDiag);
4318     return New->setInvalidDecl();
4319   }
4320 
4321   if (CheckRedeclarationInModule(New, Old))
4322     return;
4323 
4324   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4325 
4326   // FIXME: The test for external storage here seems wrong? We still
4327   // need to check for mismatches.
4328   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4329       // Don't complain about out-of-line definitions of static members.
4330       !(Old->getLexicalDeclContext()->isRecord() &&
4331         !New->getLexicalDeclContext()->isRecord())) {
4332     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4333     Diag(OldLocation, PrevDiag);
4334     return New->setInvalidDecl();
4335   }
4336 
4337   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4338     if (VarDecl *Def = Old->getDefinition()) {
4339       // C++1z [dcl.fcn.spec]p4:
4340       //   If the definition of a variable appears in a translation unit before
4341       //   its first declaration as inline, the program is ill-formed.
4342       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4343       Diag(Def->getLocation(), diag::note_previous_definition);
4344     }
4345   }
4346 
4347   // If this redeclaration makes the variable inline, we may need to add it to
4348   // UndefinedButUsed.
4349   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4350       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4351     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4352                                            SourceLocation()));
4353 
4354   if (New->getTLSKind() != Old->getTLSKind()) {
4355     if (!Old->getTLSKind()) {
4356       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4357       Diag(OldLocation, PrevDiag);
4358     } else if (!New->getTLSKind()) {
4359       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4360       Diag(OldLocation, PrevDiag);
4361     } else {
4362       // Do not allow redeclaration to change the variable between requiring
4363       // static and dynamic initialization.
4364       // FIXME: GCC allows this, but uses the TLS keyword on the first
4365       // declaration to determine the kind. Do we need to be compatible here?
4366       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4367         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4368       Diag(OldLocation, PrevDiag);
4369     }
4370   }
4371 
4372   // C++ doesn't have tentative definitions, so go right ahead and check here.
4373   if (getLangOpts().CPlusPlus &&
4374       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4375     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4376         Old->getCanonicalDecl()->isConstexpr()) {
4377       // This definition won't be a definition any more once it's been merged.
4378       Diag(New->getLocation(),
4379            diag::warn_deprecated_redundant_constexpr_static_def);
4380     } else if (VarDecl *Def = Old->getDefinition()) {
4381       if (checkVarDeclRedefinition(Def, New))
4382         return;
4383     }
4384   }
4385 
4386   if (haveIncompatibleLanguageLinkages(Old, New)) {
4387     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4388     Diag(OldLocation, PrevDiag);
4389     New->setInvalidDecl();
4390     return;
4391   }
4392 
4393   // Merge "used" flag.
4394   if (Old->getMostRecentDecl()->isUsed(false))
4395     New->setIsUsed();
4396 
4397   // Keep a chain of previous declarations.
4398   New->setPreviousDecl(Old);
4399   if (NewTemplate)
4400     NewTemplate->setPreviousDecl(OldTemplate);
4401 
4402   // Inherit access appropriately.
4403   New->setAccess(Old->getAccess());
4404   if (NewTemplate)
4405     NewTemplate->setAccess(New->getAccess());
4406 
4407   if (Old->isInline())
4408     New->setImplicitlyInline();
4409 }
4410 
4411 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4412   SourceManager &SrcMgr = getSourceManager();
4413   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4414   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4415   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4416   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4417   auto &HSI = PP.getHeaderSearchInfo();
4418   StringRef HdrFilename =
4419       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4420 
4421   auto noteFromModuleOrInclude = [&](Module *Mod,
4422                                      SourceLocation IncLoc) -> bool {
4423     // Redefinition errors with modules are common with non modular mapped
4424     // headers, example: a non-modular header H in module A that also gets
4425     // included directly in a TU. Pointing twice to the same header/definition
4426     // is confusing, try to get better diagnostics when modules is on.
4427     if (IncLoc.isValid()) {
4428       if (Mod) {
4429         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4430             << HdrFilename.str() << Mod->getFullModuleName();
4431         if (!Mod->DefinitionLoc.isInvalid())
4432           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4433               << Mod->getFullModuleName();
4434       } else {
4435         Diag(IncLoc, diag::note_redefinition_include_same_file)
4436             << HdrFilename.str();
4437       }
4438       return true;
4439     }
4440 
4441     return false;
4442   };
4443 
4444   // Is it the same file and same offset? Provide more information on why
4445   // this leads to a redefinition error.
4446   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4447     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4448     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4449     bool EmittedDiag =
4450         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4451     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4452 
4453     // If the header has no guards, emit a note suggesting one.
4454     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4455       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4456 
4457     if (EmittedDiag)
4458       return;
4459   }
4460 
4461   // Redefinition coming from different files or couldn't do better above.
4462   if (Old->getLocation().isValid())
4463     Diag(Old->getLocation(), diag::note_previous_definition);
4464 }
4465 
4466 /// We've just determined that \p Old and \p New both appear to be definitions
4467 /// of the same variable. Either diagnose or fix the problem.
4468 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4469   if (!hasVisibleDefinition(Old) &&
4470       (New->getFormalLinkage() == InternalLinkage ||
4471        New->isInline() ||
4472        New->getDescribedVarTemplate() ||
4473        New->getNumTemplateParameterLists() ||
4474        New->getDeclContext()->isDependentContext())) {
4475     // The previous definition is hidden, and multiple definitions are
4476     // permitted (in separate TUs). Demote this to a declaration.
4477     New->demoteThisDefinitionToDeclaration();
4478 
4479     // Make the canonical definition visible.
4480     if (auto *OldTD = Old->getDescribedVarTemplate())
4481       makeMergedDefinitionVisible(OldTD);
4482     makeMergedDefinitionVisible(Old);
4483     return false;
4484   } else {
4485     Diag(New->getLocation(), diag::err_redefinition) << New;
4486     notePreviousDefinition(Old, New->getLocation());
4487     New->setInvalidDecl();
4488     return true;
4489   }
4490 }
4491 
4492 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4493 /// no declarator (e.g. "struct foo;") is parsed.
4494 Decl *
4495 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4496                                  RecordDecl *&AnonRecord) {
4497   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4498                                     AnonRecord);
4499 }
4500 
4501 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4502 // disambiguate entities defined in different scopes.
4503 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4504 // compatibility.
4505 // We will pick our mangling number depending on which version of MSVC is being
4506 // targeted.
4507 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4508   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4509              ? S->getMSCurManglingNumber()
4510              : S->getMSLastManglingNumber();
4511 }
4512 
4513 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4514   if (!Context.getLangOpts().CPlusPlus)
4515     return;
4516 
4517   if (isa<CXXRecordDecl>(Tag->getParent())) {
4518     // If this tag is the direct child of a class, number it if
4519     // it is anonymous.
4520     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4521       return;
4522     MangleNumberingContext &MCtx =
4523         Context.getManglingNumberContext(Tag->getParent());
4524     Context.setManglingNumber(
4525         Tag, MCtx.getManglingNumber(
4526                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4527     return;
4528   }
4529 
4530   // If this tag isn't a direct child of a class, number it if it is local.
4531   MangleNumberingContext *MCtx;
4532   Decl *ManglingContextDecl;
4533   std::tie(MCtx, ManglingContextDecl) =
4534       getCurrentMangleNumberContext(Tag->getDeclContext());
4535   if (MCtx) {
4536     Context.setManglingNumber(
4537         Tag, MCtx->getManglingNumber(
4538                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4539   }
4540 }
4541 
4542 namespace {
4543 struct NonCLikeKind {
4544   enum {
4545     None,
4546     BaseClass,
4547     DefaultMemberInit,
4548     Lambda,
4549     Friend,
4550     OtherMember,
4551     Invalid,
4552   } Kind = None;
4553   SourceRange Range;
4554 
4555   explicit operator bool() { return Kind != None; }
4556 };
4557 }
4558 
4559 /// Determine whether a class is C-like, according to the rules of C++
4560 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4561 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4562   if (RD->isInvalidDecl())
4563     return {NonCLikeKind::Invalid, {}};
4564 
4565   // C++ [dcl.typedef]p9: [P1766R1]
4566   //   An unnamed class with a typedef name for linkage purposes shall not
4567   //
4568   //    -- have any base classes
4569   if (RD->getNumBases())
4570     return {NonCLikeKind::BaseClass,
4571             SourceRange(RD->bases_begin()->getBeginLoc(),
4572                         RD->bases_end()[-1].getEndLoc())};
4573   bool Invalid = false;
4574   for (Decl *D : RD->decls()) {
4575     // Don't complain about things we already diagnosed.
4576     if (D->isInvalidDecl()) {
4577       Invalid = true;
4578       continue;
4579     }
4580 
4581     //  -- have any [...] default member initializers
4582     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4583       if (FD->hasInClassInitializer()) {
4584         auto *Init = FD->getInClassInitializer();
4585         return {NonCLikeKind::DefaultMemberInit,
4586                 Init ? Init->getSourceRange() : D->getSourceRange()};
4587       }
4588       continue;
4589     }
4590 
4591     // FIXME: We don't allow friend declarations. This violates the wording of
4592     // P1766, but not the intent.
4593     if (isa<FriendDecl>(D))
4594       return {NonCLikeKind::Friend, D->getSourceRange()};
4595 
4596     //  -- declare any members other than non-static data members, member
4597     //     enumerations, or member classes,
4598     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4599         isa<EnumDecl>(D))
4600       continue;
4601     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4602     if (!MemberRD) {
4603       if (D->isImplicit())
4604         continue;
4605       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4606     }
4607 
4608     //  -- contain a lambda-expression,
4609     if (MemberRD->isLambda())
4610       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4611 
4612     //  and all member classes shall also satisfy these requirements
4613     //  (recursively).
4614     if (MemberRD->isThisDeclarationADefinition()) {
4615       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4616         return Kind;
4617     }
4618   }
4619 
4620   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4621 }
4622 
4623 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4624                                         TypedefNameDecl *NewTD) {
4625   if (TagFromDeclSpec->isInvalidDecl())
4626     return;
4627 
4628   // Do nothing if the tag already has a name for linkage purposes.
4629   if (TagFromDeclSpec->hasNameForLinkage())
4630     return;
4631 
4632   // A well-formed anonymous tag must always be a TUK_Definition.
4633   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4634 
4635   // The type must match the tag exactly;  no qualifiers allowed.
4636   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4637                            Context.getTagDeclType(TagFromDeclSpec))) {
4638     if (getLangOpts().CPlusPlus)
4639       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4640     return;
4641   }
4642 
4643   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4644   //   An unnamed class with a typedef name for linkage purposes shall [be
4645   //   C-like].
4646   //
4647   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4648   // shouldn't happen, but there are constructs that the language rule doesn't
4649   // disallow for which we can't reasonably avoid computing linkage early.
4650   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4651   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4652                              : NonCLikeKind();
4653   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4654   if (NonCLike || ChangesLinkage) {
4655     if (NonCLike.Kind == NonCLikeKind::Invalid)
4656       return;
4657 
4658     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4659     if (ChangesLinkage) {
4660       // If the linkage changes, we can't accept this as an extension.
4661       if (NonCLike.Kind == NonCLikeKind::None)
4662         DiagID = diag::err_typedef_changes_linkage;
4663       else
4664         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4665     }
4666 
4667     SourceLocation FixitLoc =
4668         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4669     llvm::SmallString<40> TextToInsert;
4670     TextToInsert += ' ';
4671     TextToInsert += NewTD->getIdentifier()->getName();
4672 
4673     Diag(FixitLoc, DiagID)
4674       << isa<TypeAliasDecl>(NewTD)
4675       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4676     if (NonCLike.Kind != NonCLikeKind::None) {
4677       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4678         << NonCLike.Kind - 1 << NonCLike.Range;
4679     }
4680     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4681       << NewTD << isa<TypeAliasDecl>(NewTD);
4682 
4683     if (ChangesLinkage)
4684       return;
4685   }
4686 
4687   // Otherwise, set this as the anon-decl typedef for the tag.
4688   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4689 }
4690 
4691 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4692   switch (T) {
4693   case DeclSpec::TST_class:
4694     return 0;
4695   case DeclSpec::TST_struct:
4696     return 1;
4697   case DeclSpec::TST_interface:
4698     return 2;
4699   case DeclSpec::TST_union:
4700     return 3;
4701   case DeclSpec::TST_enum:
4702     return 4;
4703   default:
4704     llvm_unreachable("unexpected type specifier");
4705   }
4706 }
4707 
4708 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4709 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4710 /// parameters to cope with template friend declarations.
4711 Decl *
4712 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4713                                  MultiTemplateParamsArg TemplateParams,
4714                                  bool IsExplicitInstantiation,
4715                                  RecordDecl *&AnonRecord) {
4716   Decl *TagD = nullptr;
4717   TagDecl *Tag = nullptr;
4718   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4719       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4720       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4721       DS.getTypeSpecType() == DeclSpec::TST_union ||
4722       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4723     TagD = DS.getRepAsDecl();
4724 
4725     if (!TagD) // We probably had an error
4726       return nullptr;
4727 
4728     // Note that the above type specs guarantee that the
4729     // type rep is a Decl, whereas in many of the others
4730     // it's a Type.
4731     if (isa<TagDecl>(TagD))
4732       Tag = cast<TagDecl>(TagD);
4733     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4734       Tag = CTD->getTemplatedDecl();
4735   }
4736 
4737   if (Tag) {
4738     handleTagNumbering(Tag, S);
4739     Tag->setFreeStanding();
4740     if (Tag->isInvalidDecl())
4741       return Tag;
4742   }
4743 
4744   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4745     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4746     // or incomplete types shall not be restrict-qualified."
4747     if (TypeQuals & DeclSpec::TQ_restrict)
4748       Diag(DS.getRestrictSpecLoc(),
4749            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4750            << DS.getSourceRange();
4751   }
4752 
4753   if (DS.isInlineSpecified())
4754     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4755         << getLangOpts().CPlusPlus17;
4756 
4757   if (DS.hasConstexprSpecifier()) {
4758     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4759     // and definitions of functions and variables.
4760     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4761     // the declaration of a function or function template
4762     if (Tag)
4763       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4764           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4765           << static_cast<int>(DS.getConstexprSpecifier());
4766     else
4767       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4768           << static_cast<int>(DS.getConstexprSpecifier());
4769     // Don't emit warnings after this error.
4770     return TagD;
4771   }
4772 
4773   DiagnoseFunctionSpecifiers(DS);
4774 
4775   if (DS.isFriendSpecified()) {
4776     // If we're dealing with a decl but not a TagDecl, assume that
4777     // whatever routines created it handled the friendship aspect.
4778     if (TagD && !Tag)
4779       return nullptr;
4780     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4781   }
4782 
4783   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4784   bool IsExplicitSpecialization =
4785     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4786   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4787       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4788       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4789     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4790     // nested-name-specifier unless it is an explicit instantiation
4791     // or an explicit specialization.
4792     //
4793     // FIXME: We allow class template partial specializations here too, per the
4794     // obvious intent of DR1819.
4795     //
4796     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4797     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4798         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4799     return nullptr;
4800   }
4801 
4802   // Track whether this decl-specifier declares anything.
4803   bool DeclaresAnything = true;
4804 
4805   // Handle anonymous struct definitions.
4806   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4807     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4808         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4809       if (getLangOpts().CPlusPlus ||
4810           Record->getDeclContext()->isRecord()) {
4811         // If CurContext is a DeclContext that can contain statements,
4812         // RecursiveASTVisitor won't visit the decls that
4813         // BuildAnonymousStructOrUnion() will put into CurContext.
4814         // Also store them here so that they can be part of the
4815         // DeclStmt that gets created in this case.
4816         // FIXME: Also return the IndirectFieldDecls created by
4817         // BuildAnonymousStructOr union, for the same reason?
4818         if (CurContext->isFunctionOrMethod())
4819           AnonRecord = Record;
4820         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4821                                            Context.getPrintingPolicy());
4822       }
4823 
4824       DeclaresAnything = false;
4825     }
4826   }
4827 
4828   // C11 6.7.2.1p2:
4829   //   A struct-declaration that does not declare an anonymous structure or
4830   //   anonymous union shall contain a struct-declarator-list.
4831   //
4832   // This rule also existed in C89 and C99; the grammar for struct-declaration
4833   // did not permit a struct-declaration without a struct-declarator-list.
4834   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4835       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4836     // Check for Microsoft C extension: anonymous struct/union member.
4837     // Handle 2 kinds of anonymous struct/union:
4838     //   struct STRUCT;
4839     //   union UNION;
4840     // and
4841     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4842     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4843     if ((Tag && Tag->getDeclName()) ||
4844         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4845       RecordDecl *Record = nullptr;
4846       if (Tag)
4847         Record = dyn_cast<RecordDecl>(Tag);
4848       else if (const RecordType *RT =
4849                    DS.getRepAsType().get()->getAsStructureType())
4850         Record = RT->getDecl();
4851       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4852         Record = UT->getDecl();
4853 
4854       if (Record && getLangOpts().MicrosoftExt) {
4855         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4856             << Record->isUnion() << DS.getSourceRange();
4857         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4858       }
4859 
4860       DeclaresAnything = false;
4861     }
4862   }
4863 
4864   // Skip all the checks below if we have a type error.
4865   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4866       (TagD && TagD->isInvalidDecl()))
4867     return TagD;
4868 
4869   if (getLangOpts().CPlusPlus &&
4870       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4871     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4872       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4873           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4874         DeclaresAnything = false;
4875 
4876   if (!DS.isMissingDeclaratorOk()) {
4877     // Customize diagnostic for a typedef missing a name.
4878     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4879       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4880           << DS.getSourceRange();
4881     else
4882       DeclaresAnything = false;
4883   }
4884 
4885   if (DS.isModulePrivateSpecified() &&
4886       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4887     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4888       << Tag->getTagKind()
4889       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4890 
4891   ActOnDocumentableDecl(TagD);
4892 
4893   // C 6.7/2:
4894   //   A declaration [...] shall declare at least a declarator [...], a tag,
4895   //   or the members of an enumeration.
4896   // C++ [dcl.dcl]p3:
4897   //   [If there are no declarators], and except for the declaration of an
4898   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4899   //   names into the program, or shall redeclare a name introduced by a
4900   //   previous declaration.
4901   if (!DeclaresAnything) {
4902     // In C, we allow this as a (popular) extension / bug. Don't bother
4903     // producing further diagnostics for redundant qualifiers after this.
4904     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4905                                ? diag::err_no_declarators
4906                                : diag::ext_no_declarators)
4907         << DS.getSourceRange();
4908     return TagD;
4909   }
4910 
4911   // C++ [dcl.stc]p1:
4912   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4913   //   init-declarator-list of the declaration shall not be empty.
4914   // C++ [dcl.fct.spec]p1:
4915   //   If a cv-qualifier appears in a decl-specifier-seq, the
4916   //   init-declarator-list of the declaration shall not be empty.
4917   //
4918   // Spurious qualifiers here appear to be valid in C.
4919   unsigned DiagID = diag::warn_standalone_specifier;
4920   if (getLangOpts().CPlusPlus)
4921     DiagID = diag::ext_standalone_specifier;
4922 
4923   // Note that a linkage-specification sets a storage class, but
4924   // 'extern "C" struct foo;' is actually valid and not theoretically
4925   // useless.
4926   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4927     if (SCS == DeclSpec::SCS_mutable)
4928       // Since mutable is not a viable storage class specifier in C, there is
4929       // no reason to treat it as an extension. Instead, diagnose as an error.
4930       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4931     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4932       Diag(DS.getStorageClassSpecLoc(), DiagID)
4933         << DeclSpec::getSpecifierName(SCS);
4934   }
4935 
4936   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4937     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4938       << DeclSpec::getSpecifierName(TSCS);
4939   if (DS.getTypeQualifiers()) {
4940     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4941       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4942     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4943       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4944     // Restrict is covered above.
4945     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4946       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4947     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4948       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4949   }
4950 
4951   // Warn about ignored type attributes, for example:
4952   // __attribute__((aligned)) struct A;
4953   // Attributes should be placed after tag to apply to type declaration.
4954   if (!DS.getAttributes().empty()) {
4955     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4956     if (TypeSpecType == DeclSpec::TST_class ||
4957         TypeSpecType == DeclSpec::TST_struct ||
4958         TypeSpecType == DeclSpec::TST_interface ||
4959         TypeSpecType == DeclSpec::TST_union ||
4960         TypeSpecType == DeclSpec::TST_enum) {
4961       for (const ParsedAttr &AL : DS.getAttributes())
4962         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4963             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4964     }
4965   }
4966 
4967   return TagD;
4968 }
4969 
4970 /// We are trying to inject an anonymous member into the given scope;
4971 /// check if there's an existing declaration that can't be overloaded.
4972 ///
4973 /// \return true if this is a forbidden redeclaration
4974 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4975                                          Scope *S,
4976                                          DeclContext *Owner,
4977                                          DeclarationName Name,
4978                                          SourceLocation NameLoc,
4979                                          bool IsUnion) {
4980   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4981                  Sema::ForVisibleRedeclaration);
4982   if (!SemaRef.LookupName(R, S)) return false;
4983 
4984   // Pick a representative declaration.
4985   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4986   assert(PrevDecl && "Expected a non-null Decl");
4987 
4988   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4989     return false;
4990 
4991   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4992     << IsUnion << Name;
4993   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4994 
4995   return true;
4996 }
4997 
4998 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4999 /// anonymous struct or union AnonRecord into the owning context Owner
5000 /// and scope S. This routine will be invoked just after we realize
5001 /// that an unnamed union or struct is actually an anonymous union or
5002 /// struct, e.g.,
5003 ///
5004 /// @code
5005 /// union {
5006 ///   int i;
5007 ///   float f;
5008 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5009 ///    // f into the surrounding scope.x
5010 /// @endcode
5011 ///
5012 /// This routine is recursive, injecting the names of nested anonymous
5013 /// structs/unions into the owning context and scope as well.
5014 static bool
5015 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5016                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5017                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5018   bool Invalid = false;
5019 
5020   // Look every FieldDecl and IndirectFieldDecl with a name.
5021   for (auto *D : AnonRecord->decls()) {
5022     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5023         cast<NamedDecl>(D)->getDeclName()) {
5024       ValueDecl *VD = cast<ValueDecl>(D);
5025       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5026                                        VD->getLocation(),
5027                                        AnonRecord->isUnion())) {
5028         // C++ [class.union]p2:
5029         //   The names of the members of an anonymous union shall be
5030         //   distinct from the names of any other entity in the
5031         //   scope in which the anonymous union is declared.
5032         Invalid = true;
5033       } else {
5034         // C++ [class.union]p2:
5035         //   For the purpose of name lookup, after the anonymous union
5036         //   definition, the members of the anonymous union are
5037         //   considered to have been defined in the scope in which the
5038         //   anonymous union is declared.
5039         unsigned OldChainingSize = Chaining.size();
5040         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5041           Chaining.append(IF->chain_begin(), IF->chain_end());
5042         else
5043           Chaining.push_back(VD);
5044 
5045         assert(Chaining.size() >= 2);
5046         NamedDecl **NamedChain =
5047           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5048         for (unsigned i = 0; i < Chaining.size(); i++)
5049           NamedChain[i] = Chaining[i];
5050 
5051         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5052             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5053             VD->getType(), {NamedChain, Chaining.size()});
5054 
5055         for (const auto *Attr : VD->attrs())
5056           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5057 
5058         IndirectField->setAccess(AS);
5059         IndirectField->setImplicit();
5060         SemaRef.PushOnScopeChains(IndirectField, S);
5061 
5062         // That includes picking up the appropriate access specifier.
5063         if (AS != AS_none) IndirectField->setAccess(AS);
5064 
5065         Chaining.resize(OldChainingSize);
5066       }
5067     }
5068   }
5069 
5070   return Invalid;
5071 }
5072 
5073 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5074 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5075 /// illegal input values are mapped to SC_None.
5076 static StorageClass
5077 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5078   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5079   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5080          "Parser allowed 'typedef' as storage class VarDecl.");
5081   switch (StorageClassSpec) {
5082   case DeclSpec::SCS_unspecified:    return SC_None;
5083   case DeclSpec::SCS_extern:
5084     if (DS.isExternInLinkageSpec())
5085       return SC_None;
5086     return SC_Extern;
5087   case DeclSpec::SCS_static:         return SC_Static;
5088   case DeclSpec::SCS_auto:           return SC_Auto;
5089   case DeclSpec::SCS_register:       return SC_Register;
5090   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5091     // Illegal SCSs map to None: error reporting is up to the caller.
5092   case DeclSpec::SCS_mutable:        // Fall through.
5093   case DeclSpec::SCS_typedef:        return SC_None;
5094   }
5095   llvm_unreachable("unknown storage class specifier");
5096 }
5097 
5098 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5099   assert(Record->hasInClassInitializer());
5100 
5101   for (const auto *I : Record->decls()) {
5102     const auto *FD = dyn_cast<FieldDecl>(I);
5103     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5104       FD = IFD->getAnonField();
5105     if (FD && FD->hasInClassInitializer())
5106       return FD->getLocation();
5107   }
5108 
5109   llvm_unreachable("couldn't find in-class initializer");
5110 }
5111 
5112 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5113                                       SourceLocation DefaultInitLoc) {
5114   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5115     return;
5116 
5117   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5118   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5119 }
5120 
5121 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5122                                       CXXRecordDecl *AnonUnion) {
5123   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5124     return;
5125 
5126   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5127 }
5128 
5129 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5130 /// anonymous structure or union. Anonymous unions are a C++ feature
5131 /// (C++ [class.union]) and a C11 feature; anonymous structures
5132 /// are a C11 feature and GNU C++ extension.
5133 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5134                                         AccessSpecifier AS,
5135                                         RecordDecl *Record,
5136                                         const PrintingPolicy &Policy) {
5137   DeclContext *Owner = Record->getDeclContext();
5138 
5139   // Diagnose whether this anonymous struct/union is an extension.
5140   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5141     Diag(Record->getLocation(), diag::ext_anonymous_union);
5142   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5143     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5144   else if (!Record->isUnion() && !getLangOpts().C11)
5145     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5146 
5147   // C and C++ require different kinds of checks for anonymous
5148   // structs/unions.
5149   bool Invalid = false;
5150   if (getLangOpts().CPlusPlus) {
5151     const char *PrevSpec = nullptr;
5152     if (Record->isUnion()) {
5153       // C++ [class.union]p6:
5154       // C++17 [class.union.anon]p2:
5155       //   Anonymous unions declared in a named namespace or in the
5156       //   global namespace shall be declared static.
5157       unsigned DiagID;
5158       DeclContext *OwnerScope = Owner->getRedeclContext();
5159       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5160           (OwnerScope->isTranslationUnit() ||
5161            (OwnerScope->isNamespace() &&
5162             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5163         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5164           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5165 
5166         // Recover by adding 'static'.
5167         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5168                                PrevSpec, DiagID, Policy);
5169       }
5170       // C++ [class.union]p6:
5171       //   A storage class is not allowed in a declaration of an
5172       //   anonymous union in a class scope.
5173       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5174                isa<RecordDecl>(Owner)) {
5175         Diag(DS.getStorageClassSpecLoc(),
5176              diag::err_anonymous_union_with_storage_spec)
5177           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5178 
5179         // Recover by removing the storage specifier.
5180         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5181                                SourceLocation(),
5182                                PrevSpec, DiagID, Context.getPrintingPolicy());
5183       }
5184     }
5185 
5186     // Ignore const/volatile/restrict qualifiers.
5187     if (DS.getTypeQualifiers()) {
5188       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5189         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5190           << Record->isUnion() << "const"
5191           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5192       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5193         Diag(DS.getVolatileSpecLoc(),
5194              diag::ext_anonymous_struct_union_qualified)
5195           << Record->isUnion() << "volatile"
5196           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5197       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5198         Diag(DS.getRestrictSpecLoc(),
5199              diag::ext_anonymous_struct_union_qualified)
5200           << Record->isUnion() << "restrict"
5201           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5202       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5203         Diag(DS.getAtomicSpecLoc(),
5204              diag::ext_anonymous_struct_union_qualified)
5205           << Record->isUnion() << "_Atomic"
5206           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5207       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5208         Diag(DS.getUnalignedSpecLoc(),
5209              diag::ext_anonymous_struct_union_qualified)
5210           << Record->isUnion() << "__unaligned"
5211           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5212 
5213       DS.ClearTypeQualifiers();
5214     }
5215 
5216     // C++ [class.union]p2:
5217     //   The member-specification of an anonymous union shall only
5218     //   define non-static data members. [Note: nested types and
5219     //   functions cannot be declared within an anonymous union. ]
5220     for (auto *Mem : Record->decls()) {
5221       // Ignore invalid declarations; we already diagnosed them.
5222       if (Mem->isInvalidDecl())
5223         continue;
5224 
5225       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5226         // C++ [class.union]p3:
5227         //   An anonymous union shall not have private or protected
5228         //   members (clause 11).
5229         assert(FD->getAccess() != AS_none);
5230         if (FD->getAccess() != AS_public) {
5231           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5232             << Record->isUnion() << (FD->getAccess() == AS_protected);
5233           Invalid = true;
5234         }
5235 
5236         // C++ [class.union]p1
5237         //   An object of a class with a non-trivial constructor, a non-trivial
5238         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5239         //   assignment operator cannot be a member of a union, nor can an
5240         //   array of such objects.
5241         if (CheckNontrivialField(FD))
5242           Invalid = true;
5243       } else if (Mem->isImplicit()) {
5244         // Any implicit members are fine.
5245       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5246         // This is a type that showed up in an
5247         // elaborated-type-specifier inside the anonymous struct or
5248         // union, but which actually declares a type outside of the
5249         // anonymous struct or union. It's okay.
5250       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5251         if (!MemRecord->isAnonymousStructOrUnion() &&
5252             MemRecord->getDeclName()) {
5253           // Visual C++ allows type definition in anonymous struct or union.
5254           if (getLangOpts().MicrosoftExt)
5255             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5256               << Record->isUnion();
5257           else {
5258             // This is a nested type declaration.
5259             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5260               << Record->isUnion();
5261             Invalid = true;
5262           }
5263         } else {
5264           // This is an anonymous type definition within another anonymous type.
5265           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5266           // not part of standard C++.
5267           Diag(MemRecord->getLocation(),
5268                diag::ext_anonymous_record_with_anonymous_type)
5269             << Record->isUnion();
5270         }
5271       } else if (isa<AccessSpecDecl>(Mem)) {
5272         // Any access specifier is fine.
5273       } else if (isa<StaticAssertDecl>(Mem)) {
5274         // In C++1z, static_assert declarations are also fine.
5275       } else {
5276         // We have something that isn't a non-static data
5277         // member. Complain about it.
5278         unsigned DK = diag::err_anonymous_record_bad_member;
5279         if (isa<TypeDecl>(Mem))
5280           DK = diag::err_anonymous_record_with_type;
5281         else if (isa<FunctionDecl>(Mem))
5282           DK = diag::err_anonymous_record_with_function;
5283         else if (isa<VarDecl>(Mem))
5284           DK = diag::err_anonymous_record_with_static;
5285 
5286         // Visual C++ allows type definition in anonymous struct or union.
5287         if (getLangOpts().MicrosoftExt &&
5288             DK == diag::err_anonymous_record_with_type)
5289           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5290             << Record->isUnion();
5291         else {
5292           Diag(Mem->getLocation(), DK) << Record->isUnion();
5293           Invalid = true;
5294         }
5295       }
5296     }
5297 
5298     // C++11 [class.union]p8 (DR1460):
5299     //   At most one variant member of a union may have a
5300     //   brace-or-equal-initializer.
5301     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5302         Owner->isRecord())
5303       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5304                                 cast<CXXRecordDecl>(Record));
5305   }
5306 
5307   if (!Record->isUnion() && !Owner->isRecord()) {
5308     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5309       << getLangOpts().CPlusPlus;
5310     Invalid = true;
5311   }
5312 
5313   // C++ [dcl.dcl]p3:
5314   //   [If there are no declarators], and except for the declaration of an
5315   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5316   //   names into the program
5317   // C++ [class.mem]p2:
5318   //   each such member-declaration shall either declare at least one member
5319   //   name of the class or declare at least one unnamed bit-field
5320   //
5321   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5322   if (getLangOpts().CPlusPlus && Record->field_empty())
5323     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5324 
5325   // Mock up a declarator.
5326   Declarator Dc(DS, DeclaratorContext::Member);
5327   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5328   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5329 
5330   // Create a declaration for this anonymous struct/union.
5331   NamedDecl *Anon = nullptr;
5332   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5333     Anon = FieldDecl::Create(
5334         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5335         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5336         /*BitWidth=*/nullptr, /*Mutable=*/false,
5337         /*InitStyle=*/ICIS_NoInit);
5338     Anon->setAccess(AS);
5339     ProcessDeclAttributes(S, Anon, Dc);
5340 
5341     if (getLangOpts().CPlusPlus)
5342       FieldCollector->Add(cast<FieldDecl>(Anon));
5343   } else {
5344     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5345     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5346     if (SCSpec == DeclSpec::SCS_mutable) {
5347       // mutable can only appear on non-static class members, so it's always
5348       // an error here
5349       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5350       Invalid = true;
5351       SC = SC_None;
5352     }
5353 
5354     assert(DS.getAttributes().empty() && "No attribute expected");
5355     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5356                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5357                            Context.getTypeDeclType(Record), TInfo, SC);
5358 
5359     // Default-initialize the implicit variable. This initialization will be
5360     // trivial in almost all cases, except if a union member has an in-class
5361     // initializer:
5362     //   union { int n = 0; };
5363     ActOnUninitializedDecl(Anon);
5364   }
5365   Anon->setImplicit();
5366 
5367   // Mark this as an anonymous struct/union type.
5368   Record->setAnonymousStructOrUnion(true);
5369 
5370   // Add the anonymous struct/union object to the current
5371   // context. We'll be referencing this object when we refer to one of
5372   // its members.
5373   Owner->addDecl(Anon);
5374 
5375   // Inject the members of the anonymous struct/union into the owning
5376   // context and into the identifier resolver chain for name lookup
5377   // purposes.
5378   SmallVector<NamedDecl*, 2> Chain;
5379   Chain.push_back(Anon);
5380 
5381   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5382     Invalid = true;
5383 
5384   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5385     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5386       MangleNumberingContext *MCtx;
5387       Decl *ManglingContextDecl;
5388       std::tie(MCtx, ManglingContextDecl) =
5389           getCurrentMangleNumberContext(NewVD->getDeclContext());
5390       if (MCtx) {
5391         Context.setManglingNumber(
5392             NewVD, MCtx->getManglingNumber(
5393                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5394         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5395       }
5396     }
5397   }
5398 
5399   if (Invalid)
5400     Anon->setInvalidDecl();
5401 
5402   return Anon;
5403 }
5404 
5405 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5406 /// Microsoft C anonymous structure.
5407 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5408 /// Example:
5409 ///
5410 /// struct A { int a; };
5411 /// struct B { struct A; int b; };
5412 ///
5413 /// void foo() {
5414 ///   B var;
5415 ///   var.a = 3;
5416 /// }
5417 ///
5418 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5419                                            RecordDecl *Record) {
5420   assert(Record && "expected a record!");
5421 
5422   // Mock up a declarator.
5423   Declarator Dc(DS, DeclaratorContext::TypeName);
5424   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5425   assert(TInfo && "couldn't build declarator info for anonymous struct");
5426 
5427   auto *ParentDecl = cast<RecordDecl>(CurContext);
5428   QualType RecTy = Context.getTypeDeclType(Record);
5429 
5430   // Create a declaration for this anonymous struct.
5431   NamedDecl *Anon =
5432       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5433                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5434                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5435                         /*InitStyle=*/ICIS_NoInit);
5436   Anon->setImplicit();
5437 
5438   // Add the anonymous struct object to the current context.
5439   CurContext->addDecl(Anon);
5440 
5441   // Inject the members of the anonymous struct into the current
5442   // context and into the identifier resolver chain for name lookup
5443   // purposes.
5444   SmallVector<NamedDecl*, 2> Chain;
5445   Chain.push_back(Anon);
5446 
5447   RecordDecl *RecordDef = Record->getDefinition();
5448   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5449                                diag::err_field_incomplete_or_sizeless) ||
5450       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5451                                           AS_none, Chain)) {
5452     Anon->setInvalidDecl();
5453     ParentDecl->setInvalidDecl();
5454   }
5455 
5456   return Anon;
5457 }
5458 
5459 /// GetNameForDeclarator - Determine the full declaration name for the
5460 /// given Declarator.
5461 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5462   return GetNameFromUnqualifiedId(D.getName());
5463 }
5464 
5465 /// Retrieves the declaration name from a parsed unqualified-id.
5466 DeclarationNameInfo
5467 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5468   DeclarationNameInfo NameInfo;
5469   NameInfo.setLoc(Name.StartLocation);
5470 
5471   switch (Name.getKind()) {
5472 
5473   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5474   case UnqualifiedIdKind::IK_Identifier:
5475     NameInfo.setName(Name.Identifier);
5476     return NameInfo;
5477 
5478   case UnqualifiedIdKind::IK_DeductionGuideName: {
5479     // C++ [temp.deduct.guide]p3:
5480     //   The simple-template-id shall name a class template specialization.
5481     //   The template-name shall be the same identifier as the template-name
5482     //   of the simple-template-id.
5483     // These together intend to imply that the template-name shall name a
5484     // class template.
5485     // FIXME: template<typename T> struct X {};
5486     //        template<typename T> using Y = X<T>;
5487     //        Y(int) -> Y<int>;
5488     //   satisfies these rules but does not name a class template.
5489     TemplateName TN = Name.TemplateName.get().get();
5490     auto *Template = TN.getAsTemplateDecl();
5491     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5492       Diag(Name.StartLocation,
5493            diag::err_deduction_guide_name_not_class_template)
5494         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5495       if (Template)
5496         Diag(Template->getLocation(), diag::note_template_decl_here);
5497       return DeclarationNameInfo();
5498     }
5499 
5500     NameInfo.setName(
5501         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5502     return NameInfo;
5503   }
5504 
5505   case UnqualifiedIdKind::IK_OperatorFunctionId:
5506     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5507                                            Name.OperatorFunctionId.Operator));
5508     NameInfo.setCXXOperatorNameRange(SourceRange(
5509         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5510     return NameInfo;
5511 
5512   case UnqualifiedIdKind::IK_LiteralOperatorId:
5513     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5514                                                            Name.Identifier));
5515     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5516     return NameInfo;
5517 
5518   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5519     TypeSourceInfo *TInfo;
5520     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5521     if (Ty.isNull())
5522       return DeclarationNameInfo();
5523     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5524                                                Context.getCanonicalType(Ty)));
5525     NameInfo.setNamedTypeInfo(TInfo);
5526     return NameInfo;
5527   }
5528 
5529   case UnqualifiedIdKind::IK_ConstructorName: {
5530     TypeSourceInfo *TInfo;
5531     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5532     if (Ty.isNull())
5533       return DeclarationNameInfo();
5534     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5535                                               Context.getCanonicalType(Ty)));
5536     NameInfo.setNamedTypeInfo(TInfo);
5537     return NameInfo;
5538   }
5539 
5540   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5541     // In well-formed code, we can only have a constructor
5542     // template-id that refers to the current context, so go there
5543     // to find the actual type being constructed.
5544     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5545     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5546       return DeclarationNameInfo();
5547 
5548     // Determine the type of the class being constructed.
5549     QualType CurClassType = Context.getTypeDeclType(CurClass);
5550 
5551     // FIXME: Check two things: that the template-id names the same type as
5552     // CurClassType, and that the template-id does not occur when the name
5553     // was qualified.
5554 
5555     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5556                                     Context.getCanonicalType(CurClassType)));
5557     // FIXME: should we retrieve TypeSourceInfo?
5558     NameInfo.setNamedTypeInfo(nullptr);
5559     return NameInfo;
5560   }
5561 
5562   case UnqualifiedIdKind::IK_DestructorName: {
5563     TypeSourceInfo *TInfo;
5564     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5565     if (Ty.isNull())
5566       return DeclarationNameInfo();
5567     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5568                                               Context.getCanonicalType(Ty)));
5569     NameInfo.setNamedTypeInfo(TInfo);
5570     return NameInfo;
5571   }
5572 
5573   case UnqualifiedIdKind::IK_TemplateId: {
5574     TemplateName TName = Name.TemplateId->Template.get();
5575     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5576     return Context.getNameForTemplate(TName, TNameLoc);
5577   }
5578 
5579   } // switch (Name.getKind())
5580 
5581   llvm_unreachable("Unknown name kind");
5582 }
5583 
5584 static QualType getCoreType(QualType Ty) {
5585   do {
5586     if (Ty->isPointerType() || Ty->isReferenceType())
5587       Ty = Ty->getPointeeType();
5588     else if (Ty->isArrayType())
5589       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5590     else
5591       return Ty.withoutLocalFastQualifiers();
5592   } while (true);
5593 }
5594 
5595 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5596 /// and Definition have "nearly" matching parameters. This heuristic is
5597 /// used to improve diagnostics in the case where an out-of-line function
5598 /// definition doesn't match any declaration within the class or namespace.
5599 /// Also sets Params to the list of indices to the parameters that differ
5600 /// between the declaration and the definition. If hasSimilarParameters
5601 /// returns true and Params is empty, then all of the parameters match.
5602 static bool hasSimilarParameters(ASTContext &Context,
5603                                      FunctionDecl *Declaration,
5604                                      FunctionDecl *Definition,
5605                                      SmallVectorImpl<unsigned> &Params) {
5606   Params.clear();
5607   if (Declaration->param_size() != Definition->param_size())
5608     return false;
5609   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5610     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5611     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5612 
5613     // The parameter types are identical
5614     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5615       continue;
5616 
5617     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5618     QualType DefParamBaseTy = getCoreType(DefParamTy);
5619     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5620     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5621 
5622     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5623         (DeclTyName && DeclTyName == DefTyName))
5624       Params.push_back(Idx);
5625     else  // The two parameters aren't even close
5626       return false;
5627   }
5628 
5629   return true;
5630 }
5631 
5632 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5633 /// declarator needs to be rebuilt in the current instantiation.
5634 /// Any bits of declarator which appear before the name are valid for
5635 /// consideration here.  That's specifically the type in the decl spec
5636 /// and the base type in any member-pointer chunks.
5637 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5638                                                     DeclarationName Name) {
5639   // The types we specifically need to rebuild are:
5640   //   - typenames, typeofs, and decltypes
5641   //   - types which will become injected class names
5642   // Of course, we also need to rebuild any type referencing such a
5643   // type.  It's safest to just say "dependent", but we call out a
5644   // few cases here.
5645 
5646   DeclSpec &DS = D.getMutableDeclSpec();
5647   switch (DS.getTypeSpecType()) {
5648   case DeclSpec::TST_typename:
5649   case DeclSpec::TST_typeofType:
5650   case DeclSpec::TST_underlyingType:
5651   case DeclSpec::TST_atomic: {
5652     // Grab the type from the parser.
5653     TypeSourceInfo *TSI = nullptr;
5654     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5655     if (T.isNull() || !T->isInstantiationDependentType()) break;
5656 
5657     // Make sure there's a type source info.  This isn't really much
5658     // of a waste; most dependent types should have type source info
5659     // attached already.
5660     if (!TSI)
5661       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5662 
5663     // Rebuild the type in the current instantiation.
5664     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5665     if (!TSI) return true;
5666 
5667     // Store the new type back in the decl spec.
5668     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5669     DS.UpdateTypeRep(LocType);
5670     break;
5671   }
5672 
5673   case DeclSpec::TST_decltype:
5674   case DeclSpec::TST_typeofExpr: {
5675     Expr *E = DS.getRepAsExpr();
5676     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5677     if (Result.isInvalid()) return true;
5678     DS.UpdateExprRep(Result.get());
5679     break;
5680   }
5681 
5682   default:
5683     // Nothing to do for these decl specs.
5684     break;
5685   }
5686 
5687   // It doesn't matter what order we do this in.
5688   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5689     DeclaratorChunk &Chunk = D.getTypeObject(I);
5690 
5691     // The only type information in the declarator which can come
5692     // before the declaration name is the base type of a member
5693     // pointer.
5694     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5695       continue;
5696 
5697     // Rebuild the scope specifier in-place.
5698     CXXScopeSpec &SS = Chunk.Mem.Scope();
5699     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5700       return true;
5701   }
5702 
5703   return false;
5704 }
5705 
5706 /// Returns true if the declaration is declared in a system header or from a
5707 /// system macro.
5708 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5709   return SM.isInSystemHeader(D->getLocation()) ||
5710          SM.isInSystemMacro(D->getLocation());
5711 }
5712 
5713 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5714   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5715   // of system decl.
5716   if (D->getPreviousDecl() || D->isImplicit())
5717     return;
5718   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5719   if (Status != ReservedIdentifierStatus::NotReserved &&
5720       !isFromSystemHeader(Context.getSourceManager(), D)) {
5721     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5722         << D << static_cast<int>(Status);
5723   }
5724 }
5725 
5726 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5727   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5728   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5729 
5730   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5731       Dcl && Dcl->getDeclContext()->isFileContext())
5732     Dcl->setTopLevelDeclInObjCContainer();
5733 
5734   return Dcl;
5735 }
5736 
5737 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5738 ///   If T is the name of a class, then each of the following shall have a
5739 ///   name different from T:
5740 ///     - every static data member of class T;
5741 ///     - every member function of class T
5742 ///     - every member of class T that is itself a type;
5743 /// \returns true if the declaration name violates these rules.
5744 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5745                                    DeclarationNameInfo NameInfo) {
5746   DeclarationName Name = NameInfo.getName();
5747 
5748   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5749   while (Record && Record->isAnonymousStructOrUnion())
5750     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5751   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5752     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5753     return true;
5754   }
5755 
5756   return false;
5757 }
5758 
5759 /// Diagnose a declaration whose declarator-id has the given
5760 /// nested-name-specifier.
5761 ///
5762 /// \param SS The nested-name-specifier of the declarator-id.
5763 ///
5764 /// \param DC The declaration context to which the nested-name-specifier
5765 /// resolves.
5766 ///
5767 /// \param Name The name of the entity being declared.
5768 ///
5769 /// \param Loc The location of the name of the entity being declared.
5770 ///
5771 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5772 /// we're declaring an explicit / partial specialization / instantiation.
5773 ///
5774 /// \returns true if we cannot safely recover from this error, false otherwise.
5775 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5776                                         DeclarationName Name,
5777                                         SourceLocation Loc, bool IsTemplateId) {
5778   DeclContext *Cur = CurContext;
5779   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5780     Cur = Cur->getParent();
5781 
5782   // If the user provided a superfluous scope specifier that refers back to the
5783   // class in which the entity is already declared, diagnose and ignore it.
5784   //
5785   // class X {
5786   //   void X::f();
5787   // };
5788   //
5789   // Note, it was once ill-formed to give redundant qualification in all
5790   // contexts, but that rule was removed by DR482.
5791   if (Cur->Equals(DC)) {
5792     if (Cur->isRecord()) {
5793       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5794                                       : diag::err_member_extra_qualification)
5795         << Name << FixItHint::CreateRemoval(SS.getRange());
5796       SS.clear();
5797     } else {
5798       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5799     }
5800     return false;
5801   }
5802 
5803   // Check whether the qualifying scope encloses the scope of the original
5804   // declaration. For a template-id, we perform the checks in
5805   // CheckTemplateSpecializationScope.
5806   if (!Cur->Encloses(DC) && !IsTemplateId) {
5807     if (Cur->isRecord())
5808       Diag(Loc, diag::err_member_qualification)
5809         << Name << SS.getRange();
5810     else if (isa<TranslationUnitDecl>(DC))
5811       Diag(Loc, diag::err_invalid_declarator_global_scope)
5812         << Name << SS.getRange();
5813     else if (isa<FunctionDecl>(Cur))
5814       Diag(Loc, diag::err_invalid_declarator_in_function)
5815         << Name << SS.getRange();
5816     else if (isa<BlockDecl>(Cur))
5817       Diag(Loc, diag::err_invalid_declarator_in_block)
5818         << Name << SS.getRange();
5819     else if (isa<ExportDecl>(Cur)) {
5820       if (!isa<NamespaceDecl>(DC))
5821         Diag(Loc, diag::err_export_non_namespace_scope_name)
5822             << Name << SS.getRange();
5823       else
5824         // The cases that DC is not NamespaceDecl should be handled in
5825         // CheckRedeclarationExported.
5826         return false;
5827     } else
5828       Diag(Loc, diag::err_invalid_declarator_scope)
5829       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5830 
5831     return true;
5832   }
5833 
5834   if (Cur->isRecord()) {
5835     // Cannot qualify members within a class.
5836     Diag(Loc, diag::err_member_qualification)
5837       << Name << SS.getRange();
5838     SS.clear();
5839 
5840     // C++ constructors and destructors with incorrect scopes can break
5841     // our AST invariants by having the wrong underlying types. If
5842     // that's the case, then drop this declaration entirely.
5843     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5844          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5845         !Context.hasSameType(Name.getCXXNameType(),
5846                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5847       return true;
5848 
5849     return false;
5850   }
5851 
5852   // C++11 [dcl.meaning]p1:
5853   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5854   //   not begin with a decltype-specifer"
5855   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5856   while (SpecLoc.getPrefix())
5857     SpecLoc = SpecLoc.getPrefix();
5858   if (isa_and_nonnull<DecltypeType>(
5859           SpecLoc.getNestedNameSpecifier()->getAsType()))
5860     Diag(Loc, diag::err_decltype_in_declarator)
5861       << SpecLoc.getTypeLoc().getSourceRange();
5862 
5863   return false;
5864 }
5865 
5866 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5867                                   MultiTemplateParamsArg TemplateParamLists) {
5868   // TODO: consider using NameInfo for diagnostic.
5869   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5870   DeclarationName Name = NameInfo.getName();
5871 
5872   // All of these full declarators require an identifier.  If it doesn't have
5873   // one, the ParsedFreeStandingDeclSpec action should be used.
5874   if (D.isDecompositionDeclarator()) {
5875     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5876   } else if (!Name) {
5877     if (!D.isInvalidType())  // Reject this if we think it is valid.
5878       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5879           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5880     return nullptr;
5881   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5882     return nullptr;
5883 
5884   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5885   // we find one that is.
5886   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5887          (S->getFlags() & Scope::TemplateParamScope) != 0)
5888     S = S->getParent();
5889 
5890   DeclContext *DC = CurContext;
5891   if (D.getCXXScopeSpec().isInvalid())
5892     D.setInvalidType();
5893   else if (D.getCXXScopeSpec().isSet()) {
5894     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5895                                         UPPC_DeclarationQualifier))
5896       return nullptr;
5897 
5898     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5899     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5900     if (!DC || isa<EnumDecl>(DC)) {
5901       // If we could not compute the declaration context, it's because the
5902       // declaration context is dependent but does not refer to a class,
5903       // class template, or class template partial specialization. Complain
5904       // and return early, to avoid the coming semantic disaster.
5905       Diag(D.getIdentifierLoc(),
5906            diag::err_template_qualified_declarator_no_match)
5907         << D.getCXXScopeSpec().getScopeRep()
5908         << D.getCXXScopeSpec().getRange();
5909       return nullptr;
5910     }
5911     bool IsDependentContext = DC->isDependentContext();
5912 
5913     if (!IsDependentContext &&
5914         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5915       return nullptr;
5916 
5917     // If a class is incomplete, do not parse entities inside it.
5918     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5919       Diag(D.getIdentifierLoc(),
5920            diag::err_member_def_undefined_record)
5921         << Name << DC << D.getCXXScopeSpec().getRange();
5922       return nullptr;
5923     }
5924     if (!D.getDeclSpec().isFriendSpecified()) {
5925       if (diagnoseQualifiedDeclaration(
5926               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5927               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5928         if (DC->isRecord())
5929           return nullptr;
5930 
5931         D.setInvalidType();
5932       }
5933     }
5934 
5935     // Check whether we need to rebuild the type of the given
5936     // declaration in the current instantiation.
5937     if (EnteringContext && IsDependentContext &&
5938         TemplateParamLists.size() != 0) {
5939       ContextRAII SavedContext(*this, DC);
5940       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5941         D.setInvalidType();
5942     }
5943   }
5944 
5945   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5946   QualType R = TInfo->getType();
5947 
5948   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5949                                       UPPC_DeclarationType))
5950     D.setInvalidType();
5951 
5952   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5953                         forRedeclarationInCurContext());
5954 
5955   // See if this is a redefinition of a variable in the same scope.
5956   if (!D.getCXXScopeSpec().isSet()) {
5957     bool IsLinkageLookup = false;
5958     bool CreateBuiltins = false;
5959 
5960     // If the declaration we're planning to build will be a function
5961     // or object with linkage, then look for another declaration with
5962     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5963     //
5964     // If the declaration we're planning to build will be declared with
5965     // external linkage in the translation unit, create any builtin with
5966     // the same name.
5967     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5968       /* Do nothing*/;
5969     else if (CurContext->isFunctionOrMethod() &&
5970              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5971               R->isFunctionType())) {
5972       IsLinkageLookup = true;
5973       CreateBuiltins =
5974           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5975     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5976                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5977       CreateBuiltins = true;
5978 
5979     if (IsLinkageLookup) {
5980       Previous.clear(LookupRedeclarationWithLinkage);
5981       Previous.setRedeclarationKind(ForExternalRedeclaration);
5982     }
5983 
5984     LookupName(Previous, S, CreateBuiltins);
5985   } else { // Something like "int foo::x;"
5986     LookupQualifiedName(Previous, DC);
5987 
5988     // C++ [dcl.meaning]p1:
5989     //   When the declarator-id is qualified, the declaration shall refer to a
5990     //  previously declared member of the class or namespace to which the
5991     //  qualifier refers (or, in the case of a namespace, of an element of the
5992     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5993     //  thereof; [...]
5994     //
5995     // Note that we already checked the context above, and that we do not have
5996     // enough information to make sure that Previous contains the declaration
5997     // we want to match. For example, given:
5998     //
5999     //   class X {
6000     //     void f();
6001     //     void f(float);
6002     //   };
6003     //
6004     //   void X::f(int) { } // ill-formed
6005     //
6006     // In this case, Previous will point to the overload set
6007     // containing the two f's declared in X, but neither of them
6008     // matches.
6009 
6010     // C++ [dcl.meaning]p1:
6011     //   [...] the member shall not merely have been introduced by a
6012     //   using-declaration in the scope of the class or namespace nominated by
6013     //   the nested-name-specifier of the declarator-id.
6014     RemoveUsingDecls(Previous);
6015   }
6016 
6017   if (Previous.isSingleResult() &&
6018       Previous.getFoundDecl()->isTemplateParameter()) {
6019     // Maybe we will complain about the shadowed template parameter.
6020     if (!D.isInvalidType())
6021       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6022                                       Previous.getFoundDecl());
6023 
6024     // Just pretend that we didn't see the previous declaration.
6025     Previous.clear();
6026   }
6027 
6028   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6029     // Forget that the previous declaration is the injected-class-name.
6030     Previous.clear();
6031 
6032   // In C++, the previous declaration we find might be a tag type
6033   // (class or enum). In this case, the new declaration will hide the
6034   // tag type. Note that this applies to functions, function templates, and
6035   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6036   if (Previous.isSingleTagDecl() &&
6037       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6038       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6039     Previous.clear();
6040 
6041   // Check that there are no default arguments other than in the parameters
6042   // of a function declaration (C++ only).
6043   if (getLangOpts().CPlusPlus)
6044     CheckExtraCXXDefaultArguments(D);
6045 
6046   NamedDecl *New;
6047 
6048   bool AddToScope = true;
6049   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6050     if (TemplateParamLists.size()) {
6051       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6052       return nullptr;
6053     }
6054 
6055     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6056   } else if (R->isFunctionType()) {
6057     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6058                                   TemplateParamLists,
6059                                   AddToScope);
6060   } else {
6061     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6062                                   AddToScope);
6063   }
6064 
6065   if (!New)
6066     return nullptr;
6067 
6068   // If this has an identifier and is not a function template specialization,
6069   // add it to the scope stack.
6070   if (New->getDeclName() && AddToScope)
6071     PushOnScopeChains(New, S);
6072 
6073   if (isInOpenMPDeclareTargetContext())
6074     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6075 
6076   return New;
6077 }
6078 
6079 /// Helper method to turn variable array types into constant array
6080 /// types in certain situations which would otherwise be errors (for
6081 /// GCC compatibility).
6082 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6083                                                     ASTContext &Context,
6084                                                     bool &SizeIsNegative,
6085                                                     llvm::APSInt &Oversized) {
6086   // This method tries to turn a variable array into a constant
6087   // array even when the size isn't an ICE.  This is necessary
6088   // for compatibility with code that depends on gcc's buggy
6089   // constant expression folding, like struct {char x[(int)(char*)2];}
6090   SizeIsNegative = false;
6091   Oversized = 0;
6092 
6093   if (T->isDependentType())
6094     return QualType();
6095 
6096   QualifierCollector Qs;
6097   const Type *Ty = Qs.strip(T);
6098 
6099   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6100     QualType Pointee = PTy->getPointeeType();
6101     QualType FixedType =
6102         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6103                                             Oversized);
6104     if (FixedType.isNull()) return FixedType;
6105     FixedType = Context.getPointerType(FixedType);
6106     return Qs.apply(Context, FixedType);
6107   }
6108   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6109     QualType Inner = PTy->getInnerType();
6110     QualType FixedType =
6111         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6112                                             Oversized);
6113     if (FixedType.isNull()) return FixedType;
6114     FixedType = Context.getParenType(FixedType);
6115     return Qs.apply(Context, FixedType);
6116   }
6117 
6118   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6119   if (!VLATy)
6120     return QualType();
6121 
6122   QualType ElemTy = VLATy->getElementType();
6123   if (ElemTy->isVariablyModifiedType()) {
6124     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6125                                                  SizeIsNegative, Oversized);
6126     if (ElemTy.isNull())
6127       return QualType();
6128   }
6129 
6130   Expr::EvalResult Result;
6131   if (!VLATy->getSizeExpr() ||
6132       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6133     return QualType();
6134 
6135   llvm::APSInt Res = Result.Val.getInt();
6136 
6137   // Check whether the array size is negative.
6138   if (Res.isSigned() && Res.isNegative()) {
6139     SizeIsNegative = true;
6140     return QualType();
6141   }
6142 
6143   // Check whether the array is too large to be addressed.
6144   unsigned ActiveSizeBits =
6145       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6146        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6147           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6148           : Res.getActiveBits();
6149   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6150     Oversized = Res;
6151     return QualType();
6152   }
6153 
6154   QualType FoldedArrayType = Context.getConstantArrayType(
6155       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6156   return Qs.apply(Context, FoldedArrayType);
6157 }
6158 
6159 static void
6160 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6161   SrcTL = SrcTL.getUnqualifiedLoc();
6162   DstTL = DstTL.getUnqualifiedLoc();
6163   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6164     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6165     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6166                                       DstPTL.getPointeeLoc());
6167     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6168     return;
6169   }
6170   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6171     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6172     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6173                                       DstPTL.getInnerLoc());
6174     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6175     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6176     return;
6177   }
6178   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6179   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6180   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6181   TypeLoc DstElemTL = DstATL.getElementLoc();
6182   if (VariableArrayTypeLoc SrcElemATL =
6183           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6184     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6185     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6186   } else {
6187     DstElemTL.initializeFullCopy(SrcElemTL);
6188   }
6189   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6190   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6191   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6192 }
6193 
6194 /// Helper method to turn variable array types into constant array
6195 /// types in certain situations which would otherwise be errors (for
6196 /// GCC compatibility).
6197 static TypeSourceInfo*
6198 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6199                                               ASTContext &Context,
6200                                               bool &SizeIsNegative,
6201                                               llvm::APSInt &Oversized) {
6202   QualType FixedTy
6203     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6204                                           SizeIsNegative, Oversized);
6205   if (FixedTy.isNull())
6206     return nullptr;
6207   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6208   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6209                                     FixedTInfo->getTypeLoc());
6210   return FixedTInfo;
6211 }
6212 
6213 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6214 /// true if we were successful.
6215 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6216                                            QualType &T, SourceLocation Loc,
6217                                            unsigned FailedFoldDiagID) {
6218   bool SizeIsNegative;
6219   llvm::APSInt Oversized;
6220   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6221       TInfo, Context, SizeIsNegative, Oversized);
6222   if (FixedTInfo) {
6223     Diag(Loc, diag::ext_vla_folded_to_constant);
6224     TInfo = FixedTInfo;
6225     T = FixedTInfo->getType();
6226     return true;
6227   }
6228 
6229   if (SizeIsNegative)
6230     Diag(Loc, diag::err_typecheck_negative_array_size);
6231   else if (Oversized.getBoolValue())
6232     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6233   else if (FailedFoldDiagID)
6234     Diag(Loc, FailedFoldDiagID);
6235   return false;
6236 }
6237 
6238 /// Register the given locally-scoped extern "C" declaration so
6239 /// that it can be found later for redeclarations. We include any extern "C"
6240 /// declaration that is not visible in the translation unit here, not just
6241 /// function-scope declarations.
6242 void
6243 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6244   if (!getLangOpts().CPlusPlus &&
6245       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6246     // Don't need to track declarations in the TU in C.
6247     return;
6248 
6249   // Note that we have a locally-scoped external with this name.
6250   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6251 }
6252 
6253 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6254   // FIXME: We can have multiple results via __attribute__((overloadable)).
6255   auto Result = Context.getExternCContextDecl()->lookup(Name);
6256   return Result.empty() ? nullptr : *Result.begin();
6257 }
6258 
6259 /// Diagnose function specifiers on a declaration of an identifier that
6260 /// does not identify a function.
6261 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6262   // FIXME: We should probably indicate the identifier in question to avoid
6263   // confusion for constructs like "virtual int a(), b;"
6264   if (DS.isVirtualSpecified())
6265     Diag(DS.getVirtualSpecLoc(),
6266          diag::err_virtual_non_function);
6267 
6268   if (DS.hasExplicitSpecifier())
6269     Diag(DS.getExplicitSpecLoc(),
6270          diag::err_explicit_non_function);
6271 
6272   if (DS.isNoreturnSpecified())
6273     Diag(DS.getNoreturnSpecLoc(),
6274          diag::err_noreturn_non_function);
6275 }
6276 
6277 NamedDecl*
6278 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6279                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6280   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6281   if (D.getCXXScopeSpec().isSet()) {
6282     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6283       << D.getCXXScopeSpec().getRange();
6284     D.setInvalidType();
6285     // Pretend we didn't see the scope specifier.
6286     DC = CurContext;
6287     Previous.clear();
6288   }
6289 
6290   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6291 
6292   if (D.getDeclSpec().isInlineSpecified())
6293     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6294         << getLangOpts().CPlusPlus17;
6295   if (D.getDeclSpec().hasConstexprSpecifier())
6296     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6297         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6298 
6299   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6300     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6301       Diag(D.getName().StartLocation,
6302            diag::err_deduction_guide_invalid_specifier)
6303           << "typedef";
6304     else
6305       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6306           << D.getName().getSourceRange();
6307     return nullptr;
6308   }
6309 
6310   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6311   if (!NewTD) return nullptr;
6312 
6313   // Handle attributes prior to checking for duplicates in MergeVarDecl
6314   ProcessDeclAttributes(S, NewTD, D);
6315 
6316   CheckTypedefForVariablyModifiedType(S, NewTD);
6317 
6318   bool Redeclaration = D.isRedeclaration();
6319   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6320   D.setRedeclaration(Redeclaration);
6321   return ND;
6322 }
6323 
6324 void
6325 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6326   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6327   // then it shall have block scope.
6328   // Note that variably modified types must be fixed before merging the decl so
6329   // that redeclarations will match.
6330   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6331   QualType T = TInfo->getType();
6332   if (T->isVariablyModifiedType()) {
6333     setFunctionHasBranchProtectedScope();
6334 
6335     if (S->getFnParent() == nullptr) {
6336       bool SizeIsNegative;
6337       llvm::APSInt Oversized;
6338       TypeSourceInfo *FixedTInfo =
6339         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6340                                                       SizeIsNegative,
6341                                                       Oversized);
6342       if (FixedTInfo) {
6343         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6344         NewTD->setTypeSourceInfo(FixedTInfo);
6345       } else {
6346         if (SizeIsNegative)
6347           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6348         else if (T->isVariableArrayType())
6349           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6350         else if (Oversized.getBoolValue())
6351           Diag(NewTD->getLocation(), diag::err_array_too_large)
6352             << toString(Oversized, 10);
6353         else
6354           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6355         NewTD->setInvalidDecl();
6356       }
6357     }
6358   }
6359 }
6360 
6361 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6362 /// declares a typedef-name, either using the 'typedef' type specifier or via
6363 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6364 NamedDecl*
6365 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6366                            LookupResult &Previous, bool &Redeclaration) {
6367 
6368   // Find the shadowed declaration before filtering for scope.
6369   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6370 
6371   // Merge the decl with the existing one if appropriate. If the decl is
6372   // in an outer scope, it isn't the same thing.
6373   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6374                        /*AllowInlineNamespace*/false);
6375   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6376   if (!Previous.empty()) {
6377     Redeclaration = true;
6378     MergeTypedefNameDecl(S, NewTD, Previous);
6379   } else {
6380     inferGslPointerAttribute(NewTD);
6381   }
6382 
6383   if (ShadowedDecl && !Redeclaration)
6384     CheckShadow(NewTD, ShadowedDecl, Previous);
6385 
6386   // If this is the C FILE type, notify the AST context.
6387   if (IdentifierInfo *II = NewTD->getIdentifier())
6388     if (!NewTD->isInvalidDecl() &&
6389         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6390       if (II->isStr("FILE"))
6391         Context.setFILEDecl(NewTD);
6392       else if (II->isStr("jmp_buf"))
6393         Context.setjmp_bufDecl(NewTD);
6394       else if (II->isStr("sigjmp_buf"))
6395         Context.setsigjmp_bufDecl(NewTD);
6396       else if (II->isStr("ucontext_t"))
6397         Context.setucontext_tDecl(NewTD);
6398     }
6399 
6400   return NewTD;
6401 }
6402 
6403 /// Determines whether the given declaration is an out-of-scope
6404 /// previous declaration.
6405 ///
6406 /// This routine should be invoked when name lookup has found a
6407 /// previous declaration (PrevDecl) that is not in the scope where a
6408 /// new declaration by the same name is being introduced. If the new
6409 /// declaration occurs in a local scope, previous declarations with
6410 /// linkage may still be considered previous declarations (C99
6411 /// 6.2.2p4-5, C++ [basic.link]p6).
6412 ///
6413 /// \param PrevDecl the previous declaration found by name
6414 /// lookup
6415 ///
6416 /// \param DC the context in which the new declaration is being
6417 /// declared.
6418 ///
6419 /// \returns true if PrevDecl is an out-of-scope previous declaration
6420 /// for a new delcaration with the same name.
6421 static bool
6422 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6423                                 ASTContext &Context) {
6424   if (!PrevDecl)
6425     return false;
6426 
6427   if (!PrevDecl->hasLinkage())
6428     return false;
6429 
6430   if (Context.getLangOpts().CPlusPlus) {
6431     // C++ [basic.link]p6:
6432     //   If there is a visible declaration of an entity with linkage
6433     //   having the same name and type, ignoring entities declared
6434     //   outside the innermost enclosing namespace scope, the block
6435     //   scope declaration declares that same entity and receives the
6436     //   linkage of the previous declaration.
6437     DeclContext *OuterContext = DC->getRedeclContext();
6438     if (!OuterContext->isFunctionOrMethod())
6439       // This rule only applies to block-scope declarations.
6440       return false;
6441 
6442     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6443     if (PrevOuterContext->isRecord())
6444       // We found a member function: ignore it.
6445       return false;
6446 
6447     // Find the innermost enclosing namespace for the new and
6448     // previous declarations.
6449     OuterContext = OuterContext->getEnclosingNamespaceContext();
6450     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6451 
6452     // The previous declaration is in a different namespace, so it
6453     // isn't the same function.
6454     if (!OuterContext->Equals(PrevOuterContext))
6455       return false;
6456   }
6457 
6458   return true;
6459 }
6460 
6461 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6462   CXXScopeSpec &SS = D.getCXXScopeSpec();
6463   if (!SS.isSet()) return;
6464   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6465 }
6466 
6467 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6468   QualType type = decl->getType();
6469   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6470   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6471     // Various kinds of declaration aren't allowed to be __autoreleasing.
6472     unsigned kind = -1U;
6473     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6474       if (var->hasAttr<BlocksAttr>())
6475         kind = 0; // __block
6476       else if (!var->hasLocalStorage())
6477         kind = 1; // global
6478     } else if (isa<ObjCIvarDecl>(decl)) {
6479       kind = 3; // ivar
6480     } else if (isa<FieldDecl>(decl)) {
6481       kind = 2; // field
6482     }
6483 
6484     if (kind != -1U) {
6485       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6486         << kind;
6487     }
6488   } else if (lifetime == Qualifiers::OCL_None) {
6489     // Try to infer lifetime.
6490     if (!type->isObjCLifetimeType())
6491       return false;
6492 
6493     lifetime = type->getObjCARCImplicitLifetime();
6494     type = Context.getLifetimeQualifiedType(type, lifetime);
6495     decl->setType(type);
6496   }
6497 
6498   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6499     // Thread-local variables cannot have lifetime.
6500     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6501         var->getTLSKind()) {
6502       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6503         << var->getType();
6504       return true;
6505     }
6506   }
6507 
6508   return false;
6509 }
6510 
6511 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6512   if (Decl->getType().hasAddressSpace())
6513     return;
6514   if (Decl->getType()->isDependentType())
6515     return;
6516   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6517     QualType Type = Var->getType();
6518     if (Type->isSamplerT() || Type->isVoidType())
6519       return;
6520     LangAS ImplAS = LangAS::opencl_private;
6521     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6522     // __opencl_c_program_scope_global_variables feature, the address space
6523     // for a variable at program scope or a static or extern variable inside
6524     // a function are inferred to be __global.
6525     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6526         Var->hasGlobalStorage())
6527       ImplAS = LangAS::opencl_global;
6528     // If the original type from a decayed type is an array type and that array
6529     // type has no address space yet, deduce it now.
6530     if (auto DT = dyn_cast<DecayedType>(Type)) {
6531       auto OrigTy = DT->getOriginalType();
6532       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6533         // Add the address space to the original array type and then propagate
6534         // that to the element type through `getAsArrayType`.
6535         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6536         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6537         // Re-generate the decayed type.
6538         Type = Context.getDecayedType(OrigTy);
6539       }
6540     }
6541     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6542     // Apply any qualifiers (including address space) from the array type to
6543     // the element type. This implements C99 6.7.3p8: "If the specification of
6544     // an array type includes any type qualifiers, the element type is so
6545     // qualified, not the array type."
6546     if (Type->isArrayType())
6547       Type = QualType(Context.getAsArrayType(Type), 0);
6548     Decl->setType(Type);
6549   }
6550 }
6551 
6552 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6553   // Ensure that an auto decl is deduced otherwise the checks below might cache
6554   // the wrong linkage.
6555   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6556 
6557   // 'weak' only applies to declarations with external linkage.
6558   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6559     if (!ND.isExternallyVisible()) {
6560       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6561       ND.dropAttr<WeakAttr>();
6562     }
6563   }
6564   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6565     if (ND.isExternallyVisible()) {
6566       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6567       ND.dropAttr<WeakRefAttr>();
6568       ND.dropAttr<AliasAttr>();
6569     }
6570   }
6571 
6572   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6573     if (VD->hasInit()) {
6574       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6575         assert(VD->isThisDeclarationADefinition() &&
6576                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6577         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6578         VD->dropAttr<AliasAttr>();
6579       }
6580     }
6581   }
6582 
6583   // 'selectany' only applies to externally visible variable declarations.
6584   // It does not apply to functions.
6585   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6586     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6587       S.Diag(Attr->getLocation(),
6588              diag::err_attribute_selectany_non_extern_data);
6589       ND.dropAttr<SelectAnyAttr>();
6590     }
6591   }
6592 
6593   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6594     auto *VD = dyn_cast<VarDecl>(&ND);
6595     bool IsAnonymousNS = false;
6596     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6597     if (VD) {
6598       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6599       while (NS && !IsAnonymousNS) {
6600         IsAnonymousNS = NS->isAnonymousNamespace();
6601         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6602       }
6603     }
6604     // dll attributes require external linkage. Static locals may have external
6605     // linkage but still cannot be explicitly imported or exported.
6606     // In Microsoft mode, a variable defined in anonymous namespace must have
6607     // external linkage in order to be exported.
6608     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6609     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6610         (!AnonNSInMicrosoftMode &&
6611          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6612       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6613         << &ND << Attr;
6614       ND.setInvalidDecl();
6615     }
6616   }
6617 
6618   // Check the attributes on the function type, if any.
6619   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6620     // Don't declare this variable in the second operand of the for-statement;
6621     // GCC miscompiles that by ending its lifetime before evaluating the
6622     // third operand. See gcc.gnu.org/PR86769.
6623     AttributedTypeLoc ATL;
6624     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6625          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6626          TL = ATL.getModifiedLoc()) {
6627       // The [[lifetimebound]] attribute can be applied to the implicit object
6628       // parameter of a non-static member function (other than a ctor or dtor)
6629       // by applying it to the function type.
6630       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6631         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6632         if (!MD || MD->isStatic()) {
6633           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6634               << !MD << A->getRange();
6635         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6636           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6637               << isa<CXXDestructorDecl>(MD) << A->getRange();
6638         }
6639       }
6640     }
6641   }
6642 }
6643 
6644 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6645                                            NamedDecl *NewDecl,
6646                                            bool IsSpecialization,
6647                                            bool IsDefinition) {
6648   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6649     return;
6650 
6651   bool IsTemplate = false;
6652   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6653     OldDecl = OldTD->getTemplatedDecl();
6654     IsTemplate = true;
6655     if (!IsSpecialization)
6656       IsDefinition = false;
6657   }
6658   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6659     NewDecl = NewTD->getTemplatedDecl();
6660     IsTemplate = true;
6661   }
6662 
6663   if (!OldDecl || !NewDecl)
6664     return;
6665 
6666   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6667   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6668   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6669   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6670 
6671   // dllimport and dllexport are inheritable attributes so we have to exclude
6672   // inherited attribute instances.
6673   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6674                     (NewExportAttr && !NewExportAttr->isInherited());
6675 
6676   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6677   // the only exception being explicit specializations.
6678   // Implicitly generated declarations are also excluded for now because there
6679   // is no other way to switch these to use dllimport or dllexport.
6680   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6681 
6682   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6683     // Allow with a warning for free functions and global variables.
6684     bool JustWarn = false;
6685     if (!OldDecl->isCXXClassMember()) {
6686       auto *VD = dyn_cast<VarDecl>(OldDecl);
6687       if (VD && !VD->getDescribedVarTemplate())
6688         JustWarn = true;
6689       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6690       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6691         JustWarn = true;
6692     }
6693 
6694     // We cannot change a declaration that's been used because IR has already
6695     // been emitted. Dllimported functions will still work though (modulo
6696     // address equality) as they can use the thunk.
6697     if (OldDecl->isUsed())
6698       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6699         JustWarn = false;
6700 
6701     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6702                                : diag::err_attribute_dll_redeclaration;
6703     S.Diag(NewDecl->getLocation(), DiagID)
6704         << NewDecl
6705         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6706     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6707     if (!JustWarn) {
6708       NewDecl->setInvalidDecl();
6709       return;
6710     }
6711   }
6712 
6713   // A redeclaration is not allowed to drop a dllimport attribute, the only
6714   // exceptions being inline function definitions (except for function
6715   // templates), local extern declarations, qualified friend declarations or
6716   // special MSVC extension: in the last case, the declaration is treated as if
6717   // it were marked dllexport.
6718   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6719   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6720   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6721     // Ignore static data because out-of-line definitions are diagnosed
6722     // separately.
6723     IsStaticDataMember = VD->isStaticDataMember();
6724     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6725                    VarDecl::DeclarationOnly;
6726   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6727     IsInline = FD->isInlined();
6728     IsQualifiedFriend = FD->getQualifier() &&
6729                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6730   }
6731 
6732   if (OldImportAttr && !HasNewAttr &&
6733       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6734       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6735     if (IsMicrosoftABI && IsDefinition) {
6736       S.Diag(NewDecl->getLocation(),
6737              diag::warn_redeclaration_without_import_attribute)
6738           << NewDecl;
6739       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6740       NewDecl->dropAttr<DLLImportAttr>();
6741       NewDecl->addAttr(
6742           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6743     } else {
6744       S.Diag(NewDecl->getLocation(),
6745              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6746           << NewDecl << OldImportAttr;
6747       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6748       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6749       OldDecl->dropAttr<DLLImportAttr>();
6750       NewDecl->dropAttr<DLLImportAttr>();
6751     }
6752   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6753     // In MinGW, seeing a function declared inline drops the dllimport
6754     // attribute.
6755     OldDecl->dropAttr<DLLImportAttr>();
6756     NewDecl->dropAttr<DLLImportAttr>();
6757     S.Diag(NewDecl->getLocation(),
6758            diag::warn_dllimport_dropped_from_inline_function)
6759         << NewDecl << OldImportAttr;
6760   }
6761 
6762   // A specialization of a class template member function is processed here
6763   // since it's a redeclaration. If the parent class is dllexport, the
6764   // specialization inherits that attribute. This doesn't happen automatically
6765   // since the parent class isn't instantiated until later.
6766   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6767     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6768         !NewImportAttr && !NewExportAttr) {
6769       if (const DLLExportAttr *ParentExportAttr =
6770               MD->getParent()->getAttr<DLLExportAttr>()) {
6771         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6772         NewAttr->setInherited(true);
6773         NewDecl->addAttr(NewAttr);
6774       }
6775     }
6776   }
6777 }
6778 
6779 /// Given that we are within the definition of the given function,
6780 /// will that definition behave like C99's 'inline', where the
6781 /// definition is discarded except for optimization purposes?
6782 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6783   // Try to avoid calling GetGVALinkageForFunction.
6784 
6785   // All cases of this require the 'inline' keyword.
6786   if (!FD->isInlined()) return false;
6787 
6788   // This is only possible in C++ with the gnu_inline attribute.
6789   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6790     return false;
6791 
6792   // Okay, go ahead and call the relatively-more-expensive function.
6793   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6794 }
6795 
6796 /// Determine whether a variable is extern "C" prior to attaching
6797 /// an initializer. We can't just call isExternC() here, because that
6798 /// will also compute and cache whether the declaration is externally
6799 /// visible, which might change when we attach the initializer.
6800 ///
6801 /// This can only be used if the declaration is known to not be a
6802 /// redeclaration of an internal linkage declaration.
6803 ///
6804 /// For instance:
6805 ///
6806 ///   auto x = []{};
6807 ///
6808 /// Attaching the initializer here makes this declaration not externally
6809 /// visible, because its type has internal linkage.
6810 ///
6811 /// FIXME: This is a hack.
6812 template<typename T>
6813 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6814   if (S.getLangOpts().CPlusPlus) {
6815     // In C++, the overloadable attribute negates the effects of extern "C".
6816     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6817       return false;
6818 
6819     // So do CUDA's host/device attributes.
6820     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6821                                  D->template hasAttr<CUDAHostAttr>()))
6822       return false;
6823   }
6824   return D->isExternC();
6825 }
6826 
6827 static bool shouldConsiderLinkage(const VarDecl *VD) {
6828   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6829   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6830       isa<OMPDeclareMapperDecl>(DC))
6831     return VD->hasExternalStorage();
6832   if (DC->isFileContext())
6833     return true;
6834   if (DC->isRecord())
6835     return false;
6836   if (isa<RequiresExprBodyDecl>(DC))
6837     return false;
6838   llvm_unreachable("Unexpected context");
6839 }
6840 
6841 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6842   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6843   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6844       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6845     return true;
6846   if (DC->isRecord())
6847     return false;
6848   llvm_unreachable("Unexpected context");
6849 }
6850 
6851 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6852                           ParsedAttr::Kind Kind) {
6853   // Check decl attributes on the DeclSpec.
6854   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6855     return true;
6856 
6857   // Walk the declarator structure, checking decl attributes that were in a type
6858   // position to the decl itself.
6859   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6860     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6861       return true;
6862   }
6863 
6864   // Finally, check attributes on the decl itself.
6865   return PD.getAttributes().hasAttribute(Kind);
6866 }
6867 
6868 /// Adjust the \c DeclContext for a function or variable that might be a
6869 /// function-local external declaration.
6870 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6871   if (!DC->isFunctionOrMethod())
6872     return false;
6873 
6874   // If this is a local extern function or variable declared within a function
6875   // template, don't add it into the enclosing namespace scope until it is
6876   // instantiated; it might have a dependent type right now.
6877   if (DC->isDependentContext())
6878     return true;
6879 
6880   // C++11 [basic.link]p7:
6881   //   When a block scope declaration of an entity with linkage is not found to
6882   //   refer to some other declaration, then that entity is a member of the
6883   //   innermost enclosing namespace.
6884   //
6885   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6886   // semantically-enclosing namespace, not a lexically-enclosing one.
6887   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6888     DC = DC->getParent();
6889   return true;
6890 }
6891 
6892 /// Returns true if given declaration has external C language linkage.
6893 static bool isDeclExternC(const Decl *D) {
6894   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6895     return FD->isExternC();
6896   if (const auto *VD = dyn_cast<VarDecl>(D))
6897     return VD->isExternC();
6898 
6899   llvm_unreachable("Unknown type of decl!");
6900 }
6901 
6902 /// Returns true if there hasn't been any invalid type diagnosed.
6903 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6904   DeclContext *DC = NewVD->getDeclContext();
6905   QualType R = NewVD->getType();
6906 
6907   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6908   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6909   // argument.
6910   if (R->isImageType() || R->isPipeType()) {
6911     Se.Diag(NewVD->getLocation(),
6912             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6913         << R;
6914     NewVD->setInvalidDecl();
6915     return false;
6916   }
6917 
6918   // OpenCL v1.2 s6.9.r:
6919   // The event type cannot be used to declare a program scope variable.
6920   // OpenCL v2.0 s6.9.q:
6921   // The clk_event_t and reserve_id_t types cannot be declared in program
6922   // scope.
6923   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6924     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6925       Se.Diag(NewVD->getLocation(),
6926               diag::err_invalid_type_for_program_scope_var)
6927           << R;
6928       NewVD->setInvalidDecl();
6929       return false;
6930     }
6931   }
6932 
6933   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6934   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6935                                                Se.getLangOpts())) {
6936     QualType NR = R.getCanonicalType();
6937     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6938            NR->isReferenceType()) {
6939       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6940           NR->isFunctionReferenceType()) {
6941         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6942             << NR->isReferenceType();
6943         NewVD->setInvalidDecl();
6944         return false;
6945       }
6946       NR = NR->getPointeeType();
6947     }
6948   }
6949 
6950   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6951                                                Se.getLangOpts())) {
6952     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6953     // half array type (unless the cl_khr_fp16 extension is enabled).
6954     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6955       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6956       NewVD->setInvalidDecl();
6957       return false;
6958     }
6959   }
6960 
6961   // OpenCL v1.2 s6.9.r:
6962   // The event type cannot be used with the __local, __constant and __global
6963   // address space qualifiers.
6964   if (R->isEventT()) {
6965     if (R.getAddressSpace() != LangAS::opencl_private) {
6966       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6967       NewVD->setInvalidDecl();
6968       return false;
6969     }
6970   }
6971 
6972   if (R->isSamplerT()) {
6973     // OpenCL v1.2 s6.9.b p4:
6974     // The sampler type cannot be used with the __local and __global address
6975     // space qualifiers.
6976     if (R.getAddressSpace() == LangAS::opencl_local ||
6977         R.getAddressSpace() == LangAS::opencl_global) {
6978       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6979       NewVD->setInvalidDecl();
6980     }
6981 
6982     // OpenCL v1.2 s6.12.14.1:
6983     // A global sampler must be declared with either the constant address
6984     // space qualifier or with the const qualifier.
6985     if (DC->isTranslationUnit() &&
6986         !(R.getAddressSpace() == LangAS::opencl_constant ||
6987           R.isConstQualified())) {
6988       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6989       NewVD->setInvalidDecl();
6990     }
6991     if (NewVD->isInvalidDecl())
6992       return false;
6993   }
6994 
6995   return true;
6996 }
6997 
6998 template <typename AttrTy>
6999 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7000   const TypedefNameDecl *TND = TT->getDecl();
7001   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7002     AttrTy *Clone = Attribute->clone(S.Context);
7003     Clone->setInherited(true);
7004     D->addAttr(Clone);
7005   }
7006 }
7007 
7008 NamedDecl *Sema::ActOnVariableDeclarator(
7009     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7010     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7011     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7012   QualType R = TInfo->getType();
7013   DeclarationName Name = GetNameForDeclarator(D).getName();
7014 
7015   IdentifierInfo *II = Name.getAsIdentifierInfo();
7016 
7017   if (D.isDecompositionDeclarator()) {
7018     // Take the name of the first declarator as our name for diagnostic
7019     // purposes.
7020     auto &Decomp = D.getDecompositionDeclarator();
7021     if (!Decomp.bindings().empty()) {
7022       II = Decomp.bindings()[0].Name;
7023       Name = II;
7024     }
7025   } else if (!II) {
7026     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7027     return nullptr;
7028   }
7029 
7030 
7031   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7032   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7033 
7034   // dllimport globals without explicit storage class are treated as extern. We
7035   // have to change the storage class this early to get the right DeclContext.
7036   if (SC == SC_None && !DC->isRecord() &&
7037       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7038       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7039     SC = SC_Extern;
7040 
7041   DeclContext *OriginalDC = DC;
7042   bool IsLocalExternDecl = SC == SC_Extern &&
7043                            adjustContextForLocalExternDecl(DC);
7044 
7045   if (SCSpec == DeclSpec::SCS_mutable) {
7046     // mutable can only appear on non-static class members, so it's always
7047     // an error here
7048     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7049     D.setInvalidType();
7050     SC = SC_None;
7051   }
7052 
7053   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7054       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7055                               D.getDeclSpec().getStorageClassSpecLoc())) {
7056     // In C++11, the 'register' storage class specifier is deprecated.
7057     // Suppress the warning in system macros, it's used in macros in some
7058     // popular C system headers, such as in glibc's htonl() macro.
7059     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7060          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7061                                    : diag::warn_deprecated_register)
7062       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7063   }
7064 
7065   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7066 
7067   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7068     // C99 6.9p2: The storage-class specifiers auto and register shall not
7069     // appear in the declaration specifiers in an external declaration.
7070     // Global Register+Asm is a GNU extension we support.
7071     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7072       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7073       D.setInvalidType();
7074     }
7075   }
7076 
7077   // If this variable has a VLA type and an initializer, try to
7078   // fold to a constant-sized type. This is otherwise invalid.
7079   if (D.hasInitializer() && R->isVariableArrayType())
7080     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7081                                     /*DiagID=*/0);
7082 
7083   bool IsMemberSpecialization = false;
7084   bool IsVariableTemplateSpecialization = false;
7085   bool IsPartialSpecialization = false;
7086   bool IsVariableTemplate = false;
7087   VarDecl *NewVD = nullptr;
7088   VarTemplateDecl *NewTemplate = nullptr;
7089   TemplateParameterList *TemplateParams = nullptr;
7090   if (!getLangOpts().CPlusPlus) {
7091     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7092                             II, R, TInfo, SC);
7093 
7094     if (R->getContainedDeducedType())
7095       ParsingInitForAutoVars.insert(NewVD);
7096 
7097     if (D.isInvalidType())
7098       NewVD->setInvalidDecl();
7099 
7100     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7101         NewVD->hasLocalStorage())
7102       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7103                             NTCUC_AutoVar, NTCUK_Destruct);
7104   } else {
7105     bool Invalid = false;
7106 
7107     if (DC->isRecord() && !CurContext->isRecord()) {
7108       // This is an out-of-line definition of a static data member.
7109       switch (SC) {
7110       case SC_None:
7111         break;
7112       case SC_Static:
7113         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7114              diag::err_static_out_of_line)
7115           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7116         break;
7117       case SC_Auto:
7118       case SC_Register:
7119       case SC_Extern:
7120         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7121         // to names of variables declared in a block or to function parameters.
7122         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7123         // of class members
7124 
7125         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7126              diag::err_storage_class_for_static_member)
7127           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7128         break;
7129       case SC_PrivateExtern:
7130         llvm_unreachable("C storage class in c++!");
7131       }
7132     }
7133 
7134     if (SC == SC_Static && CurContext->isRecord()) {
7135       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7136         // Walk up the enclosing DeclContexts to check for any that are
7137         // incompatible with static data members.
7138         const DeclContext *FunctionOrMethod = nullptr;
7139         const CXXRecordDecl *AnonStruct = nullptr;
7140         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7141           if (Ctxt->isFunctionOrMethod()) {
7142             FunctionOrMethod = Ctxt;
7143             break;
7144           }
7145           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7146           if (ParentDecl && !ParentDecl->getDeclName()) {
7147             AnonStruct = ParentDecl;
7148             break;
7149           }
7150         }
7151         if (FunctionOrMethod) {
7152           // C++ [class.static.data]p5: A local class shall not have static data
7153           // members.
7154           Diag(D.getIdentifierLoc(),
7155                diag::err_static_data_member_not_allowed_in_local_class)
7156             << Name << RD->getDeclName() << RD->getTagKind();
7157         } else if (AnonStruct) {
7158           // C++ [class.static.data]p4: Unnamed classes and classes contained
7159           // directly or indirectly within unnamed classes shall not contain
7160           // static data members.
7161           Diag(D.getIdentifierLoc(),
7162                diag::err_static_data_member_not_allowed_in_anon_struct)
7163             << Name << AnonStruct->getTagKind();
7164           Invalid = true;
7165         } else if (RD->isUnion()) {
7166           // C++98 [class.union]p1: If a union contains a static data member,
7167           // the program is ill-formed. C++11 drops this restriction.
7168           Diag(D.getIdentifierLoc(),
7169                getLangOpts().CPlusPlus11
7170                  ? diag::warn_cxx98_compat_static_data_member_in_union
7171                  : diag::ext_static_data_member_in_union) << Name;
7172         }
7173       }
7174     }
7175 
7176     // Match up the template parameter lists with the scope specifier, then
7177     // determine whether we have a template or a template specialization.
7178     bool InvalidScope = false;
7179     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7180         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7181         D.getCXXScopeSpec(),
7182         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7183             ? D.getName().TemplateId
7184             : nullptr,
7185         TemplateParamLists,
7186         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7187     Invalid |= InvalidScope;
7188 
7189     if (TemplateParams) {
7190       if (!TemplateParams->size() &&
7191           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7192         // There is an extraneous 'template<>' for this variable. Complain
7193         // about it, but allow the declaration of the variable.
7194         Diag(TemplateParams->getTemplateLoc(),
7195              diag::err_template_variable_noparams)
7196           << II
7197           << SourceRange(TemplateParams->getTemplateLoc(),
7198                          TemplateParams->getRAngleLoc());
7199         TemplateParams = nullptr;
7200       } else {
7201         // Check that we can declare a template here.
7202         if (CheckTemplateDeclScope(S, TemplateParams))
7203           return nullptr;
7204 
7205         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7206           // This is an explicit specialization or a partial specialization.
7207           IsVariableTemplateSpecialization = true;
7208           IsPartialSpecialization = TemplateParams->size() > 0;
7209         } else { // if (TemplateParams->size() > 0)
7210           // This is a template declaration.
7211           IsVariableTemplate = true;
7212 
7213           // Only C++1y supports variable templates (N3651).
7214           Diag(D.getIdentifierLoc(),
7215                getLangOpts().CPlusPlus14
7216                    ? diag::warn_cxx11_compat_variable_template
7217                    : diag::ext_variable_template);
7218         }
7219       }
7220     } else {
7221       // Check that we can declare a member specialization here.
7222       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7223           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7224         return nullptr;
7225       assert((Invalid ||
7226               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7227              "should have a 'template<>' for this decl");
7228     }
7229 
7230     if (IsVariableTemplateSpecialization) {
7231       SourceLocation TemplateKWLoc =
7232           TemplateParamLists.size() > 0
7233               ? TemplateParamLists[0]->getTemplateLoc()
7234               : SourceLocation();
7235       DeclResult Res = ActOnVarTemplateSpecialization(
7236           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7237           IsPartialSpecialization);
7238       if (Res.isInvalid())
7239         return nullptr;
7240       NewVD = cast<VarDecl>(Res.get());
7241       AddToScope = false;
7242     } else if (D.isDecompositionDeclarator()) {
7243       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7244                                         D.getIdentifierLoc(), R, TInfo, SC,
7245                                         Bindings);
7246     } else
7247       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7248                               D.getIdentifierLoc(), II, R, TInfo, SC);
7249 
7250     // If this is supposed to be a variable template, create it as such.
7251     if (IsVariableTemplate) {
7252       NewTemplate =
7253           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7254                                   TemplateParams, NewVD);
7255       NewVD->setDescribedVarTemplate(NewTemplate);
7256     }
7257 
7258     // If this decl has an auto type in need of deduction, make a note of the
7259     // Decl so we can diagnose uses of it in its own initializer.
7260     if (R->getContainedDeducedType())
7261       ParsingInitForAutoVars.insert(NewVD);
7262 
7263     if (D.isInvalidType() || Invalid) {
7264       NewVD->setInvalidDecl();
7265       if (NewTemplate)
7266         NewTemplate->setInvalidDecl();
7267     }
7268 
7269     SetNestedNameSpecifier(*this, NewVD, D);
7270 
7271     // If we have any template parameter lists that don't directly belong to
7272     // the variable (matching the scope specifier), store them.
7273     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7274     if (TemplateParamLists.size() > VDTemplateParamLists)
7275       NewVD->setTemplateParameterListsInfo(
7276           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7277   }
7278 
7279   if (D.getDeclSpec().isInlineSpecified()) {
7280     if (!getLangOpts().CPlusPlus) {
7281       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7282           << 0;
7283     } else if (CurContext->isFunctionOrMethod()) {
7284       // 'inline' is not allowed on block scope variable declaration.
7285       Diag(D.getDeclSpec().getInlineSpecLoc(),
7286            diag::err_inline_declaration_block_scope) << Name
7287         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7288     } else {
7289       Diag(D.getDeclSpec().getInlineSpecLoc(),
7290            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7291                                      : diag::ext_inline_variable);
7292       NewVD->setInlineSpecified();
7293     }
7294   }
7295 
7296   // Set the lexical context. If the declarator has a C++ scope specifier, the
7297   // lexical context will be different from the semantic context.
7298   NewVD->setLexicalDeclContext(CurContext);
7299   if (NewTemplate)
7300     NewTemplate->setLexicalDeclContext(CurContext);
7301 
7302   if (IsLocalExternDecl) {
7303     if (D.isDecompositionDeclarator())
7304       for (auto *B : Bindings)
7305         B->setLocalExternDecl();
7306     else
7307       NewVD->setLocalExternDecl();
7308   }
7309 
7310   bool EmitTLSUnsupportedError = false;
7311   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7312     // C++11 [dcl.stc]p4:
7313     //   When thread_local is applied to a variable of block scope the
7314     //   storage-class-specifier static is implied if it does not appear
7315     //   explicitly.
7316     // Core issue: 'static' is not implied if the variable is declared
7317     //   'extern'.
7318     if (NewVD->hasLocalStorage() &&
7319         (SCSpec != DeclSpec::SCS_unspecified ||
7320          TSCS != DeclSpec::TSCS_thread_local ||
7321          !DC->isFunctionOrMethod()))
7322       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7323            diag::err_thread_non_global)
7324         << DeclSpec::getSpecifierName(TSCS);
7325     else if (!Context.getTargetInfo().isTLSSupported()) {
7326       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7327           getLangOpts().SYCLIsDevice) {
7328         // Postpone error emission until we've collected attributes required to
7329         // figure out whether it's a host or device variable and whether the
7330         // error should be ignored.
7331         EmitTLSUnsupportedError = true;
7332         // We still need to mark the variable as TLS so it shows up in AST with
7333         // proper storage class for other tools to use even if we're not going
7334         // to emit any code for it.
7335         NewVD->setTSCSpec(TSCS);
7336       } else
7337         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7338              diag::err_thread_unsupported);
7339     } else
7340       NewVD->setTSCSpec(TSCS);
7341   }
7342 
7343   switch (D.getDeclSpec().getConstexprSpecifier()) {
7344   case ConstexprSpecKind::Unspecified:
7345     break;
7346 
7347   case ConstexprSpecKind::Consteval:
7348     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7349          diag::err_constexpr_wrong_decl_kind)
7350         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7351     LLVM_FALLTHROUGH;
7352 
7353   case ConstexprSpecKind::Constexpr:
7354     NewVD->setConstexpr(true);
7355     // C++1z [dcl.spec.constexpr]p1:
7356     //   A static data member declared with the constexpr specifier is
7357     //   implicitly an inline variable.
7358     if (NewVD->isStaticDataMember() &&
7359         (getLangOpts().CPlusPlus17 ||
7360          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7361       NewVD->setImplicitlyInline();
7362     break;
7363 
7364   case ConstexprSpecKind::Constinit:
7365     if (!NewVD->hasGlobalStorage())
7366       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7367            diag::err_constinit_local_variable);
7368     else
7369       NewVD->addAttr(ConstInitAttr::Create(
7370           Context, D.getDeclSpec().getConstexprSpecLoc(),
7371           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7372     break;
7373   }
7374 
7375   // C99 6.7.4p3
7376   //   An inline definition of a function with external linkage shall
7377   //   not contain a definition of a modifiable object with static or
7378   //   thread storage duration...
7379   // We only apply this when the function is required to be defined
7380   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7381   // that a local variable with thread storage duration still has to
7382   // be marked 'static'.  Also note that it's possible to get these
7383   // semantics in C++ using __attribute__((gnu_inline)).
7384   if (SC == SC_Static && S->getFnParent() != nullptr &&
7385       !NewVD->getType().isConstQualified()) {
7386     FunctionDecl *CurFD = getCurFunctionDecl();
7387     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7388       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7389            diag::warn_static_local_in_extern_inline);
7390       MaybeSuggestAddingStaticToDecl(CurFD);
7391     }
7392   }
7393 
7394   if (D.getDeclSpec().isModulePrivateSpecified()) {
7395     if (IsVariableTemplateSpecialization)
7396       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7397           << (IsPartialSpecialization ? 1 : 0)
7398           << FixItHint::CreateRemoval(
7399                  D.getDeclSpec().getModulePrivateSpecLoc());
7400     else if (IsMemberSpecialization)
7401       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7402         << 2
7403         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7404     else if (NewVD->hasLocalStorage())
7405       Diag(NewVD->getLocation(), diag::err_module_private_local)
7406           << 0 << NewVD
7407           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7408           << FixItHint::CreateRemoval(
7409                  D.getDeclSpec().getModulePrivateSpecLoc());
7410     else {
7411       NewVD->setModulePrivate();
7412       if (NewTemplate)
7413         NewTemplate->setModulePrivate();
7414       for (auto *B : Bindings)
7415         B->setModulePrivate();
7416     }
7417   }
7418 
7419   if (getLangOpts().OpenCL) {
7420     deduceOpenCLAddressSpace(NewVD);
7421 
7422     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7423     if (TSC != TSCS_unspecified) {
7424       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7425            diag::err_opencl_unknown_type_specifier)
7426           << getLangOpts().getOpenCLVersionString()
7427           << DeclSpec::getSpecifierName(TSC) << 1;
7428       NewVD->setInvalidDecl();
7429     }
7430   }
7431 
7432   // Handle attributes prior to checking for duplicates in MergeVarDecl
7433   ProcessDeclAttributes(S, NewVD, D);
7434 
7435   // FIXME: This is probably the wrong location to be doing this and we should
7436   // probably be doing this for more attributes (especially for function
7437   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7438   // the code to copy attributes would be generated by TableGen.
7439   if (R->isFunctionPointerType())
7440     if (const auto *TT = R->getAs<TypedefType>())
7441       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7442 
7443   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7444       getLangOpts().SYCLIsDevice) {
7445     if (EmitTLSUnsupportedError &&
7446         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7447          (getLangOpts().OpenMPIsDevice &&
7448           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7449       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7450            diag::err_thread_unsupported);
7451 
7452     if (EmitTLSUnsupportedError &&
7453         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7454       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7455     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7456     // storage [duration]."
7457     if (SC == SC_None && S->getFnParent() != nullptr &&
7458         (NewVD->hasAttr<CUDASharedAttr>() ||
7459          NewVD->hasAttr<CUDAConstantAttr>())) {
7460       NewVD->setStorageClass(SC_Static);
7461     }
7462   }
7463 
7464   // Ensure that dllimport globals without explicit storage class are treated as
7465   // extern. The storage class is set above using parsed attributes. Now we can
7466   // check the VarDecl itself.
7467   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7468          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7469          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7470 
7471   // In auto-retain/release, infer strong retension for variables of
7472   // retainable type.
7473   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7474     NewVD->setInvalidDecl();
7475 
7476   // Handle GNU asm-label extension (encoded as an attribute).
7477   if (Expr *E = (Expr*)D.getAsmLabel()) {
7478     // The parser guarantees this is a string.
7479     StringLiteral *SE = cast<StringLiteral>(E);
7480     StringRef Label = SE->getString();
7481     if (S->getFnParent() != nullptr) {
7482       switch (SC) {
7483       case SC_None:
7484       case SC_Auto:
7485         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7486         break;
7487       case SC_Register:
7488         // Local Named register
7489         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7490             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7491           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7492         break;
7493       case SC_Static:
7494       case SC_Extern:
7495       case SC_PrivateExtern:
7496         break;
7497       }
7498     } else if (SC == SC_Register) {
7499       // Global Named register
7500       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7501         const auto &TI = Context.getTargetInfo();
7502         bool HasSizeMismatch;
7503 
7504         if (!TI.isValidGCCRegisterName(Label))
7505           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7506         else if (!TI.validateGlobalRegisterVariable(Label,
7507                                                     Context.getTypeSize(R),
7508                                                     HasSizeMismatch))
7509           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7510         else if (HasSizeMismatch)
7511           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7512       }
7513 
7514       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7515         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7516         NewVD->setInvalidDecl(true);
7517       }
7518     }
7519 
7520     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7521                                         /*IsLiteralLabel=*/true,
7522                                         SE->getStrTokenLoc(0)));
7523   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7524     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7525       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7526     if (I != ExtnameUndeclaredIdentifiers.end()) {
7527       if (isDeclExternC(NewVD)) {
7528         NewVD->addAttr(I->second);
7529         ExtnameUndeclaredIdentifiers.erase(I);
7530       } else
7531         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7532             << /*Variable*/1 << NewVD;
7533     }
7534   }
7535 
7536   // Find the shadowed declaration before filtering for scope.
7537   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7538                                 ? getShadowedDeclaration(NewVD, Previous)
7539                                 : nullptr;
7540 
7541   // Don't consider existing declarations that are in a different
7542   // scope and are out-of-semantic-context declarations (if the new
7543   // declaration has linkage).
7544   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7545                        D.getCXXScopeSpec().isNotEmpty() ||
7546                        IsMemberSpecialization ||
7547                        IsVariableTemplateSpecialization);
7548 
7549   // Check whether the previous declaration is in the same block scope. This
7550   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7551   if (getLangOpts().CPlusPlus &&
7552       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7553     NewVD->setPreviousDeclInSameBlockScope(
7554         Previous.isSingleResult() && !Previous.isShadowed() &&
7555         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7556 
7557   if (!getLangOpts().CPlusPlus) {
7558     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7559   } else {
7560     // If this is an explicit specialization of a static data member, check it.
7561     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7562         CheckMemberSpecialization(NewVD, Previous))
7563       NewVD->setInvalidDecl();
7564 
7565     // Merge the decl with the existing one if appropriate.
7566     if (!Previous.empty()) {
7567       if (Previous.isSingleResult() &&
7568           isa<FieldDecl>(Previous.getFoundDecl()) &&
7569           D.getCXXScopeSpec().isSet()) {
7570         // The user tried to define a non-static data member
7571         // out-of-line (C++ [dcl.meaning]p1).
7572         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7573           << D.getCXXScopeSpec().getRange();
7574         Previous.clear();
7575         NewVD->setInvalidDecl();
7576       }
7577     } else if (D.getCXXScopeSpec().isSet()) {
7578       // No previous declaration in the qualifying scope.
7579       Diag(D.getIdentifierLoc(), diag::err_no_member)
7580         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7581         << D.getCXXScopeSpec().getRange();
7582       NewVD->setInvalidDecl();
7583     }
7584 
7585     if (!IsVariableTemplateSpecialization)
7586       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7587 
7588     if (NewTemplate) {
7589       VarTemplateDecl *PrevVarTemplate =
7590           NewVD->getPreviousDecl()
7591               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7592               : nullptr;
7593 
7594       // Check the template parameter list of this declaration, possibly
7595       // merging in the template parameter list from the previous variable
7596       // template declaration.
7597       if (CheckTemplateParameterList(
7598               TemplateParams,
7599               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7600                               : nullptr,
7601               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7602                DC->isDependentContext())
7603                   ? TPC_ClassTemplateMember
7604                   : TPC_VarTemplate))
7605         NewVD->setInvalidDecl();
7606 
7607       // If we are providing an explicit specialization of a static variable
7608       // template, make a note of that.
7609       if (PrevVarTemplate &&
7610           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7611         PrevVarTemplate->setMemberSpecialization();
7612     }
7613   }
7614 
7615   // Diagnose shadowed variables iff this isn't a redeclaration.
7616   if (ShadowedDecl && !D.isRedeclaration())
7617     CheckShadow(NewVD, ShadowedDecl, Previous);
7618 
7619   ProcessPragmaWeak(S, NewVD);
7620 
7621   // If this is the first declaration of an extern C variable, update
7622   // the map of such variables.
7623   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7624       isIncompleteDeclExternC(*this, NewVD))
7625     RegisterLocallyScopedExternCDecl(NewVD, S);
7626 
7627   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7628     MangleNumberingContext *MCtx;
7629     Decl *ManglingContextDecl;
7630     std::tie(MCtx, ManglingContextDecl) =
7631         getCurrentMangleNumberContext(NewVD->getDeclContext());
7632     if (MCtx) {
7633       Context.setManglingNumber(
7634           NewVD, MCtx->getManglingNumber(
7635                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7636       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7637     }
7638   }
7639 
7640   // Special handling of variable named 'main'.
7641   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7642       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7643       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7644 
7645     // C++ [basic.start.main]p3
7646     // A program that declares a variable main at global scope is ill-formed.
7647     if (getLangOpts().CPlusPlus)
7648       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7649 
7650     // In C, and external-linkage variable named main results in undefined
7651     // behavior.
7652     else if (NewVD->hasExternalFormalLinkage())
7653       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7654   }
7655 
7656   if (D.isRedeclaration() && !Previous.empty()) {
7657     NamedDecl *Prev = Previous.getRepresentativeDecl();
7658     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7659                                    D.isFunctionDefinition());
7660   }
7661 
7662   if (NewTemplate) {
7663     if (NewVD->isInvalidDecl())
7664       NewTemplate->setInvalidDecl();
7665     ActOnDocumentableDecl(NewTemplate);
7666     return NewTemplate;
7667   }
7668 
7669   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7670     CompleteMemberSpecialization(NewVD, Previous);
7671 
7672   return NewVD;
7673 }
7674 
7675 /// Enum describing the %select options in diag::warn_decl_shadow.
7676 enum ShadowedDeclKind {
7677   SDK_Local,
7678   SDK_Global,
7679   SDK_StaticMember,
7680   SDK_Field,
7681   SDK_Typedef,
7682   SDK_Using,
7683   SDK_StructuredBinding
7684 };
7685 
7686 /// Determine what kind of declaration we're shadowing.
7687 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7688                                                 const DeclContext *OldDC) {
7689   if (isa<TypeAliasDecl>(ShadowedDecl))
7690     return SDK_Using;
7691   else if (isa<TypedefDecl>(ShadowedDecl))
7692     return SDK_Typedef;
7693   else if (isa<BindingDecl>(ShadowedDecl))
7694     return SDK_StructuredBinding;
7695   else if (isa<RecordDecl>(OldDC))
7696     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7697 
7698   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7699 }
7700 
7701 /// Return the location of the capture if the given lambda captures the given
7702 /// variable \p VD, or an invalid source location otherwise.
7703 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7704                                          const VarDecl *VD) {
7705   for (const Capture &Capture : LSI->Captures) {
7706     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7707       return Capture.getLocation();
7708   }
7709   return SourceLocation();
7710 }
7711 
7712 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7713                                      const LookupResult &R) {
7714   // Only diagnose if we're shadowing an unambiguous field or variable.
7715   if (R.getResultKind() != LookupResult::Found)
7716     return false;
7717 
7718   // Return false if warning is ignored.
7719   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7720 }
7721 
7722 /// Return the declaration shadowed by the given variable \p D, or null
7723 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7724 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7725                                         const LookupResult &R) {
7726   if (!shouldWarnIfShadowedDecl(Diags, R))
7727     return nullptr;
7728 
7729   // Don't diagnose declarations at file scope.
7730   if (D->hasGlobalStorage())
7731     return nullptr;
7732 
7733   NamedDecl *ShadowedDecl = R.getFoundDecl();
7734   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7735                                                             : nullptr;
7736 }
7737 
7738 /// Return the declaration shadowed by the given typedef \p D, or null
7739 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7740 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7741                                         const LookupResult &R) {
7742   // Don't warn if typedef declaration is part of a class
7743   if (D->getDeclContext()->isRecord())
7744     return nullptr;
7745 
7746   if (!shouldWarnIfShadowedDecl(Diags, R))
7747     return nullptr;
7748 
7749   NamedDecl *ShadowedDecl = R.getFoundDecl();
7750   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7751 }
7752 
7753 /// Return the declaration shadowed by the given variable \p D, or null
7754 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7755 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7756                                         const LookupResult &R) {
7757   if (!shouldWarnIfShadowedDecl(Diags, R))
7758     return nullptr;
7759 
7760   NamedDecl *ShadowedDecl = R.getFoundDecl();
7761   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7762                                                             : nullptr;
7763 }
7764 
7765 /// Diagnose variable or built-in function shadowing.  Implements
7766 /// -Wshadow.
7767 ///
7768 /// This method is called whenever a VarDecl is added to a "useful"
7769 /// scope.
7770 ///
7771 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7772 /// \param R the lookup of the name
7773 ///
7774 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7775                        const LookupResult &R) {
7776   DeclContext *NewDC = D->getDeclContext();
7777 
7778   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7779     // Fields are not shadowed by variables in C++ static methods.
7780     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7781       if (MD->isStatic())
7782         return;
7783 
7784     // Fields shadowed by constructor parameters are a special case. Usually
7785     // the constructor initializes the field with the parameter.
7786     if (isa<CXXConstructorDecl>(NewDC))
7787       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7788         // Remember that this was shadowed so we can either warn about its
7789         // modification or its existence depending on warning settings.
7790         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7791         return;
7792       }
7793   }
7794 
7795   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7796     if (shadowedVar->isExternC()) {
7797       // For shadowing external vars, make sure that we point to the global
7798       // declaration, not a locally scoped extern declaration.
7799       for (auto I : shadowedVar->redecls())
7800         if (I->isFileVarDecl()) {
7801           ShadowedDecl = I;
7802           break;
7803         }
7804     }
7805 
7806   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7807 
7808   unsigned WarningDiag = diag::warn_decl_shadow;
7809   SourceLocation CaptureLoc;
7810   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7811       isa<CXXMethodDecl>(NewDC)) {
7812     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7813       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7814         if (RD->getLambdaCaptureDefault() == LCD_None) {
7815           // Try to avoid warnings for lambdas with an explicit capture list.
7816           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7817           // Warn only when the lambda captures the shadowed decl explicitly.
7818           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7819           if (CaptureLoc.isInvalid())
7820             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7821         } else {
7822           // Remember that this was shadowed so we can avoid the warning if the
7823           // shadowed decl isn't captured and the warning settings allow it.
7824           cast<LambdaScopeInfo>(getCurFunction())
7825               ->ShadowingDecls.push_back(
7826                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7827           return;
7828         }
7829       }
7830 
7831       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7832         // A variable can't shadow a local variable in an enclosing scope, if
7833         // they are separated by a non-capturing declaration context.
7834         for (DeclContext *ParentDC = NewDC;
7835              ParentDC && !ParentDC->Equals(OldDC);
7836              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7837           // Only block literals, captured statements, and lambda expressions
7838           // can capture; other scopes don't.
7839           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7840               !isLambdaCallOperator(ParentDC)) {
7841             return;
7842           }
7843         }
7844       }
7845     }
7846   }
7847 
7848   // Only warn about certain kinds of shadowing for class members.
7849   if (NewDC && NewDC->isRecord()) {
7850     // In particular, don't warn about shadowing non-class members.
7851     if (!OldDC->isRecord())
7852       return;
7853 
7854     // TODO: should we warn about static data members shadowing
7855     // static data members from base classes?
7856 
7857     // TODO: don't diagnose for inaccessible shadowed members.
7858     // This is hard to do perfectly because we might friend the
7859     // shadowing context, but that's just a false negative.
7860   }
7861 
7862 
7863   DeclarationName Name = R.getLookupName();
7864 
7865   // Emit warning and note.
7866   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7867   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7868   if (!CaptureLoc.isInvalid())
7869     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7870         << Name << /*explicitly*/ 1;
7871   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7872 }
7873 
7874 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7875 /// when these variables are captured by the lambda.
7876 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7877   for (const auto &Shadow : LSI->ShadowingDecls) {
7878     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7879     // Try to avoid the warning when the shadowed decl isn't captured.
7880     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7881     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7882     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7883                                        ? diag::warn_decl_shadow_uncaptured_local
7884                                        : diag::warn_decl_shadow)
7885         << Shadow.VD->getDeclName()
7886         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7887     if (!CaptureLoc.isInvalid())
7888       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7889           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7890     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7891   }
7892 }
7893 
7894 /// Check -Wshadow without the advantage of a previous lookup.
7895 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7896   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7897     return;
7898 
7899   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7900                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7901   LookupName(R, S);
7902   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7903     CheckShadow(D, ShadowedDecl, R);
7904 }
7905 
7906 /// Check if 'E', which is an expression that is about to be modified, refers
7907 /// to a constructor parameter that shadows a field.
7908 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7909   // Quickly ignore expressions that can't be shadowing ctor parameters.
7910   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7911     return;
7912   E = E->IgnoreParenImpCasts();
7913   auto *DRE = dyn_cast<DeclRefExpr>(E);
7914   if (!DRE)
7915     return;
7916   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7917   auto I = ShadowingDecls.find(D);
7918   if (I == ShadowingDecls.end())
7919     return;
7920   const NamedDecl *ShadowedDecl = I->second;
7921   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7922   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7923   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7924   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7925 
7926   // Avoid issuing multiple warnings about the same decl.
7927   ShadowingDecls.erase(I);
7928 }
7929 
7930 /// Check for conflict between this global or extern "C" declaration and
7931 /// previous global or extern "C" declarations. This is only used in C++.
7932 template<typename T>
7933 static bool checkGlobalOrExternCConflict(
7934     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7935   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7936   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7937 
7938   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7939     // The common case: this global doesn't conflict with any extern "C"
7940     // declaration.
7941     return false;
7942   }
7943 
7944   if (Prev) {
7945     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7946       // Both the old and new declarations have C language linkage. This is a
7947       // redeclaration.
7948       Previous.clear();
7949       Previous.addDecl(Prev);
7950       return true;
7951     }
7952 
7953     // This is a global, non-extern "C" declaration, and there is a previous
7954     // non-global extern "C" declaration. Diagnose if this is a variable
7955     // declaration.
7956     if (!isa<VarDecl>(ND))
7957       return false;
7958   } else {
7959     // The declaration is extern "C". Check for any declaration in the
7960     // translation unit which might conflict.
7961     if (IsGlobal) {
7962       // We have already performed the lookup into the translation unit.
7963       IsGlobal = false;
7964       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7965            I != E; ++I) {
7966         if (isa<VarDecl>(*I)) {
7967           Prev = *I;
7968           break;
7969         }
7970       }
7971     } else {
7972       DeclContext::lookup_result R =
7973           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7974       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7975            I != E; ++I) {
7976         if (isa<VarDecl>(*I)) {
7977           Prev = *I;
7978           break;
7979         }
7980         // FIXME: If we have any other entity with this name in global scope,
7981         // the declaration is ill-formed, but that is a defect: it breaks the
7982         // 'stat' hack, for instance. Only variables can have mangled name
7983         // clashes with extern "C" declarations, so only they deserve a
7984         // diagnostic.
7985       }
7986     }
7987 
7988     if (!Prev)
7989       return false;
7990   }
7991 
7992   // Use the first declaration's location to ensure we point at something which
7993   // is lexically inside an extern "C" linkage-spec.
7994   assert(Prev && "should have found a previous declaration to diagnose");
7995   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7996     Prev = FD->getFirstDecl();
7997   else
7998     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7999 
8000   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8001     << IsGlobal << ND;
8002   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8003     << IsGlobal;
8004   return false;
8005 }
8006 
8007 /// Apply special rules for handling extern "C" declarations. Returns \c true
8008 /// if we have found that this is a redeclaration of some prior entity.
8009 ///
8010 /// Per C++ [dcl.link]p6:
8011 ///   Two declarations [for a function or variable] with C language linkage
8012 ///   with the same name that appear in different scopes refer to the same
8013 ///   [entity]. An entity with C language linkage shall not be declared with
8014 ///   the same name as an entity in global scope.
8015 template<typename T>
8016 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8017                                                   LookupResult &Previous) {
8018   if (!S.getLangOpts().CPlusPlus) {
8019     // In C, when declaring a global variable, look for a corresponding 'extern'
8020     // variable declared in function scope. We don't need this in C++, because
8021     // we find local extern decls in the surrounding file-scope DeclContext.
8022     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8023       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8024         Previous.clear();
8025         Previous.addDecl(Prev);
8026         return true;
8027       }
8028     }
8029     return false;
8030   }
8031 
8032   // A declaration in the translation unit can conflict with an extern "C"
8033   // declaration.
8034   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8035     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8036 
8037   // An extern "C" declaration can conflict with a declaration in the
8038   // translation unit or can be a redeclaration of an extern "C" declaration
8039   // in another scope.
8040   if (isIncompleteDeclExternC(S,ND))
8041     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8042 
8043   // Neither global nor extern "C": nothing to do.
8044   return false;
8045 }
8046 
8047 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8048   // If the decl is already known invalid, don't check it.
8049   if (NewVD->isInvalidDecl())
8050     return;
8051 
8052   QualType T = NewVD->getType();
8053 
8054   // Defer checking an 'auto' type until its initializer is attached.
8055   if (T->isUndeducedType())
8056     return;
8057 
8058   if (NewVD->hasAttrs())
8059     CheckAlignasUnderalignment(NewVD);
8060 
8061   if (T->isObjCObjectType()) {
8062     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8063       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8064     T = Context.getObjCObjectPointerType(T);
8065     NewVD->setType(T);
8066   }
8067 
8068   // Emit an error if an address space was applied to decl with local storage.
8069   // This includes arrays of objects with address space qualifiers, but not
8070   // automatic variables that point to other address spaces.
8071   // ISO/IEC TR 18037 S5.1.2
8072   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8073       T.getAddressSpace() != LangAS::Default) {
8074     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8075     NewVD->setInvalidDecl();
8076     return;
8077   }
8078 
8079   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8080   // scope.
8081   if (getLangOpts().OpenCLVersion == 120 &&
8082       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8083                                             getLangOpts()) &&
8084       NewVD->isStaticLocal()) {
8085     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8086     NewVD->setInvalidDecl();
8087     return;
8088   }
8089 
8090   if (getLangOpts().OpenCL) {
8091     if (!diagnoseOpenCLTypes(*this, NewVD))
8092       return;
8093 
8094     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8095     if (NewVD->hasAttr<BlocksAttr>()) {
8096       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8097       return;
8098     }
8099 
8100     if (T->isBlockPointerType()) {
8101       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8102       // can't use 'extern' storage class.
8103       if (!T.isConstQualified()) {
8104         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8105             << 0 /*const*/;
8106         NewVD->setInvalidDecl();
8107         return;
8108       }
8109       if (NewVD->hasExternalStorage()) {
8110         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8111         NewVD->setInvalidDecl();
8112         return;
8113       }
8114     }
8115 
8116     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8117     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8118         NewVD->hasExternalStorage()) {
8119       if (!T->isSamplerT() && !T->isDependentType() &&
8120           !(T.getAddressSpace() == LangAS::opencl_constant ||
8121             (T.getAddressSpace() == LangAS::opencl_global &&
8122              getOpenCLOptions().areProgramScopeVariablesSupported(
8123                  getLangOpts())))) {
8124         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8125         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8126           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8127               << Scope << "global or constant";
8128         else
8129           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8130               << Scope << "constant";
8131         NewVD->setInvalidDecl();
8132         return;
8133       }
8134     } else {
8135       if (T.getAddressSpace() == LangAS::opencl_global) {
8136         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8137             << 1 /*is any function*/ << "global";
8138         NewVD->setInvalidDecl();
8139         return;
8140       }
8141       if (T.getAddressSpace() == LangAS::opencl_constant ||
8142           T.getAddressSpace() == LangAS::opencl_local) {
8143         FunctionDecl *FD = getCurFunctionDecl();
8144         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8145         // in functions.
8146         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8147           if (T.getAddressSpace() == LangAS::opencl_constant)
8148             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8149                 << 0 /*non-kernel only*/ << "constant";
8150           else
8151             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8152                 << 0 /*non-kernel only*/ << "local";
8153           NewVD->setInvalidDecl();
8154           return;
8155         }
8156         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8157         // in the outermost scope of a kernel function.
8158         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8159           if (!getCurScope()->isFunctionScope()) {
8160             if (T.getAddressSpace() == LangAS::opencl_constant)
8161               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8162                   << "constant";
8163             else
8164               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8165                   << "local";
8166             NewVD->setInvalidDecl();
8167             return;
8168           }
8169         }
8170       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8171                  // If we are parsing a template we didn't deduce an addr
8172                  // space yet.
8173                  T.getAddressSpace() != LangAS::Default) {
8174         // Do not allow other address spaces on automatic variable.
8175         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8176         NewVD->setInvalidDecl();
8177         return;
8178       }
8179     }
8180   }
8181 
8182   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8183       && !NewVD->hasAttr<BlocksAttr>()) {
8184     if (getLangOpts().getGC() != LangOptions::NonGC)
8185       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8186     else {
8187       assert(!getLangOpts().ObjCAutoRefCount);
8188       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8189     }
8190   }
8191 
8192   bool isVM = T->isVariablyModifiedType();
8193   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8194       NewVD->hasAttr<BlocksAttr>())
8195     setFunctionHasBranchProtectedScope();
8196 
8197   if ((isVM && NewVD->hasLinkage()) ||
8198       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8199     bool SizeIsNegative;
8200     llvm::APSInt Oversized;
8201     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8202         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8203     QualType FixedT;
8204     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8205       FixedT = FixedTInfo->getType();
8206     else if (FixedTInfo) {
8207       // Type and type-as-written are canonically different. We need to fix up
8208       // both types separately.
8209       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8210                                                    Oversized);
8211     }
8212     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8213       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8214       // FIXME: This won't give the correct result for
8215       // int a[10][n];
8216       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8217 
8218       if (NewVD->isFileVarDecl())
8219         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8220         << SizeRange;
8221       else if (NewVD->isStaticLocal())
8222         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8223         << SizeRange;
8224       else
8225         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8226         << SizeRange;
8227       NewVD->setInvalidDecl();
8228       return;
8229     }
8230 
8231     if (!FixedTInfo) {
8232       if (NewVD->isFileVarDecl())
8233         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8234       else
8235         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8236       NewVD->setInvalidDecl();
8237       return;
8238     }
8239 
8240     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8241     NewVD->setType(FixedT);
8242     NewVD->setTypeSourceInfo(FixedTInfo);
8243   }
8244 
8245   if (T->isVoidType()) {
8246     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8247     //                    of objects and functions.
8248     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8249       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8250         << T;
8251       NewVD->setInvalidDecl();
8252       return;
8253     }
8254   }
8255 
8256   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8257     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8258     NewVD->setInvalidDecl();
8259     return;
8260   }
8261 
8262   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8263     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8264     NewVD->setInvalidDecl();
8265     return;
8266   }
8267 
8268   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8269     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8270     NewVD->setInvalidDecl();
8271     return;
8272   }
8273 
8274   if (NewVD->isConstexpr() && !T->isDependentType() &&
8275       RequireLiteralType(NewVD->getLocation(), T,
8276                          diag::err_constexpr_var_non_literal)) {
8277     NewVD->setInvalidDecl();
8278     return;
8279   }
8280 
8281   // PPC MMA non-pointer types are not allowed as non-local variable types.
8282   if (Context.getTargetInfo().getTriple().isPPC64() &&
8283       !NewVD->isLocalVarDecl() &&
8284       CheckPPCMMAType(T, NewVD->getLocation())) {
8285     NewVD->setInvalidDecl();
8286     return;
8287   }
8288 }
8289 
8290 /// Perform semantic checking on a newly-created variable
8291 /// declaration.
8292 ///
8293 /// This routine performs all of the type-checking required for a
8294 /// variable declaration once it has been built. It is used both to
8295 /// check variables after they have been parsed and their declarators
8296 /// have been translated into a declaration, and to check variables
8297 /// that have been instantiated from a template.
8298 ///
8299 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8300 ///
8301 /// Returns true if the variable declaration is a redeclaration.
8302 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8303   CheckVariableDeclarationType(NewVD);
8304 
8305   // If the decl is already known invalid, don't check it.
8306   if (NewVD->isInvalidDecl())
8307     return false;
8308 
8309   // If we did not find anything by this name, look for a non-visible
8310   // extern "C" declaration with the same name.
8311   if (Previous.empty() &&
8312       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8313     Previous.setShadowed();
8314 
8315   if (!Previous.empty()) {
8316     MergeVarDecl(NewVD, Previous);
8317     return true;
8318   }
8319   return false;
8320 }
8321 
8322 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8323 /// and if so, check that it's a valid override and remember it.
8324 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8325   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8326 
8327   // Look for methods in base classes that this method might override.
8328   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8329                      /*DetectVirtual=*/false);
8330   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8331     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8332     DeclarationName Name = MD->getDeclName();
8333 
8334     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8335       // We really want to find the base class destructor here.
8336       QualType T = Context.getTypeDeclType(BaseRecord);
8337       CanQualType CT = Context.getCanonicalType(T);
8338       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8339     }
8340 
8341     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8342       CXXMethodDecl *BaseMD =
8343           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8344       if (!BaseMD || !BaseMD->isVirtual() ||
8345           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8346                      /*ConsiderCudaAttrs=*/true,
8347                      // C++2a [class.virtual]p2 does not consider requires
8348                      // clauses when overriding.
8349                      /*ConsiderRequiresClauses=*/false))
8350         continue;
8351 
8352       if (Overridden.insert(BaseMD).second) {
8353         MD->addOverriddenMethod(BaseMD);
8354         CheckOverridingFunctionReturnType(MD, BaseMD);
8355         CheckOverridingFunctionAttributes(MD, BaseMD);
8356         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8357         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8358       }
8359 
8360       // A method can only override one function from each base class. We
8361       // don't track indirectly overridden methods from bases of bases.
8362       return true;
8363     }
8364 
8365     return false;
8366   };
8367 
8368   DC->lookupInBases(VisitBase, Paths);
8369   return !Overridden.empty();
8370 }
8371 
8372 namespace {
8373   // Struct for holding all of the extra arguments needed by
8374   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8375   struct ActOnFDArgs {
8376     Scope *S;
8377     Declarator &D;
8378     MultiTemplateParamsArg TemplateParamLists;
8379     bool AddToScope;
8380   };
8381 } // end anonymous namespace
8382 
8383 namespace {
8384 
8385 // Callback to only accept typo corrections that have a non-zero edit distance.
8386 // Also only accept corrections that have the same parent decl.
8387 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8388  public:
8389   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8390                             CXXRecordDecl *Parent)
8391       : Context(Context), OriginalFD(TypoFD),
8392         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8393 
8394   bool ValidateCandidate(const TypoCorrection &candidate) override {
8395     if (candidate.getEditDistance() == 0)
8396       return false;
8397 
8398     SmallVector<unsigned, 1> MismatchedParams;
8399     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8400                                           CDeclEnd = candidate.end();
8401          CDecl != CDeclEnd; ++CDecl) {
8402       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8403 
8404       if (FD && !FD->hasBody() &&
8405           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8406         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8407           CXXRecordDecl *Parent = MD->getParent();
8408           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8409             return true;
8410         } else if (!ExpectedParent) {
8411           return true;
8412         }
8413       }
8414     }
8415 
8416     return false;
8417   }
8418 
8419   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8420     return std::make_unique<DifferentNameValidatorCCC>(*this);
8421   }
8422 
8423  private:
8424   ASTContext &Context;
8425   FunctionDecl *OriginalFD;
8426   CXXRecordDecl *ExpectedParent;
8427 };
8428 
8429 } // end anonymous namespace
8430 
8431 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8432   TypoCorrectedFunctionDefinitions.insert(F);
8433 }
8434 
8435 /// Generate diagnostics for an invalid function redeclaration.
8436 ///
8437 /// This routine handles generating the diagnostic messages for an invalid
8438 /// function redeclaration, including finding possible similar declarations
8439 /// or performing typo correction if there are no previous declarations with
8440 /// the same name.
8441 ///
8442 /// Returns a NamedDecl iff typo correction was performed and substituting in
8443 /// the new declaration name does not cause new errors.
8444 static NamedDecl *DiagnoseInvalidRedeclaration(
8445     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8446     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8447   DeclarationName Name = NewFD->getDeclName();
8448   DeclContext *NewDC = NewFD->getDeclContext();
8449   SmallVector<unsigned, 1> MismatchedParams;
8450   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8451   TypoCorrection Correction;
8452   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8453   unsigned DiagMsg =
8454     IsLocalFriend ? diag::err_no_matching_local_friend :
8455     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8456     diag::err_member_decl_does_not_match;
8457   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8458                     IsLocalFriend ? Sema::LookupLocalFriendName
8459                                   : Sema::LookupOrdinaryName,
8460                     Sema::ForVisibleRedeclaration);
8461 
8462   NewFD->setInvalidDecl();
8463   if (IsLocalFriend)
8464     SemaRef.LookupName(Prev, S);
8465   else
8466     SemaRef.LookupQualifiedName(Prev, NewDC);
8467   assert(!Prev.isAmbiguous() &&
8468          "Cannot have an ambiguity in previous-declaration lookup");
8469   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8470   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8471                                 MD ? MD->getParent() : nullptr);
8472   if (!Prev.empty()) {
8473     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8474          Func != FuncEnd; ++Func) {
8475       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8476       if (FD &&
8477           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8478         // Add 1 to the index so that 0 can mean the mismatch didn't
8479         // involve a parameter
8480         unsigned ParamNum =
8481             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8482         NearMatches.push_back(std::make_pair(FD, ParamNum));
8483       }
8484     }
8485   // If the qualified name lookup yielded nothing, try typo correction
8486   } else if ((Correction = SemaRef.CorrectTypo(
8487                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8488                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8489                   IsLocalFriend ? nullptr : NewDC))) {
8490     // Set up everything for the call to ActOnFunctionDeclarator
8491     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8492                               ExtraArgs.D.getIdentifierLoc());
8493     Previous.clear();
8494     Previous.setLookupName(Correction.getCorrection());
8495     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8496                                     CDeclEnd = Correction.end();
8497          CDecl != CDeclEnd; ++CDecl) {
8498       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8499       if (FD && !FD->hasBody() &&
8500           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8501         Previous.addDecl(FD);
8502       }
8503     }
8504     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8505 
8506     NamedDecl *Result;
8507     // Retry building the function declaration with the new previous
8508     // declarations, and with errors suppressed.
8509     {
8510       // Trap errors.
8511       Sema::SFINAETrap Trap(SemaRef);
8512 
8513       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8514       // pieces need to verify the typo-corrected C++ declaration and hopefully
8515       // eliminate the need for the parameter pack ExtraArgs.
8516       Result = SemaRef.ActOnFunctionDeclarator(
8517           ExtraArgs.S, ExtraArgs.D,
8518           Correction.getCorrectionDecl()->getDeclContext(),
8519           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8520           ExtraArgs.AddToScope);
8521 
8522       if (Trap.hasErrorOccurred())
8523         Result = nullptr;
8524     }
8525 
8526     if (Result) {
8527       // Determine which correction we picked.
8528       Decl *Canonical = Result->getCanonicalDecl();
8529       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8530            I != E; ++I)
8531         if ((*I)->getCanonicalDecl() == Canonical)
8532           Correction.setCorrectionDecl(*I);
8533 
8534       // Let Sema know about the correction.
8535       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8536       SemaRef.diagnoseTypo(
8537           Correction,
8538           SemaRef.PDiag(IsLocalFriend
8539                           ? diag::err_no_matching_local_friend_suggest
8540                           : diag::err_member_decl_does_not_match_suggest)
8541             << Name << NewDC << IsDefinition);
8542       return Result;
8543     }
8544 
8545     // Pretend the typo correction never occurred
8546     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8547                               ExtraArgs.D.getIdentifierLoc());
8548     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8549     Previous.clear();
8550     Previous.setLookupName(Name);
8551   }
8552 
8553   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8554       << Name << NewDC << IsDefinition << NewFD->getLocation();
8555 
8556   bool NewFDisConst = false;
8557   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8558     NewFDisConst = NewMD->isConst();
8559 
8560   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8561        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8562        NearMatch != NearMatchEnd; ++NearMatch) {
8563     FunctionDecl *FD = NearMatch->first;
8564     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8565     bool FDisConst = MD && MD->isConst();
8566     bool IsMember = MD || !IsLocalFriend;
8567 
8568     // FIXME: These notes are poorly worded for the local friend case.
8569     if (unsigned Idx = NearMatch->second) {
8570       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8571       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8572       if (Loc.isInvalid()) Loc = FD->getLocation();
8573       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8574                                  : diag::note_local_decl_close_param_match)
8575         << Idx << FDParam->getType()
8576         << NewFD->getParamDecl(Idx - 1)->getType();
8577     } else if (FDisConst != NewFDisConst) {
8578       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8579           << NewFDisConst << FD->getSourceRange().getEnd()
8580           << (NewFDisConst
8581                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8582                                                  .getConstQualifierLoc())
8583                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8584                                                    .getRParenLoc()
8585                                                    .getLocWithOffset(1),
8586                                                " const"));
8587     } else
8588       SemaRef.Diag(FD->getLocation(),
8589                    IsMember ? diag::note_member_def_close_match
8590                             : diag::note_local_decl_close_match);
8591   }
8592   return nullptr;
8593 }
8594 
8595 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8596   switch (D.getDeclSpec().getStorageClassSpec()) {
8597   default: llvm_unreachable("Unknown storage class!");
8598   case DeclSpec::SCS_auto:
8599   case DeclSpec::SCS_register:
8600   case DeclSpec::SCS_mutable:
8601     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8602                  diag::err_typecheck_sclass_func);
8603     D.getMutableDeclSpec().ClearStorageClassSpecs();
8604     D.setInvalidType();
8605     break;
8606   case DeclSpec::SCS_unspecified: break;
8607   case DeclSpec::SCS_extern:
8608     if (D.getDeclSpec().isExternInLinkageSpec())
8609       return SC_None;
8610     return SC_Extern;
8611   case DeclSpec::SCS_static: {
8612     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8613       // C99 6.7.1p5:
8614       //   The declaration of an identifier for a function that has
8615       //   block scope shall have no explicit storage-class specifier
8616       //   other than extern
8617       // See also (C++ [dcl.stc]p4).
8618       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8619                    diag::err_static_block_func);
8620       break;
8621     } else
8622       return SC_Static;
8623   }
8624   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8625   }
8626 
8627   // No explicit storage class has already been returned
8628   return SC_None;
8629 }
8630 
8631 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8632                                            DeclContext *DC, QualType &R,
8633                                            TypeSourceInfo *TInfo,
8634                                            StorageClass SC,
8635                                            bool &IsVirtualOkay) {
8636   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8637   DeclarationName Name = NameInfo.getName();
8638 
8639   FunctionDecl *NewFD = nullptr;
8640   bool isInline = D.getDeclSpec().isInlineSpecified();
8641 
8642   if (!SemaRef.getLangOpts().CPlusPlus) {
8643     // Determine whether the function was written with a
8644     // prototype. This true when:
8645     //   - there is a prototype in the declarator, or
8646     //   - the type R of the function is some kind of typedef or other non-
8647     //     attributed reference to a type name (which eventually refers to a
8648     //     function type).
8649     bool HasPrototype =
8650       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8651       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8652 
8653     NewFD = FunctionDecl::Create(
8654         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8655         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8656         ConstexprSpecKind::Unspecified,
8657         /*TrailingRequiresClause=*/nullptr);
8658     if (D.isInvalidType())
8659       NewFD->setInvalidDecl();
8660 
8661     return NewFD;
8662   }
8663 
8664   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8665 
8666   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8667   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8668     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8669                  diag::err_constexpr_wrong_decl_kind)
8670         << static_cast<int>(ConstexprKind);
8671     ConstexprKind = ConstexprSpecKind::Unspecified;
8672     D.getMutableDeclSpec().ClearConstexprSpec();
8673   }
8674   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8675 
8676   // Check that the return type is not an abstract class type.
8677   // For record types, this is done by the AbstractClassUsageDiagnoser once
8678   // the class has been completely parsed.
8679   if (!DC->isRecord() &&
8680       SemaRef.RequireNonAbstractType(
8681           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8682           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8683     D.setInvalidType();
8684 
8685   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8686     // This is a C++ constructor declaration.
8687     assert(DC->isRecord() &&
8688            "Constructors can only be declared in a member context");
8689 
8690     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8691     return CXXConstructorDecl::Create(
8692         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8693         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8694         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8695         InheritedConstructor(), TrailingRequiresClause);
8696 
8697   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8698     // This is a C++ destructor declaration.
8699     if (DC->isRecord()) {
8700       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8701       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8702       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8703           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8704           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8705           /*isImplicitlyDeclared=*/false, ConstexprKind,
8706           TrailingRequiresClause);
8707 
8708       // If the destructor needs an implicit exception specification, set it
8709       // now. FIXME: It'd be nice to be able to create the right type to start
8710       // with, but the type needs to reference the destructor declaration.
8711       if (SemaRef.getLangOpts().CPlusPlus11)
8712         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8713 
8714       IsVirtualOkay = true;
8715       return NewDD;
8716 
8717     } else {
8718       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8719       D.setInvalidType();
8720 
8721       // Create a FunctionDecl to satisfy the function definition parsing
8722       // code path.
8723       return FunctionDecl::Create(
8724           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8725           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8726           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8727     }
8728 
8729   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8730     if (!DC->isRecord()) {
8731       SemaRef.Diag(D.getIdentifierLoc(),
8732            diag::err_conv_function_not_member);
8733       return nullptr;
8734     }
8735 
8736     SemaRef.CheckConversionDeclarator(D, R, SC);
8737     if (D.isInvalidType())
8738       return nullptr;
8739 
8740     IsVirtualOkay = true;
8741     return CXXConversionDecl::Create(
8742         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8743         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8744         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8745         TrailingRequiresClause);
8746 
8747   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8748     if (TrailingRequiresClause)
8749       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8750                    diag::err_trailing_requires_clause_on_deduction_guide)
8751           << TrailingRequiresClause->getSourceRange();
8752     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8753 
8754     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8755                                          ExplicitSpecifier, NameInfo, R, TInfo,
8756                                          D.getEndLoc());
8757   } else if (DC->isRecord()) {
8758     // If the name of the function is the same as the name of the record,
8759     // then this must be an invalid constructor that has a return type.
8760     // (The parser checks for a return type and makes the declarator a
8761     // constructor if it has no return type).
8762     if (Name.getAsIdentifierInfo() &&
8763         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8764       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8765         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8766         << SourceRange(D.getIdentifierLoc());
8767       return nullptr;
8768     }
8769 
8770     // This is a C++ method declaration.
8771     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8772         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8773         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8774         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8775     IsVirtualOkay = !Ret->isStatic();
8776     return Ret;
8777   } else {
8778     bool isFriend =
8779         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8780     if (!isFriend && SemaRef.CurContext->isRecord())
8781       return nullptr;
8782 
8783     // Determine whether the function was written with a
8784     // prototype. This true when:
8785     //   - we're in C++ (where every function has a prototype),
8786     return FunctionDecl::Create(
8787         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8788         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8789         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8790   }
8791 }
8792 
8793 enum OpenCLParamType {
8794   ValidKernelParam,
8795   PtrPtrKernelParam,
8796   PtrKernelParam,
8797   InvalidAddrSpacePtrKernelParam,
8798   InvalidKernelParam,
8799   RecordKernelParam
8800 };
8801 
8802 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8803   // Size dependent types are just typedefs to normal integer types
8804   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8805   // integers other than by their names.
8806   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8807 
8808   // Remove typedefs one by one until we reach a typedef
8809   // for a size dependent type.
8810   QualType DesugaredTy = Ty;
8811   do {
8812     ArrayRef<StringRef> Names(SizeTypeNames);
8813     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8814     if (Names.end() != Match)
8815       return true;
8816 
8817     Ty = DesugaredTy;
8818     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8819   } while (DesugaredTy != Ty);
8820 
8821   return false;
8822 }
8823 
8824 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8825   if (PT->isDependentType())
8826     return InvalidKernelParam;
8827 
8828   if (PT->isPointerType() || PT->isReferenceType()) {
8829     QualType PointeeType = PT->getPointeeType();
8830     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8831         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8832         PointeeType.getAddressSpace() == LangAS::Default)
8833       return InvalidAddrSpacePtrKernelParam;
8834 
8835     if (PointeeType->isPointerType()) {
8836       // This is a pointer to pointer parameter.
8837       // Recursively check inner type.
8838       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8839       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8840           ParamKind == InvalidKernelParam)
8841         return ParamKind;
8842 
8843       return PtrPtrKernelParam;
8844     }
8845 
8846     // C++ for OpenCL v1.0 s2.4:
8847     // Moreover the types used in parameters of the kernel functions must be:
8848     // Standard layout types for pointer parameters. The same applies to
8849     // reference if an implementation supports them in kernel parameters.
8850     if (S.getLangOpts().OpenCLCPlusPlus &&
8851         !S.getOpenCLOptions().isAvailableOption(
8852             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8853         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8854         !PointeeType->isStandardLayoutType())
8855       return InvalidKernelParam;
8856 
8857     return PtrKernelParam;
8858   }
8859 
8860   // OpenCL v1.2 s6.9.k:
8861   // Arguments to kernel functions in a program cannot be declared with the
8862   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8863   // uintptr_t or a struct and/or union that contain fields declared to be one
8864   // of these built-in scalar types.
8865   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8866     return InvalidKernelParam;
8867 
8868   if (PT->isImageType())
8869     return PtrKernelParam;
8870 
8871   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8872     return InvalidKernelParam;
8873 
8874   // OpenCL extension spec v1.2 s9.5:
8875   // This extension adds support for half scalar and vector types as built-in
8876   // types that can be used for arithmetic operations, conversions etc.
8877   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8878       PT->isHalfType())
8879     return InvalidKernelParam;
8880 
8881   // Look into an array argument to check if it has a forbidden type.
8882   if (PT->isArrayType()) {
8883     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8884     // Call ourself to check an underlying type of an array. Since the
8885     // getPointeeOrArrayElementType returns an innermost type which is not an
8886     // array, this recursive call only happens once.
8887     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8888   }
8889 
8890   // C++ for OpenCL v1.0 s2.4:
8891   // Moreover the types used in parameters of the kernel functions must be:
8892   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8893   // types) for parameters passed by value;
8894   if (S.getLangOpts().OpenCLCPlusPlus &&
8895       !S.getOpenCLOptions().isAvailableOption(
8896           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8897       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8898     return InvalidKernelParam;
8899 
8900   if (PT->isRecordType())
8901     return RecordKernelParam;
8902 
8903   return ValidKernelParam;
8904 }
8905 
8906 static void checkIsValidOpenCLKernelParameter(
8907   Sema &S,
8908   Declarator &D,
8909   ParmVarDecl *Param,
8910   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8911   QualType PT = Param->getType();
8912 
8913   // Cache the valid types we encounter to avoid rechecking structs that are
8914   // used again
8915   if (ValidTypes.count(PT.getTypePtr()))
8916     return;
8917 
8918   switch (getOpenCLKernelParameterType(S, PT)) {
8919   case PtrPtrKernelParam:
8920     // OpenCL v3.0 s6.11.a:
8921     // A kernel function argument cannot be declared as a pointer to a pointer
8922     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8923     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8924       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8925       D.setInvalidType();
8926       return;
8927     }
8928 
8929     ValidTypes.insert(PT.getTypePtr());
8930     return;
8931 
8932   case InvalidAddrSpacePtrKernelParam:
8933     // OpenCL v1.0 s6.5:
8934     // __kernel function arguments declared to be a pointer of a type can point
8935     // to one of the following address spaces only : __global, __local or
8936     // __constant.
8937     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8938     D.setInvalidType();
8939     return;
8940 
8941     // OpenCL v1.2 s6.9.k:
8942     // Arguments to kernel functions in a program cannot be declared with the
8943     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8944     // uintptr_t or a struct and/or union that contain fields declared to be
8945     // one of these built-in scalar types.
8946 
8947   case InvalidKernelParam:
8948     // OpenCL v1.2 s6.8 n:
8949     // A kernel function argument cannot be declared
8950     // of event_t type.
8951     // Do not diagnose half type since it is diagnosed as invalid argument
8952     // type for any function elsewhere.
8953     if (!PT->isHalfType()) {
8954       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8955 
8956       // Explain what typedefs are involved.
8957       const TypedefType *Typedef = nullptr;
8958       while ((Typedef = PT->getAs<TypedefType>())) {
8959         SourceLocation Loc = Typedef->getDecl()->getLocation();
8960         // SourceLocation may be invalid for a built-in type.
8961         if (Loc.isValid())
8962           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8963         PT = Typedef->desugar();
8964       }
8965     }
8966 
8967     D.setInvalidType();
8968     return;
8969 
8970   case PtrKernelParam:
8971   case ValidKernelParam:
8972     ValidTypes.insert(PT.getTypePtr());
8973     return;
8974 
8975   case RecordKernelParam:
8976     break;
8977   }
8978 
8979   // Track nested structs we will inspect
8980   SmallVector<const Decl *, 4> VisitStack;
8981 
8982   // Track where we are in the nested structs. Items will migrate from
8983   // VisitStack to HistoryStack as we do the DFS for bad field.
8984   SmallVector<const FieldDecl *, 4> HistoryStack;
8985   HistoryStack.push_back(nullptr);
8986 
8987   // At this point we already handled everything except of a RecordType or
8988   // an ArrayType of a RecordType.
8989   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8990   const RecordType *RecTy =
8991       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8992   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8993 
8994   VisitStack.push_back(RecTy->getDecl());
8995   assert(VisitStack.back() && "First decl null?");
8996 
8997   do {
8998     const Decl *Next = VisitStack.pop_back_val();
8999     if (!Next) {
9000       assert(!HistoryStack.empty());
9001       // Found a marker, we have gone up a level
9002       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9003         ValidTypes.insert(Hist->getType().getTypePtr());
9004 
9005       continue;
9006     }
9007 
9008     // Adds everything except the original parameter declaration (which is not a
9009     // field itself) to the history stack.
9010     const RecordDecl *RD;
9011     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9012       HistoryStack.push_back(Field);
9013 
9014       QualType FieldTy = Field->getType();
9015       // Other field types (known to be valid or invalid) are handled while we
9016       // walk around RecordDecl::fields().
9017       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9018              "Unexpected type.");
9019       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9020 
9021       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9022     } else {
9023       RD = cast<RecordDecl>(Next);
9024     }
9025 
9026     // Add a null marker so we know when we've gone back up a level
9027     VisitStack.push_back(nullptr);
9028 
9029     for (const auto *FD : RD->fields()) {
9030       QualType QT = FD->getType();
9031 
9032       if (ValidTypes.count(QT.getTypePtr()))
9033         continue;
9034 
9035       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9036       if (ParamType == ValidKernelParam)
9037         continue;
9038 
9039       if (ParamType == RecordKernelParam) {
9040         VisitStack.push_back(FD);
9041         continue;
9042       }
9043 
9044       // OpenCL v1.2 s6.9.p:
9045       // Arguments to kernel functions that are declared to be a struct or union
9046       // do not allow OpenCL objects to be passed as elements of the struct or
9047       // union.
9048       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9049           ParamType == InvalidAddrSpacePtrKernelParam) {
9050         S.Diag(Param->getLocation(),
9051                diag::err_record_with_pointers_kernel_param)
9052           << PT->isUnionType()
9053           << PT;
9054       } else {
9055         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9056       }
9057 
9058       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9059           << OrigRecDecl->getDeclName();
9060 
9061       // We have an error, now let's go back up through history and show where
9062       // the offending field came from
9063       for (ArrayRef<const FieldDecl *>::const_iterator
9064                I = HistoryStack.begin() + 1,
9065                E = HistoryStack.end();
9066            I != E; ++I) {
9067         const FieldDecl *OuterField = *I;
9068         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9069           << OuterField->getType();
9070       }
9071 
9072       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9073         << QT->isPointerType()
9074         << QT;
9075       D.setInvalidType();
9076       return;
9077     }
9078   } while (!VisitStack.empty());
9079 }
9080 
9081 /// Find the DeclContext in which a tag is implicitly declared if we see an
9082 /// elaborated type specifier in the specified context, and lookup finds
9083 /// nothing.
9084 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9085   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9086     DC = DC->getParent();
9087   return DC;
9088 }
9089 
9090 /// Find the Scope in which a tag is implicitly declared if we see an
9091 /// elaborated type specifier in the specified context, and lookup finds
9092 /// nothing.
9093 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9094   while (S->isClassScope() ||
9095          (LangOpts.CPlusPlus &&
9096           S->isFunctionPrototypeScope()) ||
9097          ((S->getFlags() & Scope::DeclScope) == 0) ||
9098          (S->getEntity() && S->getEntity()->isTransparentContext()))
9099     S = S->getParent();
9100   return S;
9101 }
9102 
9103 NamedDecl*
9104 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9105                               TypeSourceInfo *TInfo, LookupResult &Previous,
9106                               MultiTemplateParamsArg TemplateParamListsRef,
9107                               bool &AddToScope) {
9108   QualType R = TInfo->getType();
9109 
9110   assert(R->isFunctionType());
9111   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9112     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9113 
9114   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9115   for (TemplateParameterList *TPL : TemplateParamListsRef)
9116     TemplateParamLists.push_back(TPL);
9117   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9118     if (!TemplateParamLists.empty() &&
9119         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9120       TemplateParamLists.back() = Invented;
9121     else
9122       TemplateParamLists.push_back(Invented);
9123   }
9124 
9125   // TODO: consider using NameInfo for diagnostic.
9126   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9127   DeclarationName Name = NameInfo.getName();
9128   StorageClass SC = getFunctionStorageClass(*this, D);
9129 
9130   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9131     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9132          diag::err_invalid_thread)
9133       << DeclSpec::getSpecifierName(TSCS);
9134 
9135   if (D.isFirstDeclarationOfMember())
9136     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9137                            D.getIdentifierLoc());
9138 
9139   bool isFriend = false;
9140   FunctionTemplateDecl *FunctionTemplate = nullptr;
9141   bool isMemberSpecialization = false;
9142   bool isFunctionTemplateSpecialization = false;
9143 
9144   bool isDependentClassScopeExplicitSpecialization = false;
9145   bool HasExplicitTemplateArgs = false;
9146   TemplateArgumentListInfo TemplateArgs;
9147 
9148   bool isVirtualOkay = false;
9149 
9150   DeclContext *OriginalDC = DC;
9151   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9152 
9153   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9154                                               isVirtualOkay);
9155   if (!NewFD) return nullptr;
9156 
9157   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9158     NewFD->setTopLevelDeclInObjCContainer();
9159 
9160   // Set the lexical context. If this is a function-scope declaration, or has a
9161   // C++ scope specifier, or is the object of a friend declaration, the lexical
9162   // context will be different from the semantic context.
9163   NewFD->setLexicalDeclContext(CurContext);
9164 
9165   if (IsLocalExternDecl)
9166     NewFD->setLocalExternDecl();
9167 
9168   if (getLangOpts().CPlusPlus) {
9169     bool isInline = D.getDeclSpec().isInlineSpecified();
9170     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9171     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9172     isFriend = D.getDeclSpec().isFriendSpecified();
9173     if (isFriend && !isInline && D.isFunctionDefinition()) {
9174       // C++ [class.friend]p5
9175       //   A function can be defined in a friend declaration of a
9176       //   class . . . . Such a function is implicitly inline.
9177       NewFD->setImplicitlyInline();
9178     }
9179 
9180     // If this is a method defined in an __interface, and is not a constructor
9181     // or an overloaded operator, then set the pure flag (isVirtual will already
9182     // return true).
9183     if (const CXXRecordDecl *Parent =
9184           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9185       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9186         NewFD->setPure(true);
9187 
9188       // C++ [class.union]p2
9189       //   A union can have member functions, but not virtual functions.
9190       if (isVirtual && Parent->isUnion()) {
9191         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9192         NewFD->setInvalidDecl();
9193       }
9194       if ((Parent->isClass() || Parent->isStruct()) &&
9195           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9196           NewFD->getKind() == Decl::Kind::CXXMethod &&
9197           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9198         if (auto *Def = Parent->getDefinition())
9199           Def->setInitMethod(true);
9200       }
9201     }
9202 
9203     SetNestedNameSpecifier(*this, NewFD, D);
9204     isMemberSpecialization = false;
9205     isFunctionTemplateSpecialization = false;
9206     if (D.isInvalidType())
9207       NewFD->setInvalidDecl();
9208 
9209     // Match up the template parameter lists with the scope specifier, then
9210     // determine whether we have a template or a template specialization.
9211     bool Invalid = false;
9212     TemplateParameterList *TemplateParams =
9213         MatchTemplateParametersToScopeSpecifier(
9214             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9215             D.getCXXScopeSpec(),
9216             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9217                 ? D.getName().TemplateId
9218                 : nullptr,
9219             TemplateParamLists, isFriend, isMemberSpecialization,
9220             Invalid);
9221     if (TemplateParams) {
9222       // Check that we can declare a template here.
9223       if (CheckTemplateDeclScope(S, TemplateParams))
9224         NewFD->setInvalidDecl();
9225 
9226       if (TemplateParams->size() > 0) {
9227         // This is a function template
9228 
9229         // A destructor cannot be a template.
9230         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9231           Diag(NewFD->getLocation(), diag::err_destructor_template);
9232           NewFD->setInvalidDecl();
9233         }
9234 
9235         // If we're adding a template to a dependent context, we may need to
9236         // rebuilding some of the types used within the template parameter list,
9237         // now that we know what the current instantiation is.
9238         if (DC->isDependentContext()) {
9239           ContextRAII SavedContext(*this, DC);
9240           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9241             Invalid = true;
9242         }
9243 
9244         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9245                                                         NewFD->getLocation(),
9246                                                         Name, TemplateParams,
9247                                                         NewFD);
9248         FunctionTemplate->setLexicalDeclContext(CurContext);
9249         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9250 
9251         // For source fidelity, store the other template param lists.
9252         if (TemplateParamLists.size() > 1) {
9253           NewFD->setTemplateParameterListsInfo(Context,
9254               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9255                   .drop_back(1));
9256         }
9257       } else {
9258         // This is a function template specialization.
9259         isFunctionTemplateSpecialization = true;
9260         // For source fidelity, store all the template param lists.
9261         if (TemplateParamLists.size() > 0)
9262           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9263 
9264         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9265         if (isFriend) {
9266           // We want to remove the "template<>", found here.
9267           SourceRange RemoveRange = TemplateParams->getSourceRange();
9268 
9269           // If we remove the template<> and the name is not a
9270           // template-id, we're actually silently creating a problem:
9271           // the friend declaration will refer to an untemplated decl,
9272           // and clearly the user wants a template specialization.  So
9273           // we need to insert '<>' after the name.
9274           SourceLocation InsertLoc;
9275           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9276             InsertLoc = D.getName().getSourceRange().getEnd();
9277             InsertLoc = getLocForEndOfToken(InsertLoc);
9278           }
9279 
9280           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9281             << Name << RemoveRange
9282             << FixItHint::CreateRemoval(RemoveRange)
9283             << FixItHint::CreateInsertion(InsertLoc, "<>");
9284           Invalid = true;
9285         }
9286       }
9287     } else {
9288       // Check that we can declare a template here.
9289       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9290           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9291         NewFD->setInvalidDecl();
9292 
9293       // All template param lists were matched against the scope specifier:
9294       // this is NOT (an explicit specialization of) a template.
9295       if (TemplateParamLists.size() > 0)
9296         // For source fidelity, store all the template param lists.
9297         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9298     }
9299 
9300     if (Invalid) {
9301       NewFD->setInvalidDecl();
9302       if (FunctionTemplate)
9303         FunctionTemplate->setInvalidDecl();
9304     }
9305 
9306     // C++ [dcl.fct.spec]p5:
9307     //   The virtual specifier shall only be used in declarations of
9308     //   nonstatic class member functions that appear within a
9309     //   member-specification of a class declaration; see 10.3.
9310     //
9311     if (isVirtual && !NewFD->isInvalidDecl()) {
9312       if (!isVirtualOkay) {
9313         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9314              diag::err_virtual_non_function);
9315       } else if (!CurContext->isRecord()) {
9316         // 'virtual' was specified outside of the class.
9317         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9318              diag::err_virtual_out_of_class)
9319           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9320       } else if (NewFD->getDescribedFunctionTemplate()) {
9321         // C++ [temp.mem]p3:
9322         //  A member function template shall not be virtual.
9323         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9324              diag::err_virtual_member_function_template)
9325           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9326       } else {
9327         // Okay: Add virtual to the method.
9328         NewFD->setVirtualAsWritten(true);
9329       }
9330 
9331       if (getLangOpts().CPlusPlus14 &&
9332           NewFD->getReturnType()->isUndeducedType())
9333         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9334     }
9335 
9336     if (getLangOpts().CPlusPlus14 &&
9337         (NewFD->isDependentContext() ||
9338          (isFriend && CurContext->isDependentContext())) &&
9339         NewFD->getReturnType()->isUndeducedType()) {
9340       // If the function template is referenced directly (for instance, as a
9341       // member of the current instantiation), pretend it has a dependent type.
9342       // This is not really justified by the standard, but is the only sane
9343       // thing to do.
9344       // FIXME: For a friend function, we have not marked the function as being
9345       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9346       const FunctionProtoType *FPT =
9347           NewFD->getType()->castAs<FunctionProtoType>();
9348       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9349       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9350                                              FPT->getExtProtoInfo()));
9351     }
9352 
9353     // C++ [dcl.fct.spec]p3:
9354     //  The inline specifier shall not appear on a block scope function
9355     //  declaration.
9356     if (isInline && !NewFD->isInvalidDecl()) {
9357       if (CurContext->isFunctionOrMethod()) {
9358         // 'inline' is not allowed on block scope function declaration.
9359         Diag(D.getDeclSpec().getInlineSpecLoc(),
9360              diag::err_inline_declaration_block_scope) << Name
9361           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9362       }
9363     }
9364 
9365     // C++ [dcl.fct.spec]p6:
9366     //  The explicit specifier shall be used only in the declaration of a
9367     //  constructor or conversion function within its class definition;
9368     //  see 12.3.1 and 12.3.2.
9369     if (hasExplicit && !NewFD->isInvalidDecl() &&
9370         !isa<CXXDeductionGuideDecl>(NewFD)) {
9371       if (!CurContext->isRecord()) {
9372         // 'explicit' was specified outside of the class.
9373         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9374              diag::err_explicit_out_of_class)
9375             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9376       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9377                  !isa<CXXConversionDecl>(NewFD)) {
9378         // 'explicit' was specified on a function that wasn't a constructor
9379         // or conversion function.
9380         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9381              diag::err_explicit_non_ctor_or_conv_function)
9382             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9383       }
9384     }
9385 
9386     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9387     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9388       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9389       // are implicitly inline.
9390       NewFD->setImplicitlyInline();
9391 
9392       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9393       // be either constructors or to return a literal type. Therefore,
9394       // destructors cannot be declared constexpr.
9395       if (isa<CXXDestructorDecl>(NewFD) &&
9396           (!getLangOpts().CPlusPlus20 ||
9397            ConstexprKind == ConstexprSpecKind::Consteval)) {
9398         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9399             << static_cast<int>(ConstexprKind);
9400         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9401                                     ? ConstexprSpecKind::Unspecified
9402                                     : ConstexprSpecKind::Constexpr);
9403       }
9404       // C++20 [dcl.constexpr]p2: An allocation function, or a
9405       // deallocation function shall not be declared with the consteval
9406       // specifier.
9407       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9408           (NewFD->getOverloadedOperator() == OO_New ||
9409            NewFD->getOverloadedOperator() == OO_Array_New ||
9410            NewFD->getOverloadedOperator() == OO_Delete ||
9411            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9412         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9413              diag::err_invalid_consteval_decl_kind)
9414             << NewFD;
9415         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9416       }
9417     }
9418 
9419     // If __module_private__ was specified, mark the function accordingly.
9420     if (D.getDeclSpec().isModulePrivateSpecified()) {
9421       if (isFunctionTemplateSpecialization) {
9422         SourceLocation ModulePrivateLoc
9423           = D.getDeclSpec().getModulePrivateSpecLoc();
9424         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9425           << 0
9426           << FixItHint::CreateRemoval(ModulePrivateLoc);
9427       } else {
9428         NewFD->setModulePrivate();
9429         if (FunctionTemplate)
9430           FunctionTemplate->setModulePrivate();
9431       }
9432     }
9433 
9434     if (isFriend) {
9435       if (FunctionTemplate) {
9436         FunctionTemplate->setObjectOfFriendDecl();
9437         FunctionTemplate->setAccess(AS_public);
9438       }
9439       NewFD->setObjectOfFriendDecl();
9440       NewFD->setAccess(AS_public);
9441     }
9442 
9443     // If a function is defined as defaulted or deleted, mark it as such now.
9444     // We'll do the relevant checks on defaulted / deleted functions later.
9445     switch (D.getFunctionDefinitionKind()) {
9446     case FunctionDefinitionKind::Declaration:
9447     case FunctionDefinitionKind::Definition:
9448       break;
9449 
9450     case FunctionDefinitionKind::Defaulted:
9451       NewFD->setDefaulted();
9452       break;
9453 
9454     case FunctionDefinitionKind::Deleted:
9455       NewFD->setDeletedAsWritten();
9456       break;
9457     }
9458 
9459     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9460         D.isFunctionDefinition()) {
9461       // C++ [class.mfct]p2:
9462       //   A member function may be defined (8.4) in its class definition, in
9463       //   which case it is an inline member function (7.1.2)
9464       NewFD->setImplicitlyInline();
9465     }
9466 
9467     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9468         !CurContext->isRecord()) {
9469       // C++ [class.static]p1:
9470       //   A data or function member of a class may be declared static
9471       //   in a class definition, in which case it is a static member of
9472       //   the class.
9473 
9474       // Complain about the 'static' specifier if it's on an out-of-line
9475       // member function definition.
9476 
9477       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9478       // member function template declaration and class member template
9479       // declaration (MSVC versions before 2015), warn about this.
9480       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9481            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9482              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9483            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9484            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9485         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9486     }
9487 
9488     // C++11 [except.spec]p15:
9489     //   A deallocation function with no exception-specification is treated
9490     //   as if it were specified with noexcept(true).
9491     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9492     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9493          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9494         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9495       NewFD->setType(Context.getFunctionType(
9496           FPT->getReturnType(), FPT->getParamTypes(),
9497           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9498   }
9499 
9500   // Filter out previous declarations that don't match the scope.
9501   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9502                        D.getCXXScopeSpec().isNotEmpty() ||
9503                        isMemberSpecialization ||
9504                        isFunctionTemplateSpecialization);
9505 
9506   // Handle GNU asm-label extension (encoded as an attribute).
9507   if (Expr *E = (Expr*) D.getAsmLabel()) {
9508     // The parser guarantees this is a string.
9509     StringLiteral *SE = cast<StringLiteral>(E);
9510     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9511                                         /*IsLiteralLabel=*/true,
9512                                         SE->getStrTokenLoc(0)));
9513   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9514     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9515       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9516     if (I != ExtnameUndeclaredIdentifiers.end()) {
9517       if (isDeclExternC(NewFD)) {
9518         NewFD->addAttr(I->second);
9519         ExtnameUndeclaredIdentifiers.erase(I);
9520       } else
9521         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9522             << /*Variable*/0 << NewFD;
9523     }
9524   }
9525 
9526   // Copy the parameter declarations from the declarator D to the function
9527   // declaration NewFD, if they are available.  First scavenge them into Params.
9528   SmallVector<ParmVarDecl*, 16> Params;
9529   unsigned FTIIdx;
9530   if (D.isFunctionDeclarator(FTIIdx)) {
9531     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9532 
9533     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9534     // function that takes no arguments, not a function that takes a
9535     // single void argument.
9536     // We let through "const void" here because Sema::GetTypeForDeclarator
9537     // already checks for that case.
9538     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9539       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9540         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9541         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9542         Param->setDeclContext(NewFD);
9543         Params.push_back(Param);
9544 
9545         if (Param->isInvalidDecl())
9546           NewFD->setInvalidDecl();
9547       }
9548     }
9549 
9550     if (!getLangOpts().CPlusPlus) {
9551       // In C, find all the tag declarations from the prototype and move them
9552       // into the function DeclContext. Remove them from the surrounding tag
9553       // injection context of the function, which is typically but not always
9554       // the TU.
9555       DeclContext *PrototypeTagContext =
9556           getTagInjectionContext(NewFD->getLexicalDeclContext());
9557       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9558         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9559 
9560         // We don't want to reparent enumerators. Look at their parent enum
9561         // instead.
9562         if (!TD) {
9563           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9564             TD = cast<EnumDecl>(ECD->getDeclContext());
9565         }
9566         if (!TD)
9567           continue;
9568         DeclContext *TagDC = TD->getLexicalDeclContext();
9569         if (!TagDC->containsDecl(TD))
9570           continue;
9571         TagDC->removeDecl(TD);
9572         TD->setDeclContext(NewFD);
9573         NewFD->addDecl(TD);
9574 
9575         // Preserve the lexical DeclContext if it is not the surrounding tag
9576         // injection context of the FD. In this example, the semantic context of
9577         // E will be f and the lexical context will be S, while both the
9578         // semantic and lexical contexts of S will be f:
9579         //   void f(struct S { enum E { a } f; } s);
9580         if (TagDC != PrototypeTagContext)
9581           TD->setLexicalDeclContext(TagDC);
9582       }
9583     }
9584   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9585     // When we're declaring a function with a typedef, typeof, etc as in the
9586     // following example, we'll need to synthesize (unnamed)
9587     // parameters for use in the declaration.
9588     //
9589     // @code
9590     // typedef void fn(int);
9591     // fn f;
9592     // @endcode
9593 
9594     // Synthesize a parameter for each argument type.
9595     for (const auto &AI : FT->param_types()) {
9596       ParmVarDecl *Param =
9597           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9598       Param->setScopeInfo(0, Params.size());
9599       Params.push_back(Param);
9600     }
9601   } else {
9602     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9603            "Should not need args for typedef of non-prototype fn");
9604   }
9605 
9606   // Finally, we know we have the right number of parameters, install them.
9607   NewFD->setParams(Params);
9608 
9609   if (D.getDeclSpec().isNoreturnSpecified())
9610     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9611                                            D.getDeclSpec().getNoreturnSpecLoc(),
9612                                            AttributeCommonInfo::AS_Keyword));
9613 
9614   // Functions returning a variably modified type violate C99 6.7.5.2p2
9615   // because all functions have linkage.
9616   if (!NewFD->isInvalidDecl() &&
9617       NewFD->getReturnType()->isVariablyModifiedType()) {
9618     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9619     NewFD->setInvalidDecl();
9620   }
9621 
9622   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9623   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9624       !NewFD->hasAttr<SectionAttr>())
9625     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9626         Context, PragmaClangTextSection.SectionName,
9627         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9628 
9629   // Apply an implicit SectionAttr if #pragma code_seg is active.
9630   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9631       !NewFD->hasAttr<SectionAttr>()) {
9632     NewFD->addAttr(SectionAttr::CreateImplicit(
9633         Context, CodeSegStack.CurrentValue->getString(),
9634         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9635         SectionAttr::Declspec_allocate));
9636     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9637                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9638                          ASTContext::PSF_Read,
9639                      NewFD))
9640       NewFD->dropAttr<SectionAttr>();
9641   }
9642 
9643   // Apply an implicit CodeSegAttr from class declspec or
9644   // apply an implicit SectionAttr from #pragma code_seg if active.
9645   if (!NewFD->hasAttr<CodeSegAttr>()) {
9646     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9647                                                                  D.isFunctionDefinition())) {
9648       NewFD->addAttr(SAttr);
9649     }
9650   }
9651 
9652   // Handle attributes.
9653   ProcessDeclAttributes(S, NewFD, D);
9654 
9655   if (getLangOpts().OpenCL) {
9656     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9657     // type declaration will generate a compilation error.
9658     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9659     if (AddressSpace != LangAS::Default) {
9660       Diag(NewFD->getLocation(),
9661            diag::err_opencl_return_value_with_address_space);
9662       NewFD->setInvalidDecl();
9663     }
9664   }
9665 
9666   if (!getLangOpts().CPlusPlus) {
9667     // Perform semantic checking on the function declaration.
9668     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9669       CheckMain(NewFD, D.getDeclSpec());
9670 
9671     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9672       CheckMSVCRTEntryPoint(NewFD);
9673 
9674     if (!NewFD->isInvalidDecl())
9675       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9676                                                   isMemberSpecialization));
9677     else if (!Previous.empty())
9678       // Recover gracefully from an invalid redeclaration.
9679       D.setRedeclaration(true);
9680     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9681             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9682            "previous declaration set still overloaded");
9683 
9684     // Diagnose no-prototype function declarations with calling conventions that
9685     // don't support variadic calls. Only do this in C and do it after merging
9686     // possibly prototyped redeclarations.
9687     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9688     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9689       CallingConv CC = FT->getExtInfo().getCC();
9690       if (!supportsVariadicCall(CC)) {
9691         // Windows system headers sometimes accidentally use stdcall without
9692         // (void) parameters, so we relax this to a warning.
9693         int DiagID =
9694             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9695         Diag(NewFD->getLocation(), DiagID)
9696             << FunctionType::getNameForCallConv(CC);
9697       }
9698     }
9699 
9700    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9701        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9702      checkNonTrivialCUnion(NewFD->getReturnType(),
9703                            NewFD->getReturnTypeSourceRange().getBegin(),
9704                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9705   } else {
9706     // C++11 [replacement.functions]p3:
9707     //  The program's definitions shall not be specified as inline.
9708     //
9709     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9710     //
9711     // Suppress the diagnostic if the function is __attribute__((used)), since
9712     // that forces an external definition to be emitted.
9713     if (D.getDeclSpec().isInlineSpecified() &&
9714         NewFD->isReplaceableGlobalAllocationFunction() &&
9715         !NewFD->hasAttr<UsedAttr>())
9716       Diag(D.getDeclSpec().getInlineSpecLoc(),
9717            diag::ext_operator_new_delete_declared_inline)
9718         << NewFD->getDeclName();
9719 
9720     // If the declarator is a template-id, translate the parser's template
9721     // argument list into our AST format.
9722     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9723       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9724       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9725       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9726       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9727                                          TemplateId->NumArgs);
9728       translateTemplateArguments(TemplateArgsPtr,
9729                                  TemplateArgs);
9730 
9731       HasExplicitTemplateArgs = true;
9732 
9733       if (NewFD->isInvalidDecl()) {
9734         HasExplicitTemplateArgs = false;
9735       } else if (FunctionTemplate) {
9736         // Function template with explicit template arguments.
9737         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9738           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9739 
9740         HasExplicitTemplateArgs = false;
9741       } else {
9742         assert((isFunctionTemplateSpecialization ||
9743                 D.getDeclSpec().isFriendSpecified()) &&
9744                "should have a 'template<>' for this decl");
9745         // "friend void foo<>(int);" is an implicit specialization decl.
9746         isFunctionTemplateSpecialization = true;
9747       }
9748     } else if (isFriend && isFunctionTemplateSpecialization) {
9749       // This combination is only possible in a recovery case;  the user
9750       // wrote something like:
9751       //   template <> friend void foo(int);
9752       // which we're recovering from as if the user had written:
9753       //   friend void foo<>(int);
9754       // Go ahead and fake up a template id.
9755       HasExplicitTemplateArgs = true;
9756       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9757       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9758     }
9759 
9760     // We do not add HD attributes to specializations here because
9761     // they may have different constexpr-ness compared to their
9762     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9763     // may end up with different effective targets. Instead, a
9764     // specialization inherits its target attributes from its template
9765     // in the CheckFunctionTemplateSpecialization() call below.
9766     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9767       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9768 
9769     // If it's a friend (and only if it's a friend), it's possible
9770     // that either the specialized function type or the specialized
9771     // template is dependent, and therefore matching will fail.  In
9772     // this case, don't check the specialization yet.
9773     if (isFunctionTemplateSpecialization && isFriend &&
9774         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9775          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9776              TemplateArgs.arguments()))) {
9777       assert(HasExplicitTemplateArgs &&
9778              "friend function specialization without template args");
9779       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9780                                                        Previous))
9781         NewFD->setInvalidDecl();
9782     } else if (isFunctionTemplateSpecialization) {
9783       if (CurContext->isDependentContext() && CurContext->isRecord()
9784           && !isFriend) {
9785         isDependentClassScopeExplicitSpecialization = true;
9786       } else if (!NewFD->isInvalidDecl() &&
9787                  CheckFunctionTemplateSpecialization(
9788                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9789                      Previous))
9790         NewFD->setInvalidDecl();
9791 
9792       // C++ [dcl.stc]p1:
9793       //   A storage-class-specifier shall not be specified in an explicit
9794       //   specialization (14.7.3)
9795       FunctionTemplateSpecializationInfo *Info =
9796           NewFD->getTemplateSpecializationInfo();
9797       if (Info && SC != SC_None) {
9798         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9799           Diag(NewFD->getLocation(),
9800                diag::err_explicit_specialization_inconsistent_storage_class)
9801             << SC
9802             << FixItHint::CreateRemoval(
9803                                       D.getDeclSpec().getStorageClassSpecLoc());
9804 
9805         else
9806           Diag(NewFD->getLocation(),
9807                diag::ext_explicit_specialization_storage_class)
9808             << FixItHint::CreateRemoval(
9809                                       D.getDeclSpec().getStorageClassSpecLoc());
9810       }
9811     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9812       if (CheckMemberSpecialization(NewFD, Previous))
9813           NewFD->setInvalidDecl();
9814     }
9815 
9816     // Perform semantic checking on the function declaration.
9817     if (!isDependentClassScopeExplicitSpecialization) {
9818       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9819         CheckMain(NewFD, D.getDeclSpec());
9820 
9821       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9822         CheckMSVCRTEntryPoint(NewFD);
9823 
9824       if (!NewFD->isInvalidDecl())
9825         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9826                                                     isMemberSpecialization));
9827       else if (!Previous.empty())
9828         // Recover gracefully from an invalid redeclaration.
9829         D.setRedeclaration(true);
9830     }
9831 
9832     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9833             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9834            "previous declaration set still overloaded");
9835 
9836     NamedDecl *PrincipalDecl = (FunctionTemplate
9837                                 ? cast<NamedDecl>(FunctionTemplate)
9838                                 : NewFD);
9839 
9840     if (isFriend && NewFD->getPreviousDecl()) {
9841       AccessSpecifier Access = AS_public;
9842       if (!NewFD->isInvalidDecl())
9843         Access = NewFD->getPreviousDecl()->getAccess();
9844 
9845       NewFD->setAccess(Access);
9846       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9847     }
9848 
9849     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9850         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9851       PrincipalDecl->setNonMemberOperator();
9852 
9853     // If we have a function template, check the template parameter
9854     // list. This will check and merge default template arguments.
9855     if (FunctionTemplate) {
9856       FunctionTemplateDecl *PrevTemplate =
9857                                      FunctionTemplate->getPreviousDecl();
9858       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9859                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9860                                     : nullptr,
9861                             D.getDeclSpec().isFriendSpecified()
9862                               ? (D.isFunctionDefinition()
9863                                    ? TPC_FriendFunctionTemplateDefinition
9864                                    : TPC_FriendFunctionTemplate)
9865                               : (D.getCXXScopeSpec().isSet() &&
9866                                  DC && DC->isRecord() &&
9867                                  DC->isDependentContext())
9868                                   ? TPC_ClassTemplateMember
9869                                   : TPC_FunctionTemplate);
9870     }
9871 
9872     if (NewFD->isInvalidDecl()) {
9873       // Ignore all the rest of this.
9874     } else if (!D.isRedeclaration()) {
9875       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9876                                        AddToScope };
9877       // Fake up an access specifier if it's supposed to be a class member.
9878       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9879         NewFD->setAccess(AS_public);
9880 
9881       // Qualified decls generally require a previous declaration.
9882       if (D.getCXXScopeSpec().isSet()) {
9883         // ...with the major exception of templated-scope or
9884         // dependent-scope friend declarations.
9885 
9886         // TODO: we currently also suppress this check in dependent
9887         // contexts because (1) the parameter depth will be off when
9888         // matching friend templates and (2) we might actually be
9889         // selecting a friend based on a dependent factor.  But there
9890         // are situations where these conditions don't apply and we
9891         // can actually do this check immediately.
9892         //
9893         // Unless the scope is dependent, it's always an error if qualified
9894         // redeclaration lookup found nothing at all. Diagnose that now;
9895         // nothing will diagnose that error later.
9896         if (isFriend &&
9897             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9898              (!Previous.empty() && CurContext->isDependentContext()))) {
9899           // ignore these
9900         } else if (NewFD->isCPUDispatchMultiVersion() ||
9901                    NewFD->isCPUSpecificMultiVersion()) {
9902           // ignore this, we allow the redeclaration behavior here to create new
9903           // versions of the function.
9904         } else {
9905           // The user tried to provide an out-of-line definition for a
9906           // function that is a member of a class or namespace, but there
9907           // was no such member function declared (C++ [class.mfct]p2,
9908           // C++ [namespace.memdef]p2). For example:
9909           //
9910           // class X {
9911           //   void f() const;
9912           // };
9913           //
9914           // void X::f() { } // ill-formed
9915           //
9916           // Complain about this problem, and attempt to suggest close
9917           // matches (e.g., those that differ only in cv-qualifiers and
9918           // whether the parameter types are references).
9919 
9920           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9921                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9922             AddToScope = ExtraArgs.AddToScope;
9923             return Result;
9924           }
9925         }
9926 
9927         // Unqualified local friend declarations are required to resolve
9928         // to something.
9929       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9930         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9931                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9932           AddToScope = ExtraArgs.AddToScope;
9933           return Result;
9934         }
9935       }
9936     } else if (!D.isFunctionDefinition() &&
9937                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9938                !isFriend && !isFunctionTemplateSpecialization &&
9939                !isMemberSpecialization) {
9940       // An out-of-line member function declaration must also be a
9941       // definition (C++ [class.mfct]p2).
9942       // Note that this is not the case for explicit specializations of
9943       // function templates or member functions of class templates, per
9944       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9945       // extension for compatibility with old SWIG code which likes to
9946       // generate them.
9947       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9948         << D.getCXXScopeSpec().getRange();
9949     }
9950   }
9951 
9952   // If this is the first declaration of a library builtin function, add
9953   // attributes as appropriate.
9954   if (!D.isRedeclaration() &&
9955       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9956     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9957       if (unsigned BuiltinID = II->getBuiltinID()) {
9958         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9959           // Validate the type matches unless this builtin is specified as
9960           // matching regardless of its declared type.
9961           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9962             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9963           } else {
9964             ASTContext::GetBuiltinTypeError Error;
9965             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9966             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9967 
9968             if (!Error && !BuiltinType.isNull() &&
9969                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9970                     NewFD->getType(), BuiltinType))
9971               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9972           }
9973         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9974                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9975           // FIXME: We should consider this a builtin only in the std namespace.
9976           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9977         }
9978       }
9979     }
9980   }
9981 
9982   ProcessPragmaWeak(S, NewFD);
9983   checkAttributesAfterMerging(*this, *NewFD);
9984 
9985   AddKnownFunctionAttributes(NewFD);
9986 
9987   if (NewFD->hasAttr<OverloadableAttr>() &&
9988       !NewFD->getType()->getAs<FunctionProtoType>()) {
9989     Diag(NewFD->getLocation(),
9990          diag::err_attribute_overloadable_no_prototype)
9991       << NewFD;
9992 
9993     // Turn this into a variadic function with no parameters.
9994     const auto *FT = NewFD->getType()->castAs<FunctionType>();
9995     FunctionProtoType::ExtProtoInfo EPI(
9996         Context.getDefaultCallingConvention(true, false));
9997     EPI.Variadic = true;
9998     EPI.ExtInfo = FT->getExtInfo();
9999 
10000     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10001     NewFD->setType(R);
10002   }
10003 
10004   // If there's a #pragma GCC visibility in scope, and this isn't a class
10005   // member, set the visibility of this function.
10006   if (!DC->isRecord() && NewFD->isExternallyVisible())
10007     AddPushedVisibilityAttribute(NewFD);
10008 
10009   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10010   // marking the function.
10011   AddCFAuditedAttribute(NewFD);
10012 
10013   // If this is a function definition, check if we have to apply optnone due to
10014   // a pragma.
10015   if(D.isFunctionDefinition())
10016     AddRangeBasedOptnone(NewFD);
10017 
10018   // If this is the first declaration of an extern C variable, update
10019   // the map of such variables.
10020   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10021       isIncompleteDeclExternC(*this, NewFD))
10022     RegisterLocallyScopedExternCDecl(NewFD, S);
10023 
10024   // Set this FunctionDecl's range up to the right paren.
10025   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10026 
10027   if (D.isRedeclaration() && !Previous.empty()) {
10028     NamedDecl *Prev = Previous.getRepresentativeDecl();
10029     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10030                                    isMemberSpecialization ||
10031                                        isFunctionTemplateSpecialization,
10032                                    D.isFunctionDefinition());
10033   }
10034 
10035   if (getLangOpts().CUDA) {
10036     IdentifierInfo *II = NewFD->getIdentifier();
10037     if (II && II->isStr(getCudaConfigureFuncName()) &&
10038         !NewFD->isInvalidDecl() &&
10039         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10040       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10041         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10042             << getCudaConfigureFuncName();
10043       Context.setcudaConfigureCallDecl(NewFD);
10044     }
10045 
10046     // Variadic functions, other than a *declaration* of printf, are not allowed
10047     // in device-side CUDA code, unless someone passed
10048     // -fcuda-allow-variadic-functions.
10049     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10050         (NewFD->hasAttr<CUDADeviceAttr>() ||
10051          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10052         !(II && II->isStr("printf") && NewFD->isExternC() &&
10053           !D.isFunctionDefinition())) {
10054       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10055     }
10056   }
10057 
10058   MarkUnusedFileScopedDecl(NewFD);
10059 
10060 
10061 
10062   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10063     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10064     if (SC == SC_Static) {
10065       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10066       D.setInvalidType();
10067     }
10068 
10069     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10070     if (!NewFD->getReturnType()->isVoidType()) {
10071       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10072       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10073           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10074                                 : FixItHint());
10075       D.setInvalidType();
10076     }
10077 
10078     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10079     for (auto Param : NewFD->parameters())
10080       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10081 
10082     if (getLangOpts().OpenCLCPlusPlus) {
10083       if (DC->isRecord()) {
10084         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10085         D.setInvalidType();
10086       }
10087       if (FunctionTemplate) {
10088         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10089         D.setInvalidType();
10090       }
10091     }
10092   }
10093 
10094   if (getLangOpts().CPlusPlus) {
10095     if (FunctionTemplate) {
10096       if (NewFD->isInvalidDecl())
10097         FunctionTemplate->setInvalidDecl();
10098       return FunctionTemplate;
10099     }
10100 
10101     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10102       CompleteMemberSpecialization(NewFD, Previous);
10103   }
10104 
10105   for (const ParmVarDecl *Param : NewFD->parameters()) {
10106     QualType PT = Param->getType();
10107 
10108     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10109     // types.
10110     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10111       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10112         QualType ElemTy = PipeTy->getElementType();
10113           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10114             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10115             D.setInvalidType();
10116           }
10117       }
10118     }
10119   }
10120 
10121   // Here we have an function template explicit specialization at class scope.
10122   // The actual specialization will be postponed to template instatiation
10123   // time via the ClassScopeFunctionSpecializationDecl node.
10124   if (isDependentClassScopeExplicitSpecialization) {
10125     ClassScopeFunctionSpecializationDecl *NewSpec =
10126                          ClassScopeFunctionSpecializationDecl::Create(
10127                                 Context, CurContext, NewFD->getLocation(),
10128                                 cast<CXXMethodDecl>(NewFD),
10129                                 HasExplicitTemplateArgs, TemplateArgs);
10130     CurContext->addDecl(NewSpec);
10131     AddToScope = false;
10132   }
10133 
10134   // Diagnose availability attributes. Availability cannot be used on functions
10135   // that are run during load/unload.
10136   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10137     if (NewFD->hasAttr<ConstructorAttr>()) {
10138       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10139           << 1;
10140       NewFD->dropAttr<AvailabilityAttr>();
10141     }
10142     if (NewFD->hasAttr<DestructorAttr>()) {
10143       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10144           << 2;
10145       NewFD->dropAttr<AvailabilityAttr>();
10146     }
10147   }
10148 
10149   // Diagnose no_builtin attribute on function declaration that are not a
10150   // definition.
10151   // FIXME: We should really be doing this in
10152   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10153   // the FunctionDecl and at this point of the code
10154   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10155   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10156   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10157     switch (D.getFunctionDefinitionKind()) {
10158     case FunctionDefinitionKind::Defaulted:
10159     case FunctionDefinitionKind::Deleted:
10160       Diag(NBA->getLocation(),
10161            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10162           << NBA->getSpelling();
10163       break;
10164     case FunctionDefinitionKind::Declaration:
10165       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10166           << NBA->getSpelling();
10167       break;
10168     case FunctionDefinitionKind::Definition:
10169       break;
10170     }
10171 
10172   return NewFD;
10173 }
10174 
10175 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10176 /// when __declspec(code_seg) "is applied to a class, all member functions of
10177 /// the class and nested classes -- this includes compiler-generated special
10178 /// member functions -- are put in the specified segment."
10179 /// The actual behavior is a little more complicated. The Microsoft compiler
10180 /// won't check outer classes if there is an active value from #pragma code_seg.
10181 /// The CodeSeg is always applied from the direct parent but only from outer
10182 /// classes when the #pragma code_seg stack is empty. See:
10183 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10184 /// available since MS has removed the page.
10185 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10186   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10187   if (!Method)
10188     return nullptr;
10189   const CXXRecordDecl *Parent = Method->getParent();
10190   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10191     Attr *NewAttr = SAttr->clone(S.getASTContext());
10192     NewAttr->setImplicit(true);
10193     return NewAttr;
10194   }
10195 
10196   // The Microsoft compiler won't check outer classes for the CodeSeg
10197   // when the #pragma code_seg stack is active.
10198   if (S.CodeSegStack.CurrentValue)
10199    return nullptr;
10200 
10201   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10202     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10203       Attr *NewAttr = SAttr->clone(S.getASTContext());
10204       NewAttr->setImplicit(true);
10205       return NewAttr;
10206     }
10207   }
10208   return nullptr;
10209 }
10210 
10211 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10212 /// containing class. Otherwise it will return implicit SectionAttr if the
10213 /// function is a definition and there is an active value on CodeSegStack
10214 /// (from the current #pragma code-seg value).
10215 ///
10216 /// \param FD Function being declared.
10217 /// \param IsDefinition Whether it is a definition or just a declarartion.
10218 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10219 ///          nullptr if no attribute should be added.
10220 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10221                                                        bool IsDefinition) {
10222   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10223     return A;
10224   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10225       CodeSegStack.CurrentValue)
10226     return SectionAttr::CreateImplicit(
10227         getASTContext(), CodeSegStack.CurrentValue->getString(),
10228         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10229         SectionAttr::Declspec_allocate);
10230   return nullptr;
10231 }
10232 
10233 /// Determines if we can perform a correct type check for \p D as a
10234 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10235 /// best-effort check.
10236 ///
10237 /// \param NewD The new declaration.
10238 /// \param OldD The old declaration.
10239 /// \param NewT The portion of the type of the new declaration to check.
10240 /// \param OldT The portion of the type of the old declaration to check.
10241 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10242                                           QualType NewT, QualType OldT) {
10243   if (!NewD->getLexicalDeclContext()->isDependentContext())
10244     return true;
10245 
10246   // For dependently-typed local extern declarations and friends, we can't
10247   // perform a correct type check in general until instantiation:
10248   //
10249   //   int f();
10250   //   template<typename T> void g() { T f(); }
10251   //
10252   // (valid if g() is only instantiated with T = int).
10253   if (NewT->isDependentType() &&
10254       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10255     return false;
10256 
10257   // Similarly, if the previous declaration was a dependent local extern
10258   // declaration, we don't really know its type yet.
10259   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10260     return false;
10261 
10262   return true;
10263 }
10264 
10265 /// Checks if the new declaration declared in dependent context must be
10266 /// put in the same redeclaration chain as the specified declaration.
10267 ///
10268 /// \param D Declaration that is checked.
10269 /// \param PrevDecl Previous declaration found with proper lookup method for the
10270 ///                 same declaration name.
10271 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10272 ///          belongs to.
10273 ///
10274 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10275   if (!D->getLexicalDeclContext()->isDependentContext())
10276     return true;
10277 
10278   // Don't chain dependent friend function definitions until instantiation, to
10279   // permit cases like
10280   //
10281   //   void func();
10282   //   template<typename T> class C1 { friend void func() {} };
10283   //   template<typename T> class C2 { friend void func() {} };
10284   //
10285   // ... which is valid if only one of C1 and C2 is ever instantiated.
10286   //
10287   // FIXME: This need only apply to function definitions. For now, we proxy
10288   // this by checking for a file-scope function. We do not want this to apply
10289   // to friend declarations nominating member functions, because that gets in
10290   // the way of access checks.
10291   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10292     return false;
10293 
10294   auto *VD = dyn_cast<ValueDecl>(D);
10295   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10296   return !VD || !PrevVD ||
10297          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10298                                         PrevVD->getType());
10299 }
10300 
10301 /// Check the target attribute of the function for MultiVersion
10302 /// validity.
10303 ///
10304 /// Returns true if there was an error, false otherwise.
10305 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10306   const auto *TA = FD->getAttr<TargetAttr>();
10307   assert(TA && "MultiVersion Candidate requires a target attribute");
10308   ParsedTargetAttr ParseInfo = TA->parse();
10309   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10310   enum ErrType { Feature = 0, Architecture = 1 };
10311 
10312   if (!ParseInfo.Architecture.empty() &&
10313       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10314     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10315         << Architecture << ParseInfo.Architecture;
10316     return true;
10317   }
10318 
10319   for (const auto &Feat : ParseInfo.Features) {
10320     auto BareFeat = StringRef{Feat}.substr(1);
10321     if (Feat[0] == '-') {
10322       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10323           << Feature << ("no-" + BareFeat).str();
10324       return true;
10325     }
10326 
10327     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10328         !TargetInfo.isValidFeatureName(BareFeat)) {
10329       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10330           << Feature << BareFeat;
10331       return true;
10332     }
10333   }
10334   return false;
10335 }
10336 
10337 // Provide a white-list of attributes that are allowed to be combined with
10338 // multiversion functions.
10339 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10340                                            MultiVersionKind MVType) {
10341   // Note: this list/diagnosis must match the list in
10342   // checkMultiversionAttributesAllSame.
10343   switch (Kind) {
10344   default:
10345     return false;
10346   case attr::Used:
10347     return MVType == MultiVersionKind::Target;
10348   case attr::NonNull:
10349   case attr::NoThrow:
10350     return true;
10351   }
10352 }
10353 
10354 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10355                                                  const FunctionDecl *FD,
10356                                                  const FunctionDecl *CausedFD,
10357                                                  MultiVersionKind MVType) {
10358   const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) {
10359     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10360         << static_cast<unsigned>(MVType) << A;
10361     if (CausedFD)
10362       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10363     return true;
10364   };
10365 
10366   for (const Attr *A : FD->attrs()) {
10367     switch (A->getKind()) {
10368     case attr::CPUDispatch:
10369     case attr::CPUSpecific:
10370       if (MVType != MultiVersionKind::CPUDispatch &&
10371           MVType != MultiVersionKind::CPUSpecific)
10372         return Diagnose(S, A);
10373       break;
10374     case attr::Target:
10375       if (MVType != MultiVersionKind::Target)
10376         return Diagnose(S, A);
10377       break;
10378     case attr::TargetClones:
10379       if (MVType != MultiVersionKind::TargetClones)
10380         return Diagnose(S, A);
10381       break;
10382     default:
10383       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10384         return Diagnose(S, A);
10385       break;
10386     }
10387   }
10388   return false;
10389 }
10390 
10391 bool Sema::areMultiversionVariantFunctionsCompatible(
10392     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10393     const PartialDiagnostic &NoProtoDiagID,
10394     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10395     const PartialDiagnosticAt &NoSupportDiagIDAt,
10396     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10397     bool ConstexprSupported, bool CLinkageMayDiffer) {
10398   enum DoesntSupport {
10399     FuncTemplates = 0,
10400     VirtFuncs = 1,
10401     DeducedReturn = 2,
10402     Constructors = 3,
10403     Destructors = 4,
10404     DeletedFuncs = 5,
10405     DefaultedFuncs = 6,
10406     ConstexprFuncs = 7,
10407     ConstevalFuncs = 8,
10408     Lambda = 9,
10409   };
10410   enum Different {
10411     CallingConv = 0,
10412     ReturnType = 1,
10413     ConstexprSpec = 2,
10414     InlineSpec = 3,
10415     Linkage = 4,
10416     LanguageLinkage = 5,
10417   };
10418 
10419   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10420       !OldFD->getType()->getAs<FunctionProtoType>()) {
10421     Diag(OldFD->getLocation(), NoProtoDiagID);
10422     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10423     return true;
10424   }
10425 
10426   if (NoProtoDiagID.getDiagID() != 0 &&
10427       !NewFD->getType()->getAs<FunctionProtoType>())
10428     return Diag(NewFD->getLocation(), NoProtoDiagID);
10429 
10430   if (!TemplatesSupported &&
10431       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10432     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10433            << FuncTemplates;
10434 
10435   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10436     if (NewCXXFD->isVirtual())
10437       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10438              << VirtFuncs;
10439 
10440     if (isa<CXXConstructorDecl>(NewCXXFD))
10441       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10442              << Constructors;
10443 
10444     if (isa<CXXDestructorDecl>(NewCXXFD))
10445       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10446              << Destructors;
10447   }
10448 
10449   if (NewFD->isDeleted())
10450     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10451            << DeletedFuncs;
10452 
10453   if (NewFD->isDefaulted())
10454     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10455            << DefaultedFuncs;
10456 
10457   if (!ConstexprSupported && NewFD->isConstexpr())
10458     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10459            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10460 
10461   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10462   const auto *NewType = cast<FunctionType>(NewQType);
10463   QualType NewReturnType = NewType->getReturnType();
10464 
10465   if (NewReturnType->isUndeducedType())
10466     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10467            << DeducedReturn;
10468 
10469   // Ensure the return type is identical.
10470   if (OldFD) {
10471     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10472     const auto *OldType = cast<FunctionType>(OldQType);
10473     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10474     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10475 
10476     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10477       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10478 
10479     QualType OldReturnType = OldType->getReturnType();
10480 
10481     if (OldReturnType != NewReturnType)
10482       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10483 
10484     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10485       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10486 
10487     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10488       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10489 
10490     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10491       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10492 
10493     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10494       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10495 
10496     if (CheckEquivalentExceptionSpec(
10497             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10498             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10499       return true;
10500   }
10501   return false;
10502 }
10503 
10504 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10505                                              const FunctionDecl *NewFD,
10506                                              bool CausesMV,
10507                                              MultiVersionKind MVType) {
10508   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10509     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10510     if (OldFD)
10511       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10512     return true;
10513   }
10514 
10515   bool IsCPUSpecificCPUDispatchMVType =
10516       MVType == MultiVersionKind::CPUDispatch ||
10517       MVType == MultiVersionKind::CPUSpecific;
10518 
10519   if (CausesMV && OldFD &&
10520       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10521     return true;
10522 
10523   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10524     return true;
10525 
10526   // Only allow transition to MultiVersion if it hasn't been used.
10527   if (OldFD && CausesMV && OldFD->isUsed(false))
10528     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10529 
10530   return S.areMultiversionVariantFunctionsCompatible(
10531       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10532       PartialDiagnosticAt(NewFD->getLocation(),
10533                           S.PDiag(diag::note_multiversioning_caused_here)),
10534       PartialDiagnosticAt(NewFD->getLocation(),
10535                           S.PDiag(diag::err_multiversion_doesnt_support)
10536                               << static_cast<unsigned>(MVType)),
10537       PartialDiagnosticAt(NewFD->getLocation(),
10538                           S.PDiag(diag::err_multiversion_diff)),
10539       /*TemplatesSupported=*/false,
10540       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10541       /*CLinkageMayDiffer=*/false);
10542 }
10543 
10544 /// Check the validity of a multiversion function declaration that is the
10545 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10546 ///
10547 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10548 ///
10549 /// Returns true if there was an error, false otherwise.
10550 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10551                                            MultiVersionKind MVType,
10552                                            const TargetAttr *TA) {
10553   assert(MVType != MultiVersionKind::None &&
10554          "Function lacks multiversion attribute");
10555 
10556   // Target only causes MV if it is default, otherwise this is a normal
10557   // function.
10558   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10559     return false;
10560 
10561   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10562     FD->setInvalidDecl();
10563     return true;
10564   }
10565 
10566   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10567     FD->setInvalidDecl();
10568     return true;
10569   }
10570 
10571   FD->setIsMultiVersion();
10572   return false;
10573 }
10574 
10575 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10576   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10577     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10578       return true;
10579   }
10580 
10581   return false;
10582 }
10583 
10584 static bool CheckTargetCausesMultiVersioning(
10585     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10586     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10587     LookupResult &Previous) {
10588   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10589   ParsedTargetAttr NewParsed = NewTA->parse();
10590   // Sort order doesn't matter, it just needs to be consistent.
10591   llvm::sort(NewParsed.Features);
10592 
10593   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10594   // to change, this is a simple redeclaration.
10595   if (!NewTA->isDefaultVersion() &&
10596       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10597     return false;
10598 
10599   // Otherwise, this decl causes MultiVersioning.
10600   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10601     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10602     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10603     NewFD->setInvalidDecl();
10604     return true;
10605   }
10606 
10607   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10608                                        MultiVersionKind::Target)) {
10609     NewFD->setInvalidDecl();
10610     return true;
10611   }
10612 
10613   if (CheckMultiVersionValue(S, NewFD)) {
10614     NewFD->setInvalidDecl();
10615     return true;
10616   }
10617 
10618   // If this is 'default', permit the forward declaration.
10619   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10620     Redeclaration = true;
10621     OldDecl = OldFD;
10622     OldFD->setIsMultiVersion();
10623     NewFD->setIsMultiVersion();
10624     return false;
10625   }
10626 
10627   if (CheckMultiVersionValue(S, OldFD)) {
10628     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10629     NewFD->setInvalidDecl();
10630     return true;
10631   }
10632 
10633   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10634 
10635   if (OldParsed == NewParsed) {
10636     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10637     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10638     NewFD->setInvalidDecl();
10639     return true;
10640   }
10641 
10642   for (const auto *FD : OldFD->redecls()) {
10643     const auto *CurTA = FD->getAttr<TargetAttr>();
10644     // We allow forward declarations before ANY multiversioning attributes, but
10645     // nothing after the fact.
10646     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10647         (!CurTA || CurTA->isInherited())) {
10648       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10649           << 0;
10650       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10651       NewFD->setInvalidDecl();
10652       return true;
10653     }
10654   }
10655 
10656   OldFD->setIsMultiVersion();
10657   NewFD->setIsMultiVersion();
10658   Redeclaration = false;
10659   MergeTypeWithPrevious = false;
10660   OldDecl = nullptr;
10661   Previous.clear();
10662   return false;
10663 }
10664 
10665 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10666                                         MultiVersionKind New) {
10667   if (Old == New || Old == MultiVersionKind::None ||
10668       New == MultiVersionKind::None)
10669     return true;
10670 
10671   return (Old == MultiVersionKind::CPUDispatch &&
10672           New == MultiVersionKind::CPUSpecific) ||
10673          (Old == MultiVersionKind::CPUSpecific &&
10674           New == MultiVersionKind::CPUDispatch);
10675 }
10676 
10677 /// Check the validity of a new function declaration being added to an existing
10678 /// multiversioned declaration collection.
10679 static bool CheckMultiVersionAdditionalDecl(
10680     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10681     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10682     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10683     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10684     bool &MergeTypeWithPrevious, LookupResult &Previous) {
10685 
10686   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10687   // Disallow mixing of multiversioning types.
10688   if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) {
10689     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10690     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10691     NewFD->setInvalidDecl();
10692     return true;
10693   }
10694 
10695   ParsedTargetAttr NewParsed;
10696   if (NewTA) {
10697     NewParsed = NewTA->parse();
10698     llvm::sort(NewParsed.Features);
10699   }
10700 
10701   bool UseMemberUsingDeclRules =
10702       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10703 
10704   // Next, check ALL non-overloads to see if this is a redeclaration of a
10705   // previous member of the MultiVersion set.
10706   for (NamedDecl *ND : Previous) {
10707     FunctionDecl *CurFD = ND->getAsFunction();
10708     if (!CurFD)
10709       continue;
10710     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10711       continue;
10712 
10713     switch (NewMVType) {
10714     case MultiVersionKind::None:
10715       assert(OldMVType == MultiVersionKind::TargetClones &&
10716              "Only target_clones can be omitted in subsequent declarations");
10717       break;
10718     case MultiVersionKind::Target: {
10719       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10720       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10721         NewFD->setIsMultiVersion();
10722         Redeclaration = true;
10723         OldDecl = ND;
10724         return false;
10725       }
10726 
10727       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10728       if (CurParsed == NewParsed) {
10729         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10730         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10731         NewFD->setInvalidDecl();
10732         return true;
10733       }
10734       break;
10735     }
10736     case MultiVersionKind::TargetClones: {
10737       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10738       Redeclaration = true;
10739       OldDecl = CurFD;
10740       MergeTypeWithPrevious = true;
10741       NewFD->setIsMultiVersion();
10742 
10743       if (CurClones && NewClones &&
10744           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10745            !std::equal(CurClones->featuresStrs_begin(),
10746                        CurClones->featuresStrs_end(),
10747                        NewClones->featuresStrs_begin()))) {
10748         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10749         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10750         NewFD->setInvalidDecl();
10751         return true;
10752       }
10753 
10754       return false;
10755     }
10756     case MultiVersionKind::CPUSpecific:
10757     case MultiVersionKind::CPUDispatch: {
10758       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10759       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10760       // Handle CPUDispatch/CPUSpecific versions.
10761       // Only 1 CPUDispatch function is allowed, this will make it go through
10762       // the redeclaration errors.
10763       if (NewMVType == MultiVersionKind::CPUDispatch &&
10764           CurFD->hasAttr<CPUDispatchAttr>()) {
10765         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10766             std::equal(
10767                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10768                 NewCPUDisp->cpus_begin(),
10769                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10770                   return Cur->getName() == New->getName();
10771                 })) {
10772           NewFD->setIsMultiVersion();
10773           Redeclaration = true;
10774           OldDecl = ND;
10775           return false;
10776         }
10777 
10778         // If the declarations don't match, this is an error condition.
10779         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10780         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10781         NewFD->setInvalidDecl();
10782         return true;
10783       }
10784       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10785 
10786         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10787             std::equal(
10788                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10789                 NewCPUSpec->cpus_begin(),
10790                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10791                   return Cur->getName() == New->getName();
10792                 })) {
10793           NewFD->setIsMultiVersion();
10794           Redeclaration = true;
10795           OldDecl = ND;
10796           return false;
10797         }
10798 
10799         // Only 1 version of CPUSpecific is allowed for each CPU.
10800         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10801           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10802             if (CurII == NewII) {
10803               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10804                   << NewII;
10805               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10806               NewFD->setInvalidDecl();
10807               return true;
10808             }
10809           }
10810         }
10811       }
10812       break;
10813     }
10814     }
10815   }
10816 
10817   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10818   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10819   // handled in the attribute adding step.
10820   if (NewMVType == MultiVersionKind::Target &&
10821       CheckMultiVersionValue(S, NewFD)) {
10822     NewFD->setInvalidDecl();
10823     return true;
10824   }
10825 
10826   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10827                                        !OldFD->isMultiVersion(), NewMVType)) {
10828     NewFD->setInvalidDecl();
10829     return true;
10830   }
10831 
10832   // Permit forward declarations in the case where these two are compatible.
10833   if (!OldFD->isMultiVersion()) {
10834     OldFD->setIsMultiVersion();
10835     NewFD->setIsMultiVersion();
10836     Redeclaration = true;
10837     OldDecl = OldFD;
10838     return false;
10839   }
10840 
10841   NewFD->setIsMultiVersion();
10842   Redeclaration = false;
10843   MergeTypeWithPrevious = false;
10844   OldDecl = nullptr;
10845   Previous.clear();
10846   return false;
10847 }
10848 
10849 /// Check the validity of a mulitversion function declaration.
10850 /// Also sets the multiversion'ness' of the function itself.
10851 ///
10852 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10853 ///
10854 /// Returns true if there was an error, false otherwise.
10855 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10856                                       bool &Redeclaration, NamedDecl *&OldDecl,
10857                                       bool &MergeTypeWithPrevious,
10858                                       LookupResult &Previous) {
10859   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10860   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10861   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10862   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10863   MultiVersionKind MVType = NewFD->getMultiVersionKind();
10864 
10865   // Main isn't allowed to become a multiversion function, however it IS
10866   // permitted to have 'main' be marked with the 'target' optimization hint.
10867   if (NewFD->isMain()) {
10868     if (MVType != MultiVersionKind::None &&
10869         !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10870       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10871       NewFD->setInvalidDecl();
10872       return true;
10873     }
10874     return false;
10875   }
10876 
10877   if (!OldDecl || !OldDecl->getAsFunction() ||
10878       OldDecl->getDeclContext()->getRedeclContext() !=
10879           NewFD->getDeclContext()->getRedeclContext()) {
10880     // If there's no previous declaration, AND this isn't attempting to cause
10881     // multiversioning, this isn't an error condition.
10882     if (MVType == MultiVersionKind::None)
10883       return false;
10884     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10885   }
10886 
10887   FunctionDecl *OldFD = OldDecl->getAsFunction();
10888 
10889   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10890     return false;
10891 
10892   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10893   // for target_clones.
10894   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None &&
10895       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10896     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10897         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10898     NewFD->setInvalidDecl();
10899     return true;
10900   }
10901 
10902   if (!OldFD->isMultiVersion()) {
10903     switch (MVType) {
10904     case MultiVersionKind::Target:
10905       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10906                                               Redeclaration, OldDecl,
10907                                               MergeTypeWithPrevious, Previous);
10908     case MultiVersionKind::TargetClones:
10909       if (OldFD->isUsed(false)) {
10910         NewFD->setInvalidDecl();
10911         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10912       }
10913       OldFD->setIsMultiVersion();
10914       break;
10915     case MultiVersionKind::CPUDispatch:
10916     case MultiVersionKind::CPUSpecific:
10917     case MultiVersionKind::None:
10918       break;
10919     }
10920   }
10921   // Handle the target potentially causes multiversioning case.
10922   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10923     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10924                                             Redeclaration, OldDecl,
10925                                             MergeTypeWithPrevious, Previous);
10926 
10927   // At this point, we have a multiversion function decl (in OldFD) AND an
10928   // appropriate attribute in the current function decl.  Resolve that these are
10929   // still compatible with previous declarations.
10930   return CheckMultiVersionAdditionalDecl(
10931       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones,
10932       Redeclaration, OldDecl, MergeTypeWithPrevious, Previous);
10933 }
10934 
10935 /// Perform semantic checking of a new function declaration.
10936 ///
10937 /// Performs semantic analysis of the new function declaration
10938 /// NewFD. This routine performs all semantic checking that does not
10939 /// require the actual declarator involved in the declaration, and is
10940 /// used both for the declaration of functions as they are parsed
10941 /// (called via ActOnDeclarator) and for the declaration of functions
10942 /// that have been instantiated via C++ template instantiation (called
10943 /// via InstantiateDecl).
10944 ///
10945 /// \param IsMemberSpecialization whether this new function declaration is
10946 /// a member specialization (that replaces any definition provided by the
10947 /// previous declaration).
10948 ///
10949 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10950 ///
10951 /// \returns true if the function declaration is a redeclaration.
10952 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10953                                     LookupResult &Previous,
10954                                     bool IsMemberSpecialization) {
10955   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10956          "Variably modified return types are not handled here");
10957 
10958   // Determine whether the type of this function should be merged with
10959   // a previous visible declaration. This never happens for functions in C++,
10960   // and always happens in C if the previous declaration was visible.
10961   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10962                                !Previous.isShadowed();
10963 
10964   bool Redeclaration = false;
10965   NamedDecl *OldDecl = nullptr;
10966   bool MayNeedOverloadableChecks = false;
10967 
10968   // Merge or overload the declaration with an existing declaration of
10969   // the same name, if appropriate.
10970   if (!Previous.empty()) {
10971     // Determine whether NewFD is an overload of PrevDecl or
10972     // a declaration that requires merging. If it's an overload,
10973     // there's no more work to do here; we'll just add the new
10974     // function to the scope.
10975     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10976       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10977       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10978         Redeclaration = true;
10979         OldDecl = Candidate;
10980       }
10981     } else {
10982       MayNeedOverloadableChecks = true;
10983       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10984                             /*NewIsUsingDecl*/ false)) {
10985       case Ovl_Match:
10986         Redeclaration = true;
10987         break;
10988 
10989       case Ovl_NonFunction:
10990         Redeclaration = true;
10991         break;
10992 
10993       case Ovl_Overload:
10994         Redeclaration = false;
10995         break;
10996       }
10997     }
10998   }
10999 
11000   // Check for a previous extern "C" declaration with this name.
11001   if (!Redeclaration &&
11002       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11003     if (!Previous.empty()) {
11004       // This is an extern "C" declaration with the same name as a previous
11005       // declaration, and thus redeclares that entity...
11006       Redeclaration = true;
11007       OldDecl = Previous.getFoundDecl();
11008       MergeTypeWithPrevious = false;
11009 
11010       // ... except in the presence of __attribute__((overloadable)).
11011       if (OldDecl->hasAttr<OverloadableAttr>() ||
11012           NewFD->hasAttr<OverloadableAttr>()) {
11013         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11014           MayNeedOverloadableChecks = true;
11015           Redeclaration = false;
11016           OldDecl = nullptr;
11017         }
11018       }
11019     }
11020   }
11021 
11022   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
11023                                 MergeTypeWithPrevious, Previous))
11024     return Redeclaration;
11025 
11026   // PPC MMA non-pointer types are not allowed as function return types.
11027   if (Context.getTargetInfo().getTriple().isPPC64() &&
11028       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11029     NewFD->setInvalidDecl();
11030   }
11031 
11032   // C++11 [dcl.constexpr]p8:
11033   //   A constexpr specifier for a non-static member function that is not
11034   //   a constructor declares that member function to be const.
11035   //
11036   // This needs to be delayed until we know whether this is an out-of-line
11037   // definition of a static member function.
11038   //
11039   // This rule is not present in C++1y, so we produce a backwards
11040   // compatibility warning whenever it happens in C++11.
11041   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11042   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11043       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11044       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11045     CXXMethodDecl *OldMD = nullptr;
11046     if (OldDecl)
11047       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11048     if (!OldMD || !OldMD->isStatic()) {
11049       const FunctionProtoType *FPT =
11050         MD->getType()->castAs<FunctionProtoType>();
11051       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11052       EPI.TypeQuals.addConst();
11053       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11054                                           FPT->getParamTypes(), EPI));
11055 
11056       // Warn that we did this, if we're not performing template instantiation.
11057       // In that case, we'll have warned already when the template was defined.
11058       if (!inTemplateInstantiation()) {
11059         SourceLocation AddConstLoc;
11060         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11061                 .IgnoreParens().getAs<FunctionTypeLoc>())
11062           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11063 
11064         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11065           << FixItHint::CreateInsertion(AddConstLoc, " const");
11066       }
11067     }
11068   }
11069 
11070   if (Redeclaration) {
11071     // NewFD and OldDecl represent declarations that need to be
11072     // merged.
11073     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11074       NewFD->setInvalidDecl();
11075       return Redeclaration;
11076     }
11077 
11078     Previous.clear();
11079     Previous.addDecl(OldDecl);
11080 
11081     if (FunctionTemplateDecl *OldTemplateDecl =
11082             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11083       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11084       FunctionTemplateDecl *NewTemplateDecl
11085         = NewFD->getDescribedFunctionTemplate();
11086       assert(NewTemplateDecl && "Template/non-template mismatch");
11087 
11088       // The call to MergeFunctionDecl above may have created some state in
11089       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11090       // can add it as a redeclaration.
11091       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11092 
11093       NewFD->setPreviousDeclaration(OldFD);
11094       if (NewFD->isCXXClassMember()) {
11095         NewFD->setAccess(OldTemplateDecl->getAccess());
11096         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11097       }
11098 
11099       // If this is an explicit specialization of a member that is a function
11100       // template, mark it as a member specialization.
11101       if (IsMemberSpecialization &&
11102           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11103         NewTemplateDecl->setMemberSpecialization();
11104         assert(OldTemplateDecl->isMemberSpecialization());
11105         // Explicit specializations of a member template do not inherit deleted
11106         // status from the parent member template that they are specializing.
11107         if (OldFD->isDeleted()) {
11108           // FIXME: This assert will not hold in the presence of modules.
11109           assert(OldFD->getCanonicalDecl() == OldFD);
11110           // FIXME: We need an update record for this AST mutation.
11111           OldFD->setDeletedAsWritten(false);
11112         }
11113       }
11114 
11115     } else {
11116       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11117         auto *OldFD = cast<FunctionDecl>(OldDecl);
11118         // This needs to happen first so that 'inline' propagates.
11119         NewFD->setPreviousDeclaration(OldFD);
11120         if (NewFD->isCXXClassMember())
11121           NewFD->setAccess(OldFD->getAccess());
11122       }
11123     }
11124   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11125              !NewFD->getAttr<OverloadableAttr>()) {
11126     assert((Previous.empty() ||
11127             llvm::any_of(Previous,
11128                          [](const NamedDecl *ND) {
11129                            return ND->hasAttr<OverloadableAttr>();
11130                          })) &&
11131            "Non-redecls shouldn't happen without overloadable present");
11132 
11133     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11134       const auto *FD = dyn_cast<FunctionDecl>(ND);
11135       return FD && !FD->hasAttr<OverloadableAttr>();
11136     });
11137 
11138     if (OtherUnmarkedIter != Previous.end()) {
11139       Diag(NewFD->getLocation(),
11140            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11141       Diag((*OtherUnmarkedIter)->getLocation(),
11142            diag::note_attribute_overloadable_prev_overload)
11143           << false;
11144 
11145       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11146     }
11147   }
11148 
11149   if (LangOpts.OpenMP)
11150     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11151 
11152   // Semantic checking for this function declaration (in isolation).
11153 
11154   if (getLangOpts().CPlusPlus) {
11155     // C++-specific checks.
11156     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11157       CheckConstructor(Constructor);
11158     } else if (CXXDestructorDecl *Destructor =
11159                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11160       CXXRecordDecl *Record = Destructor->getParent();
11161       QualType ClassType = Context.getTypeDeclType(Record);
11162 
11163       // FIXME: Shouldn't we be able to perform this check even when the class
11164       // type is dependent? Both gcc and edg can handle that.
11165       if (!ClassType->isDependentType()) {
11166         DeclarationName Name
11167           = Context.DeclarationNames.getCXXDestructorName(
11168                                         Context.getCanonicalType(ClassType));
11169         if (NewFD->getDeclName() != Name) {
11170           Diag(NewFD->getLocation(), diag::err_destructor_name);
11171           NewFD->setInvalidDecl();
11172           return Redeclaration;
11173         }
11174       }
11175     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11176       if (auto *TD = Guide->getDescribedFunctionTemplate())
11177         CheckDeductionGuideTemplate(TD);
11178 
11179       // A deduction guide is not on the list of entities that can be
11180       // explicitly specialized.
11181       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11182         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11183             << /*explicit specialization*/ 1;
11184     }
11185 
11186     // Find any virtual functions that this function overrides.
11187     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11188       if (!Method->isFunctionTemplateSpecialization() &&
11189           !Method->getDescribedFunctionTemplate() &&
11190           Method->isCanonicalDecl()) {
11191         AddOverriddenMethods(Method->getParent(), Method);
11192       }
11193       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11194         // C++2a [class.virtual]p6
11195         // A virtual method shall not have a requires-clause.
11196         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11197              diag::err_constrained_virtual_method);
11198 
11199       if (Method->isStatic())
11200         checkThisInStaticMemberFunctionType(Method);
11201     }
11202 
11203     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11204       ActOnConversionDeclarator(Conversion);
11205 
11206     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11207     if (NewFD->isOverloadedOperator() &&
11208         CheckOverloadedOperatorDeclaration(NewFD)) {
11209       NewFD->setInvalidDecl();
11210       return Redeclaration;
11211     }
11212 
11213     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11214     if (NewFD->getLiteralIdentifier() &&
11215         CheckLiteralOperatorDeclaration(NewFD)) {
11216       NewFD->setInvalidDecl();
11217       return Redeclaration;
11218     }
11219 
11220     // In C++, check default arguments now that we have merged decls. Unless
11221     // the lexical context is the class, because in this case this is done
11222     // during delayed parsing anyway.
11223     if (!CurContext->isRecord())
11224       CheckCXXDefaultArguments(NewFD);
11225 
11226     // If this function is declared as being extern "C", then check to see if
11227     // the function returns a UDT (class, struct, or union type) that is not C
11228     // compatible, and if it does, warn the user.
11229     // But, issue any diagnostic on the first declaration only.
11230     if (Previous.empty() && NewFD->isExternC()) {
11231       QualType R = NewFD->getReturnType();
11232       if (R->isIncompleteType() && !R->isVoidType())
11233         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11234             << NewFD << R;
11235       else if (!R.isPODType(Context) && !R->isVoidType() &&
11236                !R->isObjCObjectPointerType())
11237         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11238     }
11239 
11240     // C++1z [dcl.fct]p6:
11241     //   [...] whether the function has a non-throwing exception-specification
11242     //   [is] part of the function type
11243     //
11244     // This results in an ABI break between C++14 and C++17 for functions whose
11245     // declared type includes an exception-specification in a parameter or
11246     // return type. (Exception specifications on the function itself are OK in
11247     // most cases, and exception specifications are not permitted in most other
11248     // contexts where they could make it into a mangling.)
11249     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11250       auto HasNoexcept = [&](QualType T) -> bool {
11251         // Strip off declarator chunks that could be between us and a function
11252         // type. We don't need to look far, exception specifications are very
11253         // restricted prior to C++17.
11254         if (auto *RT = T->getAs<ReferenceType>())
11255           T = RT->getPointeeType();
11256         else if (T->isAnyPointerType())
11257           T = T->getPointeeType();
11258         else if (auto *MPT = T->getAs<MemberPointerType>())
11259           T = MPT->getPointeeType();
11260         if (auto *FPT = T->getAs<FunctionProtoType>())
11261           if (FPT->isNothrow())
11262             return true;
11263         return false;
11264       };
11265 
11266       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11267       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11268       for (QualType T : FPT->param_types())
11269         AnyNoexcept |= HasNoexcept(T);
11270       if (AnyNoexcept)
11271         Diag(NewFD->getLocation(),
11272              diag::warn_cxx17_compat_exception_spec_in_signature)
11273             << NewFD;
11274     }
11275 
11276     if (!Redeclaration && LangOpts.CUDA)
11277       checkCUDATargetOverload(NewFD, Previous);
11278   }
11279   return Redeclaration;
11280 }
11281 
11282 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11283   // C++11 [basic.start.main]p3:
11284   //   A program that [...] declares main to be inline, static or
11285   //   constexpr is ill-formed.
11286   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11287   //   appear in a declaration of main.
11288   // static main is not an error under C99, but we should warn about it.
11289   // We accept _Noreturn main as an extension.
11290   if (FD->getStorageClass() == SC_Static)
11291     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11292          ? diag::err_static_main : diag::warn_static_main)
11293       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11294   if (FD->isInlineSpecified())
11295     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11296       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11297   if (DS.isNoreturnSpecified()) {
11298     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11299     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11300     Diag(NoreturnLoc, diag::ext_noreturn_main);
11301     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11302       << FixItHint::CreateRemoval(NoreturnRange);
11303   }
11304   if (FD->isConstexpr()) {
11305     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11306         << FD->isConsteval()
11307         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11308     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11309   }
11310 
11311   if (getLangOpts().OpenCL) {
11312     Diag(FD->getLocation(), diag::err_opencl_no_main)
11313         << FD->hasAttr<OpenCLKernelAttr>();
11314     FD->setInvalidDecl();
11315     return;
11316   }
11317 
11318   QualType T = FD->getType();
11319   assert(T->isFunctionType() && "function decl is not of function type");
11320   const FunctionType* FT = T->castAs<FunctionType>();
11321 
11322   // Set default calling convention for main()
11323   if (FT->getCallConv() != CC_C) {
11324     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11325     FD->setType(QualType(FT, 0));
11326     T = Context.getCanonicalType(FD->getType());
11327   }
11328 
11329   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11330     // In C with GNU extensions we allow main() to have non-integer return
11331     // type, but we should warn about the extension, and we disable the
11332     // implicit-return-zero rule.
11333 
11334     // GCC in C mode accepts qualified 'int'.
11335     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11336       FD->setHasImplicitReturnZero(true);
11337     else {
11338       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11339       SourceRange RTRange = FD->getReturnTypeSourceRange();
11340       if (RTRange.isValid())
11341         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11342             << FixItHint::CreateReplacement(RTRange, "int");
11343     }
11344   } else {
11345     // In C and C++, main magically returns 0 if you fall off the end;
11346     // set the flag which tells us that.
11347     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11348 
11349     // All the standards say that main() should return 'int'.
11350     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11351       FD->setHasImplicitReturnZero(true);
11352     else {
11353       // Otherwise, this is just a flat-out error.
11354       SourceRange RTRange = FD->getReturnTypeSourceRange();
11355       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11356           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11357                                 : FixItHint());
11358       FD->setInvalidDecl(true);
11359     }
11360   }
11361 
11362   // Treat protoless main() as nullary.
11363   if (isa<FunctionNoProtoType>(FT)) return;
11364 
11365   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11366   unsigned nparams = FTP->getNumParams();
11367   assert(FD->getNumParams() == nparams);
11368 
11369   bool HasExtraParameters = (nparams > 3);
11370 
11371   if (FTP->isVariadic()) {
11372     Diag(FD->getLocation(), diag::ext_variadic_main);
11373     // FIXME: if we had information about the location of the ellipsis, we
11374     // could add a FixIt hint to remove it as a parameter.
11375   }
11376 
11377   // Darwin passes an undocumented fourth argument of type char**.  If
11378   // other platforms start sprouting these, the logic below will start
11379   // getting shifty.
11380   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11381     HasExtraParameters = false;
11382 
11383   if (HasExtraParameters) {
11384     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11385     FD->setInvalidDecl(true);
11386     nparams = 3;
11387   }
11388 
11389   // FIXME: a lot of the following diagnostics would be improved
11390   // if we had some location information about types.
11391 
11392   QualType CharPP =
11393     Context.getPointerType(Context.getPointerType(Context.CharTy));
11394   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11395 
11396   for (unsigned i = 0; i < nparams; ++i) {
11397     QualType AT = FTP->getParamType(i);
11398 
11399     bool mismatch = true;
11400 
11401     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11402       mismatch = false;
11403     else if (Expected[i] == CharPP) {
11404       // As an extension, the following forms are okay:
11405       //   char const **
11406       //   char const * const *
11407       //   char * const *
11408 
11409       QualifierCollector qs;
11410       const PointerType* PT;
11411       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11412           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11413           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11414                               Context.CharTy)) {
11415         qs.removeConst();
11416         mismatch = !qs.empty();
11417       }
11418     }
11419 
11420     if (mismatch) {
11421       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11422       // TODO: suggest replacing given type with expected type
11423       FD->setInvalidDecl(true);
11424     }
11425   }
11426 
11427   if (nparams == 1 && !FD->isInvalidDecl()) {
11428     Diag(FD->getLocation(), diag::warn_main_one_arg);
11429   }
11430 
11431   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11432     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11433     FD->setInvalidDecl();
11434   }
11435 }
11436 
11437 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11438 
11439   // Default calling convention for main and wmain is __cdecl
11440   if (FD->getName() == "main" || FD->getName() == "wmain")
11441     return false;
11442 
11443   // Default calling convention for MinGW is __cdecl
11444   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11445   if (T.isWindowsGNUEnvironment())
11446     return false;
11447 
11448   // Default calling convention for WinMain, wWinMain and DllMain
11449   // is __stdcall on 32 bit Windows
11450   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11451     return true;
11452 
11453   return false;
11454 }
11455 
11456 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11457   QualType T = FD->getType();
11458   assert(T->isFunctionType() && "function decl is not of function type");
11459   const FunctionType *FT = T->castAs<FunctionType>();
11460 
11461   // Set an implicit return of 'zero' if the function can return some integral,
11462   // enumeration, pointer or nullptr type.
11463   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11464       FT->getReturnType()->isAnyPointerType() ||
11465       FT->getReturnType()->isNullPtrType())
11466     // DllMain is exempt because a return value of zero means it failed.
11467     if (FD->getName() != "DllMain")
11468       FD->setHasImplicitReturnZero(true);
11469 
11470   // Explicity specified calling conventions are applied to MSVC entry points
11471   if (!hasExplicitCallingConv(T)) {
11472     if (isDefaultStdCall(FD, *this)) {
11473       if (FT->getCallConv() != CC_X86StdCall) {
11474         FT = Context.adjustFunctionType(
11475             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11476         FD->setType(QualType(FT, 0));
11477       }
11478     } else if (FT->getCallConv() != CC_C) {
11479       FT = Context.adjustFunctionType(FT,
11480                                       FT->getExtInfo().withCallingConv(CC_C));
11481       FD->setType(QualType(FT, 0));
11482     }
11483   }
11484 
11485   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11486     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11487     FD->setInvalidDecl();
11488   }
11489 }
11490 
11491 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11492   // FIXME: Need strict checking.  In C89, we need to check for
11493   // any assignment, increment, decrement, function-calls, or
11494   // commas outside of a sizeof.  In C99, it's the same list,
11495   // except that the aforementioned are allowed in unevaluated
11496   // expressions.  Everything else falls under the
11497   // "may accept other forms of constant expressions" exception.
11498   //
11499   // Regular C++ code will not end up here (exceptions: language extensions,
11500   // OpenCL C++ etc), so the constant expression rules there don't matter.
11501   if (Init->isValueDependent()) {
11502     assert(Init->containsErrors() &&
11503            "Dependent code should only occur in error-recovery path.");
11504     return true;
11505   }
11506   const Expr *Culprit;
11507   if (Init->isConstantInitializer(Context, false, &Culprit))
11508     return false;
11509   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11510     << Culprit->getSourceRange();
11511   return true;
11512 }
11513 
11514 namespace {
11515   // Visits an initialization expression to see if OrigDecl is evaluated in
11516   // its own initialization and throws a warning if it does.
11517   class SelfReferenceChecker
11518       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11519     Sema &S;
11520     Decl *OrigDecl;
11521     bool isRecordType;
11522     bool isPODType;
11523     bool isReferenceType;
11524 
11525     bool isInitList;
11526     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11527 
11528   public:
11529     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11530 
11531     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11532                                                     S(S), OrigDecl(OrigDecl) {
11533       isPODType = false;
11534       isRecordType = false;
11535       isReferenceType = false;
11536       isInitList = false;
11537       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11538         isPODType = VD->getType().isPODType(S.Context);
11539         isRecordType = VD->getType()->isRecordType();
11540         isReferenceType = VD->getType()->isReferenceType();
11541       }
11542     }
11543 
11544     // For most expressions, just call the visitor.  For initializer lists,
11545     // track the index of the field being initialized since fields are
11546     // initialized in order allowing use of previously initialized fields.
11547     void CheckExpr(Expr *E) {
11548       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11549       if (!InitList) {
11550         Visit(E);
11551         return;
11552       }
11553 
11554       // Track and increment the index here.
11555       isInitList = true;
11556       InitFieldIndex.push_back(0);
11557       for (auto Child : InitList->children()) {
11558         CheckExpr(cast<Expr>(Child));
11559         ++InitFieldIndex.back();
11560       }
11561       InitFieldIndex.pop_back();
11562     }
11563 
11564     // Returns true if MemberExpr is checked and no further checking is needed.
11565     // Returns false if additional checking is required.
11566     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11567       llvm::SmallVector<FieldDecl*, 4> Fields;
11568       Expr *Base = E;
11569       bool ReferenceField = false;
11570 
11571       // Get the field members used.
11572       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11573         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11574         if (!FD)
11575           return false;
11576         Fields.push_back(FD);
11577         if (FD->getType()->isReferenceType())
11578           ReferenceField = true;
11579         Base = ME->getBase()->IgnoreParenImpCasts();
11580       }
11581 
11582       // Keep checking only if the base Decl is the same.
11583       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11584       if (!DRE || DRE->getDecl() != OrigDecl)
11585         return false;
11586 
11587       // A reference field can be bound to an unininitialized field.
11588       if (CheckReference && !ReferenceField)
11589         return true;
11590 
11591       // Convert FieldDecls to their index number.
11592       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11593       for (const FieldDecl *I : llvm::reverse(Fields))
11594         UsedFieldIndex.push_back(I->getFieldIndex());
11595 
11596       // See if a warning is needed by checking the first difference in index
11597       // numbers.  If field being used has index less than the field being
11598       // initialized, then the use is safe.
11599       for (auto UsedIter = UsedFieldIndex.begin(),
11600                 UsedEnd = UsedFieldIndex.end(),
11601                 OrigIter = InitFieldIndex.begin(),
11602                 OrigEnd = InitFieldIndex.end();
11603            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11604         if (*UsedIter < *OrigIter)
11605           return true;
11606         if (*UsedIter > *OrigIter)
11607           break;
11608       }
11609 
11610       // TODO: Add a different warning which will print the field names.
11611       HandleDeclRefExpr(DRE);
11612       return true;
11613     }
11614 
11615     // For most expressions, the cast is directly above the DeclRefExpr.
11616     // For conditional operators, the cast can be outside the conditional
11617     // operator if both expressions are DeclRefExpr's.
11618     void HandleValue(Expr *E) {
11619       E = E->IgnoreParens();
11620       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11621         HandleDeclRefExpr(DRE);
11622         return;
11623       }
11624 
11625       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11626         Visit(CO->getCond());
11627         HandleValue(CO->getTrueExpr());
11628         HandleValue(CO->getFalseExpr());
11629         return;
11630       }
11631 
11632       if (BinaryConditionalOperator *BCO =
11633               dyn_cast<BinaryConditionalOperator>(E)) {
11634         Visit(BCO->getCond());
11635         HandleValue(BCO->getFalseExpr());
11636         return;
11637       }
11638 
11639       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11640         HandleValue(OVE->getSourceExpr());
11641         return;
11642       }
11643 
11644       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11645         if (BO->getOpcode() == BO_Comma) {
11646           Visit(BO->getLHS());
11647           HandleValue(BO->getRHS());
11648           return;
11649         }
11650       }
11651 
11652       if (isa<MemberExpr>(E)) {
11653         if (isInitList) {
11654           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11655                                       false /*CheckReference*/))
11656             return;
11657         }
11658 
11659         Expr *Base = E->IgnoreParenImpCasts();
11660         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11661           // Check for static member variables and don't warn on them.
11662           if (!isa<FieldDecl>(ME->getMemberDecl()))
11663             return;
11664           Base = ME->getBase()->IgnoreParenImpCasts();
11665         }
11666         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11667           HandleDeclRefExpr(DRE);
11668         return;
11669       }
11670 
11671       Visit(E);
11672     }
11673 
11674     // Reference types not handled in HandleValue are handled here since all
11675     // uses of references are bad, not just r-value uses.
11676     void VisitDeclRefExpr(DeclRefExpr *E) {
11677       if (isReferenceType)
11678         HandleDeclRefExpr(E);
11679     }
11680 
11681     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11682       if (E->getCastKind() == CK_LValueToRValue) {
11683         HandleValue(E->getSubExpr());
11684         return;
11685       }
11686 
11687       Inherited::VisitImplicitCastExpr(E);
11688     }
11689 
11690     void VisitMemberExpr(MemberExpr *E) {
11691       if (isInitList) {
11692         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11693           return;
11694       }
11695 
11696       // Don't warn on arrays since they can be treated as pointers.
11697       if (E->getType()->canDecayToPointerType()) return;
11698 
11699       // Warn when a non-static method call is followed by non-static member
11700       // field accesses, which is followed by a DeclRefExpr.
11701       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11702       bool Warn = (MD && !MD->isStatic());
11703       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11704       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11705         if (!isa<FieldDecl>(ME->getMemberDecl()))
11706           Warn = false;
11707         Base = ME->getBase()->IgnoreParenImpCasts();
11708       }
11709 
11710       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11711         if (Warn)
11712           HandleDeclRefExpr(DRE);
11713         return;
11714       }
11715 
11716       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11717       // Visit that expression.
11718       Visit(Base);
11719     }
11720 
11721     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11722       Expr *Callee = E->getCallee();
11723 
11724       if (isa<UnresolvedLookupExpr>(Callee))
11725         return Inherited::VisitCXXOperatorCallExpr(E);
11726 
11727       Visit(Callee);
11728       for (auto Arg: E->arguments())
11729         HandleValue(Arg->IgnoreParenImpCasts());
11730     }
11731 
11732     void VisitUnaryOperator(UnaryOperator *E) {
11733       // For POD record types, addresses of its own members are well-defined.
11734       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11735           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11736         if (!isPODType)
11737           HandleValue(E->getSubExpr());
11738         return;
11739       }
11740 
11741       if (E->isIncrementDecrementOp()) {
11742         HandleValue(E->getSubExpr());
11743         return;
11744       }
11745 
11746       Inherited::VisitUnaryOperator(E);
11747     }
11748 
11749     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11750 
11751     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11752       if (E->getConstructor()->isCopyConstructor()) {
11753         Expr *ArgExpr = E->getArg(0);
11754         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11755           if (ILE->getNumInits() == 1)
11756             ArgExpr = ILE->getInit(0);
11757         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11758           if (ICE->getCastKind() == CK_NoOp)
11759             ArgExpr = ICE->getSubExpr();
11760         HandleValue(ArgExpr);
11761         return;
11762       }
11763       Inherited::VisitCXXConstructExpr(E);
11764     }
11765 
11766     void VisitCallExpr(CallExpr *E) {
11767       // Treat std::move as a use.
11768       if (E->isCallToStdMove()) {
11769         HandleValue(E->getArg(0));
11770         return;
11771       }
11772 
11773       Inherited::VisitCallExpr(E);
11774     }
11775 
11776     void VisitBinaryOperator(BinaryOperator *E) {
11777       if (E->isCompoundAssignmentOp()) {
11778         HandleValue(E->getLHS());
11779         Visit(E->getRHS());
11780         return;
11781       }
11782 
11783       Inherited::VisitBinaryOperator(E);
11784     }
11785 
11786     // A custom visitor for BinaryConditionalOperator is needed because the
11787     // regular visitor would check the condition and true expression separately
11788     // but both point to the same place giving duplicate diagnostics.
11789     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11790       Visit(E->getCond());
11791       Visit(E->getFalseExpr());
11792     }
11793 
11794     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11795       Decl* ReferenceDecl = DRE->getDecl();
11796       if (OrigDecl != ReferenceDecl) return;
11797       unsigned diag;
11798       if (isReferenceType) {
11799         diag = diag::warn_uninit_self_reference_in_reference_init;
11800       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11801         diag = diag::warn_static_self_reference_in_init;
11802       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11803                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11804                  DRE->getDecl()->getType()->isRecordType()) {
11805         diag = diag::warn_uninit_self_reference_in_init;
11806       } else {
11807         // Local variables will be handled by the CFG analysis.
11808         return;
11809       }
11810 
11811       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11812                             S.PDiag(diag)
11813                                 << DRE->getDecl() << OrigDecl->getLocation()
11814                                 << DRE->getSourceRange());
11815     }
11816   };
11817 
11818   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11819   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11820                                  bool DirectInit) {
11821     // Parameters arguments are occassionially constructed with itself,
11822     // for instance, in recursive functions.  Skip them.
11823     if (isa<ParmVarDecl>(OrigDecl))
11824       return;
11825 
11826     E = E->IgnoreParens();
11827 
11828     // Skip checking T a = a where T is not a record or reference type.
11829     // Doing so is a way to silence uninitialized warnings.
11830     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11831       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11832         if (ICE->getCastKind() == CK_LValueToRValue)
11833           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11834             if (DRE->getDecl() == OrigDecl)
11835               return;
11836 
11837     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11838   }
11839 } // end anonymous namespace
11840 
11841 namespace {
11842   // Simple wrapper to add the name of a variable or (if no variable is
11843   // available) a DeclarationName into a diagnostic.
11844   struct VarDeclOrName {
11845     VarDecl *VDecl;
11846     DeclarationName Name;
11847 
11848     friend const Sema::SemaDiagnosticBuilder &
11849     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11850       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11851     }
11852   };
11853 } // end anonymous namespace
11854 
11855 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11856                                             DeclarationName Name, QualType Type,
11857                                             TypeSourceInfo *TSI,
11858                                             SourceRange Range, bool DirectInit,
11859                                             Expr *Init) {
11860   bool IsInitCapture = !VDecl;
11861   assert((!VDecl || !VDecl->isInitCapture()) &&
11862          "init captures are expected to be deduced prior to initialization");
11863 
11864   VarDeclOrName VN{VDecl, Name};
11865 
11866   DeducedType *Deduced = Type->getContainedDeducedType();
11867   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11868 
11869   // C++11 [dcl.spec.auto]p3
11870   if (!Init) {
11871     assert(VDecl && "no init for init capture deduction?");
11872 
11873     // Except for class argument deduction, and then for an initializing
11874     // declaration only, i.e. no static at class scope or extern.
11875     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11876         VDecl->hasExternalStorage() ||
11877         VDecl->isStaticDataMember()) {
11878       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11879         << VDecl->getDeclName() << Type;
11880       return QualType();
11881     }
11882   }
11883 
11884   ArrayRef<Expr*> DeduceInits;
11885   if (Init)
11886     DeduceInits = Init;
11887 
11888   if (DirectInit) {
11889     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11890       DeduceInits = PL->exprs();
11891   }
11892 
11893   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11894     assert(VDecl && "non-auto type for init capture deduction?");
11895     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11896     InitializationKind Kind = InitializationKind::CreateForInit(
11897         VDecl->getLocation(), DirectInit, Init);
11898     // FIXME: Initialization should not be taking a mutable list of inits.
11899     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11900     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11901                                                        InitsCopy);
11902   }
11903 
11904   if (DirectInit) {
11905     if (auto *IL = dyn_cast<InitListExpr>(Init))
11906       DeduceInits = IL->inits();
11907   }
11908 
11909   // Deduction only works if we have exactly one source expression.
11910   if (DeduceInits.empty()) {
11911     // It isn't possible to write this directly, but it is possible to
11912     // end up in this situation with "auto x(some_pack...);"
11913     Diag(Init->getBeginLoc(), IsInitCapture
11914                                   ? diag::err_init_capture_no_expression
11915                                   : diag::err_auto_var_init_no_expression)
11916         << VN << Type << Range;
11917     return QualType();
11918   }
11919 
11920   if (DeduceInits.size() > 1) {
11921     Diag(DeduceInits[1]->getBeginLoc(),
11922          IsInitCapture ? diag::err_init_capture_multiple_expressions
11923                        : diag::err_auto_var_init_multiple_expressions)
11924         << VN << Type << Range;
11925     return QualType();
11926   }
11927 
11928   Expr *DeduceInit = DeduceInits[0];
11929   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11930     Diag(Init->getBeginLoc(), IsInitCapture
11931                                   ? diag::err_init_capture_paren_braces
11932                                   : diag::err_auto_var_init_paren_braces)
11933         << isa<InitListExpr>(Init) << VN << Type << Range;
11934     return QualType();
11935   }
11936 
11937   // Expressions default to 'id' when we're in a debugger.
11938   bool DefaultedAnyToId = false;
11939   if (getLangOpts().DebuggerCastResultToId &&
11940       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11941     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11942     if (Result.isInvalid()) {
11943       return QualType();
11944     }
11945     Init = Result.get();
11946     DefaultedAnyToId = true;
11947   }
11948 
11949   // C++ [dcl.decomp]p1:
11950   //   If the assignment-expression [...] has array type A and no ref-qualifier
11951   //   is present, e has type cv A
11952   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11953       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11954       DeduceInit->getType()->isConstantArrayType())
11955     return Context.getQualifiedType(DeduceInit->getType(),
11956                                     Type.getQualifiers());
11957 
11958   QualType DeducedType;
11959   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11960     if (!IsInitCapture)
11961       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11962     else if (isa<InitListExpr>(Init))
11963       Diag(Range.getBegin(),
11964            diag::err_init_capture_deduction_failure_from_init_list)
11965           << VN
11966           << (DeduceInit->getType().isNull() ? TSI->getType()
11967                                              : DeduceInit->getType())
11968           << DeduceInit->getSourceRange();
11969     else
11970       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11971           << VN << TSI->getType()
11972           << (DeduceInit->getType().isNull() ? TSI->getType()
11973                                              : DeduceInit->getType())
11974           << DeduceInit->getSourceRange();
11975   }
11976 
11977   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11978   // 'id' instead of a specific object type prevents most of our usual
11979   // checks.
11980   // We only want to warn outside of template instantiations, though:
11981   // inside a template, the 'id' could have come from a parameter.
11982   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11983       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11984     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11985     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11986   }
11987 
11988   return DeducedType;
11989 }
11990 
11991 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11992                                          Expr *Init) {
11993   assert(!Init || !Init->containsErrors());
11994   QualType DeducedType = deduceVarTypeFromInitializer(
11995       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11996       VDecl->getSourceRange(), DirectInit, Init);
11997   if (DeducedType.isNull()) {
11998     VDecl->setInvalidDecl();
11999     return true;
12000   }
12001 
12002   VDecl->setType(DeducedType);
12003   assert(VDecl->isLinkageValid());
12004 
12005   // In ARC, infer lifetime.
12006   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12007     VDecl->setInvalidDecl();
12008 
12009   if (getLangOpts().OpenCL)
12010     deduceOpenCLAddressSpace(VDecl);
12011 
12012   // If this is a redeclaration, check that the type we just deduced matches
12013   // the previously declared type.
12014   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12015     // We never need to merge the type, because we cannot form an incomplete
12016     // array of auto, nor deduce such a type.
12017     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12018   }
12019 
12020   // Check the deduced type is valid for a variable declaration.
12021   CheckVariableDeclarationType(VDecl);
12022   return VDecl->isInvalidDecl();
12023 }
12024 
12025 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12026                                               SourceLocation Loc) {
12027   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12028     Init = EWC->getSubExpr();
12029 
12030   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12031     Init = CE->getSubExpr();
12032 
12033   QualType InitType = Init->getType();
12034   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12035           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12036          "shouldn't be called if type doesn't have a non-trivial C struct");
12037   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12038     for (auto I : ILE->inits()) {
12039       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12040           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12041         continue;
12042       SourceLocation SL = I->getExprLoc();
12043       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12044     }
12045     return;
12046   }
12047 
12048   if (isa<ImplicitValueInitExpr>(Init)) {
12049     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12050       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12051                             NTCUK_Init);
12052   } else {
12053     // Assume all other explicit initializers involving copying some existing
12054     // object.
12055     // TODO: ignore any explicit initializers where we can guarantee
12056     // copy-elision.
12057     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12058       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12059   }
12060 }
12061 
12062 namespace {
12063 
12064 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12065   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12066   // in the source code or implicitly by the compiler if it is in a union
12067   // defined in a system header and has non-trivial ObjC ownership
12068   // qualifications. We don't want those fields to participate in determining
12069   // whether the containing union is non-trivial.
12070   return FD->hasAttr<UnavailableAttr>();
12071 }
12072 
12073 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12074     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12075                                     void> {
12076   using Super =
12077       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12078                                     void>;
12079 
12080   DiagNonTrivalCUnionDefaultInitializeVisitor(
12081       QualType OrigTy, SourceLocation OrigLoc,
12082       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12083       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12084 
12085   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12086                      const FieldDecl *FD, bool InNonTrivialUnion) {
12087     if (const auto *AT = S.Context.getAsArrayType(QT))
12088       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12089                                      InNonTrivialUnion);
12090     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12091   }
12092 
12093   void visitARCStrong(QualType QT, const FieldDecl *FD,
12094                       bool InNonTrivialUnion) {
12095     if (InNonTrivialUnion)
12096       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12097           << 1 << 0 << QT << FD->getName();
12098   }
12099 
12100   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12101     if (InNonTrivialUnion)
12102       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12103           << 1 << 0 << QT << FD->getName();
12104   }
12105 
12106   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12107     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12108     if (RD->isUnion()) {
12109       if (OrigLoc.isValid()) {
12110         bool IsUnion = false;
12111         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12112           IsUnion = OrigRD->isUnion();
12113         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12114             << 0 << OrigTy << IsUnion << UseContext;
12115         // Reset OrigLoc so that this diagnostic is emitted only once.
12116         OrigLoc = SourceLocation();
12117       }
12118       InNonTrivialUnion = true;
12119     }
12120 
12121     if (InNonTrivialUnion)
12122       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12123           << 0 << 0 << QT.getUnqualifiedType() << "";
12124 
12125     for (const FieldDecl *FD : RD->fields())
12126       if (!shouldIgnoreForRecordTriviality(FD))
12127         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12128   }
12129 
12130   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12131 
12132   // The non-trivial C union type or the struct/union type that contains a
12133   // non-trivial C union.
12134   QualType OrigTy;
12135   SourceLocation OrigLoc;
12136   Sema::NonTrivialCUnionContext UseContext;
12137   Sema &S;
12138 };
12139 
12140 struct DiagNonTrivalCUnionDestructedTypeVisitor
12141     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12142   using Super =
12143       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12144 
12145   DiagNonTrivalCUnionDestructedTypeVisitor(
12146       QualType OrigTy, SourceLocation OrigLoc,
12147       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12148       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12149 
12150   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12151                      const FieldDecl *FD, bool InNonTrivialUnion) {
12152     if (const auto *AT = S.Context.getAsArrayType(QT))
12153       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12154                                      InNonTrivialUnion);
12155     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12156   }
12157 
12158   void visitARCStrong(QualType QT, const FieldDecl *FD,
12159                       bool InNonTrivialUnion) {
12160     if (InNonTrivialUnion)
12161       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12162           << 1 << 1 << QT << FD->getName();
12163   }
12164 
12165   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12166     if (InNonTrivialUnion)
12167       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12168           << 1 << 1 << QT << FD->getName();
12169   }
12170 
12171   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12172     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12173     if (RD->isUnion()) {
12174       if (OrigLoc.isValid()) {
12175         bool IsUnion = false;
12176         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12177           IsUnion = OrigRD->isUnion();
12178         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12179             << 1 << OrigTy << IsUnion << UseContext;
12180         // Reset OrigLoc so that this diagnostic is emitted only once.
12181         OrigLoc = SourceLocation();
12182       }
12183       InNonTrivialUnion = true;
12184     }
12185 
12186     if (InNonTrivialUnion)
12187       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12188           << 0 << 1 << QT.getUnqualifiedType() << "";
12189 
12190     for (const FieldDecl *FD : RD->fields())
12191       if (!shouldIgnoreForRecordTriviality(FD))
12192         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12193   }
12194 
12195   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12196   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12197                           bool InNonTrivialUnion) {}
12198 
12199   // The non-trivial C union type or the struct/union type that contains a
12200   // non-trivial C union.
12201   QualType OrigTy;
12202   SourceLocation OrigLoc;
12203   Sema::NonTrivialCUnionContext UseContext;
12204   Sema &S;
12205 };
12206 
12207 struct DiagNonTrivalCUnionCopyVisitor
12208     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12209   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12210 
12211   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12212                                  Sema::NonTrivialCUnionContext UseContext,
12213                                  Sema &S)
12214       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12215 
12216   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12217                      const FieldDecl *FD, bool InNonTrivialUnion) {
12218     if (const auto *AT = S.Context.getAsArrayType(QT))
12219       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12220                                      InNonTrivialUnion);
12221     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12222   }
12223 
12224   void visitARCStrong(QualType QT, const FieldDecl *FD,
12225                       bool InNonTrivialUnion) {
12226     if (InNonTrivialUnion)
12227       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12228           << 1 << 2 << QT << FD->getName();
12229   }
12230 
12231   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12232     if (InNonTrivialUnion)
12233       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12234           << 1 << 2 << QT << FD->getName();
12235   }
12236 
12237   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12238     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12239     if (RD->isUnion()) {
12240       if (OrigLoc.isValid()) {
12241         bool IsUnion = false;
12242         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12243           IsUnion = OrigRD->isUnion();
12244         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12245             << 2 << OrigTy << IsUnion << UseContext;
12246         // Reset OrigLoc so that this diagnostic is emitted only once.
12247         OrigLoc = SourceLocation();
12248       }
12249       InNonTrivialUnion = true;
12250     }
12251 
12252     if (InNonTrivialUnion)
12253       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12254           << 0 << 2 << QT.getUnqualifiedType() << "";
12255 
12256     for (const FieldDecl *FD : RD->fields())
12257       if (!shouldIgnoreForRecordTriviality(FD))
12258         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12259   }
12260 
12261   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12262                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12263   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12264   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12265                             bool InNonTrivialUnion) {}
12266 
12267   // The non-trivial C union type or the struct/union type that contains a
12268   // non-trivial C union.
12269   QualType OrigTy;
12270   SourceLocation OrigLoc;
12271   Sema::NonTrivialCUnionContext UseContext;
12272   Sema &S;
12273 };
12274 
12275 } // namespace
12276 
12277 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12278                                  NonTrivialCUnionContext UseContext,
12279                                  unsigned NonTrivialKind) {
12280   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12281           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12282           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12283          "shouldn't be called if type doesn't have a non-trivial C union");
12284 
12285   if ((NonTrivialKind & NTCUK_Init) &&
12286       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12287     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12288         .visit(QT, nullptr, false);
12289   if ((NonTrivialKind & NTCUK_Destruct) &&
12290       QT.hasNonTrivialToPrimitiveDestructCUnion())
12291     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12292         .visit(QT, nullptr, false);
12293   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12294     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12295         .visit(QT, nullptr, false);
12296 }
12297 
12298 /// AddInitializerToDecl - Adds the initializer Init to the
12299 /// declaration dcl. If DirectInit is true, this is C++ direct
12300 /// initialization rather than copy initialization.
12301 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12302   // If there is no declaration, there was an error parsing it.  Just ignore
12303   // the initializer.
12304   if (!RealDecl || RealDecl->isInvalidDecl()) {
12305     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12306     return;
12307   }
12308 
12309   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12310     // Pure-specifiers are handled in ActOnPureSpecifier.
12311     Diag(Method->getLocation(), diag::err_member_function_initialization)
12312       << Method->getDeclName() << Init->getSourceRange();
12313     Method->setInvalidDecl();
12314     return;
12315   }
12316 
12317   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12318   if (!VDecl) {
12319     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12320     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12321     RealDecl->setInvalidDecl();
12322     return;
12323   }
12324 
12325   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12326   if (VDecl->getType()->isUndeducedType()) {
12327     // Attempt typo correction early so that the type of the init expression can
12328     // be deduced based on the chosen correction if the original init contains a
12329     // TypoExpr.
12330     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12331     if (!Res.isUsable()) {
12332       // There are unresolved typos in Init, just drop them.
12333       // FIXME: improve the recovery strategy to preserve the Init.
12334       RealDecl->setInvalidDecl();
12335       return;
12336     }
12337     if (Res.get()->containsErrors()) {
12338       // Invalidate the decl as we don't know the type for recovery-expr yet.
12339       RealDecl->setInvalidDecl();
12340       VDecl->setInit(Res.get());
12341       return;
12342     }
12343     Init = Res.get();
12344 
12345     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12346       return;
12347   }
12348 
12349   // dllimport cannot be used on variable definitions.
12350   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12351     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12352     VDecl->setInvalidDecl();
12353     return;
12354   }
12355 
12356   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12357     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12358     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12359     VDecl->setInvalidDecl();
12360     return;
12361   }
12362 
12363   if (!VDecl->getType()->isDependentType()) {
12364     // A definition must end up with a complete type, which means it must be
12365     // complete with the restriction that an array type might be completed by
12366     // the initializer; note that later code assumes this restriction.
12367     QualType BaseDeclType = VDecl->getType();
12368     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12369       BaseDeclType = Array->getElementType();
12370     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12371                             diag::err_typecheck_decl_incomplete_type)) {
12372       RealDecl->setInvalidDecl();
12373       return;
12374     }
12375 
12376     // The variable can not have an abstract class type.
12377     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12378                                diag::err_abstract_type_in_decl,
12379                                AbstractVariableType))
12380       VDecl->setInvalidDecl();
12381   }
12382 
12383   // If adding the initializer will turn this declaration into a definition,
12384   // and we already have a definition for this variable, diagnose or otherwise
12385   // handle the situation.
12386   if (VarDecl *Def = VDecl->getDefinition())
12387     if (Def != VDecl &&
12388         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12389         !VDecl->isThisDeclarationADemotedDefinition() &&
12390         checkVarDeclRedefinition(Def, VDecl))
12391       return;
12392 
12393   if (getLangOpts().CPlusPlus) {
12394     // C++ [class.static.data]p4
12395     //   If a static data member is of const integral or const
12396     //   enumeration type, its declaration in the class definition can
12397     //   specify a constant-initializer which shall be an integral
12398     //   constant expression (5.19). In that case, the member can appear
12399     //   in integral constant expressions. The member shall still be
12400     //   defined in a namespace scope if it is used in the program and the
12401     //   namespace scope definition shall not contain an initializer.
12402     //
12403     // We already performed a redefinition check above, but for static
12404     // data members we also need to check whether there was an in-class
12405     // declaration with an initializer.
12406     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12407       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12408           << VDecl->getDeclName();
12409       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12410            diag::note_previous_initializer)
12411           << 0;
12412       return;
12413     }
12414 
12415     if (VDecl->hasLocalStorage())
12416       setFunctionHasBranchProtectedScope();
12417 
12418     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12419       VDecl->setInvalidDecl();
12420       return;
12421     }
12422   }
12423 
12424   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12425   // a kernel function cannot be initialized."
12426   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12427     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12428     VDecl->setInvalidDecl();
12429     return;
12430   }
12431 
12432   // The LoaderUninitialized attribute acts as a definition (of undef).
12433   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12434     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12435     VDecl->setInvalidDecl();
12436     return;
12437   }
12438 
12439   // Get the decls type and save a reference for later, since
12440   // CheckInitializerTypes may change it.
12441   QualType DclT = VDecl->getType(), SavT = DclT;
12442 
12443   // Expressions default to 'id' when we're in a debugger
12444   // and we are assigning it to a variable of Objective-C pointer type.
12445   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12446       Init->getType() == Context.UnknownAnyTy) {
12447     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12448     if (Result.isInvalid()) {
12449       VDecl->setInvalidDecl();
12450       return;
12451     }
12452     Init = Result.get();
12453   }
12454 
12455   // Perform the initialization.
12456   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12457   if (!VDecl->isInvalidDecl()) {
12458     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12459     InitializationKind Kind = InitializationKind::CreateForInit(
12460         VDecl->getLocation(), DirectInit, Init);
12461 
12462     MultiExprArg Args = Init;
12463     if (CXXDirectInit)
12464       Args = MultiExprArg(CXXDirectInit->getExprs(),
12465                           CXXDirectInit->getNumExprs());
12466 
12467     // Try to correct any TypoExprs in the initialization arguments.
12468     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12469       ExprResult Res = CorrectDelayedTyposInExpr(
12470           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12471           [this, Entity, Kind](Expr *E) {
12472             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12473             return Init.Failed() ? ExprError() : E;
12474           });
12475       if (Res.isInvalid()) {
12476         VDecl->setInvalidDecl();
12477       } else if (Res.get() != Args[Idx]) {
12478         Args[Idx] = Res.get();
12479       }
12480     }
12481     if (VDecl->isInvalidDecl())
12482       return;
12483 
12484     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12485                                    /*TopLevelOfInitList=*/false,
12486                                    /*TreatUnavailableAsInvalid=*/false);
12487     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12488     if (Result.isInvalid()) {
12489       // If the provided initializer fails to initialize the var decl,
12490       // we attach a recovery expr for better recovery.
12491       auto RecoveryExpr =
12492           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12493       if (RecoveryExpr.get())
12494         VDecl->setInit(RecoveryExpr.get());
12495       return;
12496     }
12497 
12498     Init = Result.getAs<Expr>();
12499   }
12500 
12501   // Check for self-references within variable initializers.
12502   // Variables declared within a function/method body (except for references)
12503   // are handled by a dataflow analysis.
12504   // This is undefined behavior in C++, but valid in C.
12505   if (getLangOpts().CPlusPlus)
12506     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12507         VDecl->getType()->isReferenceType())
12508       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12509 
12510   // If the type changed, it means we had an incomplete type that was
12511   // completed by the initializer. For example:
12512   //   int ary[] = { 1, 3, 5 };
12513   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12514   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12515     VDecl->setType(DclT);
12516 
12517   if (!VDecl->isInvalidDecl()) {
12518     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12519 
12520     if (VDecl->hasAttr<BlocksAttr>())
12521       checkRetainCycles(VDecl, Init);
12522 
12523     // It is safe to assign a weak reference into a strong variable.
12524     // Although this code can still have problems:
12525     //   id x = self.weakProp;
12526     //   id y = self.weakProp;
12527     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12528     // paths through the function. This should be revisited if
12529     // -Wrepeated-use-of-weak is made flow-sensitive.
12530     if (FunctionScopeInfo *FSI = getCurFunction())
12531       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12532            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12533           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12534                            Init->getBeginLoc()))
12535         FSI->markSafeWeakUse(Init);
12536   }
12537 
12538   // The initialization is usually a full-expression.
12539   //
12540   // FIXME: If this is a braced initialization of an aggregate, it is not
12541   // an expression, and each individual field initializer is a separate
12542   // full-expression. For instance, in:
12543   //
12544   //   struct Temp { ~Temp(); };
12545   //   struct S { S(Temp); };
12546   //   struct T { S a, b; } t = { Temp(), Temp() }
12547   //
12548   // we should destroy the first Temp before constructing the second.
12549   ExprResult Result =
12550       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12551                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12552   if (Result.isInvalid()) {
12553     VDecl->setInvalidDecl();
12554     return;
12555   }
12556   Init = Result.get();
12557 
12558   // Attach the initializer to the decl.
12559   VDecl->setInit(Init);
12560 
12561   if (VDecl->isLocalVarDecl()) {
12562     // Don't check the initializer if the declaration is malformed.
12563     if (VDecl->isInvalidDecl()) {
12564       // do nothing
12565 
12566     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12567     // This is true even in C++ for OpenCL.
12568     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12569       CheckForConstantInitializer(Init, DclT);
12570 
12571     // Otherwise, C++ does not restrict the initializer.
12572     } else if (getLangOpts().CPlusPlus) {
12573       // do nothing
12574 
12575     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12576     // static storage duration shall be constant expressions or string literals.
12577     } else if (VDecl->getStorageClass() == SC_Static) {
12578       CheckForConstantInitializer(Init, DclT);
12579 
12580     // C89 is stricter than C99 for aggregate initializers.
12581     // C89 6.5.7p3: All the expressions [...] in an initializer list
12582     // for an object that has aggregate or union type shall be
12583     // constant expressions.
12584     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12585                isa<InitListExpr>(Init)) {
12586       const Expr *Culprit;
12587       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12588         Diag(Culprit->getExprLoc(),
12589              diag::ext_aggregate_init_not_constant)
12590           << Culprit->getSourceRange();
12591       }
12592     }
12593 
12594     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12595       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12596         if (VDecl->hasLocalStorage())
12597           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12598   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12599              VDecl->getLexicalDeclContext()->isRecord()) {
12600     // This is an in-class initialization for a static data member, e.g.,
12601     //
12602     // struct S {
12603     //   static const int value = 17;
12604     // };
12605 
12606     // C++ [class.mem]p4:
12607     //   A member-declarator can contain a constant-initializer only
12608     //   if it declares a static member (9.4) of const integral or
12609     //   const enumeration type, see 9.4.2.
12610     //
12611     // C++11 [class.static.data]p3:
12612     //   If a non-volatile non-inline const static data member is of integral
12613     //   or enumeration type, its declaration in the class definition can
12614     //   specify a brace-or-equal-initializer in which every initializer-clause
12615     //   that is an assignment-expression is a constant expression. A static
12616     //   data member of literal type can be declared in the class definition
12617     //   with the constexpr specifier; if so, its declaration shall specify a
12618     //   brace-or-equal-initializer in which every initializer-clause that is
12619     //   an assignment-expression is a constant expression.
12620 
12621     // Do nothing on dependent types.
12622     if (DclT->isDependentType()) {
12623 
12624     // Allow any 'static constexpr' members, whether or not they are of literal
12625     // type. We separately check that every constexpr variable is of literal
12626     // type.
12627     } else if (VDecl->isConstexpr()) {
12628 
12629     // Require constness.
12630     } else if (!DclT.isConstQualified()) {
12631       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12632         << Init->getSourceRange();
12633       VDecl->setInvalidDecl();
12634 
12635     // We allow integer constant expressions in all cases.
12636     } else if (DclT->isIntegralOrEnumerationType()) {
12637       // Check whether the expression is a constant expression.
12638       SourceLocation Loc;
12639       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12640         // In C++11, a non-constexpr const static data member with an
12641         // in-class initializer cannot be volatile.
12642         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12643       else if (Init->isValueDependent())
12644         ; // Nothing to check.
12645       else if (Init->isIntegerConstantExpr(Context, &Loc))
12646         ; // Ok, it's an ICE!
12647       else if (Init->getType()->isScopedEnumeralType() &&
12648                Init->isCXX11ConstantExpr(Context))
12649         ; // Ok, it is a scoped-enum constant expression.
12650       else if (Init->isEvaluatable(Context)) {
12651         // If we can constant fold the initializer through heroics, accept it,
12652         // but report this as a use of an extension for -pedantic.
12653         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12654           << Init->getSourceRange();
12655       } else {
12656         // Otherwise, this is some crazy unknown case.  Report the issue at the
12657         // location provided by the isIntegerConstantExpr failed check.
12658         Diag(Loc, diag::err_in_class_initializer_non_constant)
12659           << Init->getSourceRange();
12660         VDecl->setInvalidDecl();
12661       }
12662 
12663     // We allow foldable floating-point constants as an extension.
12664     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12665       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12666       // it anyway and provide a fixit to add the 'constexpr'.
12667       if (getLangOpts().CPlusPlus11) {
12668         Diag(VDecl->getLocation(),
12669              diag::ext_in_class_initializer_float_type_cxx11)
12670             << DclT << Init->getSourceRange();
12671         Diag(VDecl->getBeginLoc(),
12672              diag::note_in_class_initializer_float_type_cxx11)
12673             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12674       } else {
12675         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12676           << DclT << Init->getSourceRange();
12677 
12678         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12679           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12680             << Init->getSourceRange();
12681           VDecl->setInvalidDecl();
12682         }
12683       }
12684 
12685     // Suggest adding 'constexpr' in C++11 for literal types.
12686     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12687       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12688           << DclT << Init->getSourceRange()
12689           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12690       VDecl->setConstexpr(true);
12691 
12692     } else {
12693       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12694         << DclT << Init->getSourceRange();
12695       VDecl->setInvalidDecl();
12696     }
12697   } else if (VDecl->isFileVarDecl()) {
12698     // In C, extern is typically used to avoid tentative definitions when
12699     // declaring variables in headers, but adding an intializer makes it a
12700     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12701     // In C++, extern is often used to give implictly static const variables
12702     // external linkage, so don't warn in that case. If selectany is present,
12703     // this might be header code intended for C and C++ inclusion, so apply the
12704     // C++ rules.
12705     if (VDecl->getStorageClass() == SC_Extern &&
12706         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12707          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12708         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12709         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12710       Diag(VDecl->getLocation(), diag::warn_extern_init);
12711 
12712     // In Microsoft C++ mode, a const variable defined in namespace scope has
12713     // external linkage by default if the variable is declared with
12714     // __declspec(dllexport).
12715     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12716         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12717         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12718       VDecl->setStorageClass(SC_Extern);
12719 
12720     // C99 6.7.8p4. All file scoped initializers need to be constant.
12721     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12722       CheckForConstantInitializer(Init, DclT);
12723   }
12724 
12725   QualType InitType = Init->getType();
12726   if (!InitType.isNull() &&
12727       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12728        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12729     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12730 
12731   // We will represent direct-initialization similarly to copy-initialization:
12732   //    int x(1);  -as-> int x = 1;
12733   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12734   //
12735   // Clients that want to distinguish between the two forms, can check for
12736   // direct initializer using VarDecl::getInitStyle().
12737   // A major benefit is that clients that don't particularly care about which
12738   // exactly form was it (like the CodeGen) can handle both cases without
12739   // special case code.
12740 
12741   // C++ 8.5p11:
12742   // The form of initialization (using parentheses or '=') is generally
12743   // insignificant, but does matter when the entity being initialized has a
12744   // class type.
12745   if (CXXDirectInit) {
12746     assert(DirectInit && "Call-style initializer must be direct init.");
12747     VDecl->setInitStyle(VarDecl::CallInit);
12748   } else if (DirectInit) {
12749     // This must be list-initialization. No other way is direct-initialization.
12750     VDecl->setInitStyle(VarDecl::ListInit);
12751   }
12752 
12753   if (LangOpts.OpenMP &&
12754       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12755       VDecl->isFileVarDecl())
12756     DeclsToCheckForDeferredDiags.insert(VDecl);
12757   CheckCompleteVariableDeclaration(VDecl);
12758 }
12759 
12760 /// ActOnInitializerError - Given that there was an error parsing an
12761 /// initializer for the given declaration, try to at least re-establish
12762 /// invariants such as whether a variable's type is either dependent or
12763 /// complete.
12764 void Sema::ActOnInitializerError(Decl *D) {
12765   // Our main concern here is re-establishing invariants like "a
12766   // variable's type is either dependent or complete".
12767   if (!D || D->isInvalidDecl()) return;
12768 
12769   VarDecl *VD = dyn_cast<VarDecl>(D);
12770   if (!VD) return;
12771 
12772   // Bindings are not usable if we can't make sense of the initializer.
12773   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12774     for (auto *BD : DD->bindings())
12775       BD->setInvalidDecl();
12776 
12777   // Auto types are meaningless if we can't make sense of the initializer.
12778   if (VD->getType()->isUndeducedType()) {
12779     D->setInvalidDecl();
12780     return;
12781   }
12782 
12783   QualType Ty = VD->getType();
12784   if (Ty->isDependentType()) return;
12785 
12786   // Require a complete type.
12787   if (RequireCompleteType(VD->getLocation(),
12788                           Context.getBaseElementType(Ty),
12789                           diag::err_typecheck_decl_incomplete_type)) {
12790     VD->setInvalidDecl();
12791     return;
12792   }
12793 
12794   // Require a non-abstract type.
12795   if (RequireNonAbstractType(VD->getLocation(), Ty,
12796                              diag::err_abstract_type_in_decl,
12797                              AbstractVariableType)) {
12798     VD->setInvalidDecl();
12799     return;
12800   }
12801 
12802   // Don't bother complaining about constructors or destructors,
12803   // though.
12804 }
12805 
12806 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12807   // If there is no declaration, there was an error parsing it. Just ignore it.
12808   if (!RealDecl)
12809     return;
12810 
12811   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12812     QualType Type = Var->getType();
12813 
12814     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12815     if (isa<DecompositionDecl>(RealDecl)) {
12816       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12817       Var->setInvalidDecl();
12818       return;
12819     }
12820 
12821     if (Type->isUndeducedType() &&
12822         DeduceVariableDeclarationType(Var, false, nullptr))
12823       return;
12824 
12825     // C++11 [class.static.data]p3: A static data member can be declared with
12826     // the constexpr specifier; if so, its declaration shall specify
12827     // a brace-or-equal-initializer.
12828     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12829     // the definition of a variable [...] or the declaration of a static data
12830     // member.
12831     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12832         !Var->isThisDeclarationADemotedDefinition()) {
12833       if (Var->isStaticDataMember()) {
12834         // C++1z removes the relevant rule; the in-class declaration is always
12835         // a definition there.
12836         if (!getLangOpts().CPlusPlus17 &&
12837             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12838           Diag(Var->getLocation(),
12839                diag::err_constexpr_static_mem_var_requires_init)
12840               << Var;
12841           Var->setInvalidDecl();
12842           return;
12843         }
12844       } else {
12845         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12846         Var->setInvalidDecl();
12847         return;
12848       }
12849     }
12850 
12851     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12852     // be initialized.
12853     if (!Var->isInvalidDecl() &&
12854         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12855         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12856       bool HasConstExprDefaultConstructor = false;
12857       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12858         for (auto *Ctor : RD->ctors()) {
12859           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12860               Ctor->getMethodQualifiers().getAddressSpace() ==
12861                   LangAS::opencl_constant) {
12862             HasConstExprDefaultConstructor = true;
12863           }
12864         }
12865       }
12866       if (!HasConstExprDefaultConstructor) {
12867         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12868         Var->setInvalidDecl();
12869         return;
12870       }
12871     }
12872 
12873     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12874       if (Var->getStorageClass() == SC_Extern) {
12875         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12876             << Var;
12877         Var->setInvalidDecl();
12878         return;
12879       }
12880       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12881                               diag::err_typecheck_decl_incomplete_type)) {
12882         Var->setInvalidDecl();
12883         return;
12884       }
12885       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12886         if (!RD->hasTrivialDefaultConstructor()) {
12887           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12888           Var->setInvalidDecl();
12889           return;
12890         }
12891       }
12892       // The declaration is unitialized, no need for further checks.
12893       return;
12894     }
12895 
12896     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12897     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12898         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12899       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12900                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12901 
12902 
12903     switch (DefKind) {
12904     case VarDecl::Definition:
12905       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12906         break;
12907 
12908       // We have an out-of-line definition of a static data member
12909       // that has an in-class initializer, so we type-check this like
12910       // a declaration.
12911       //
12912       LLVM_FALLTHROUGH;
12913 
12914     case VarDecl::DeclarationOnly:
12915       // It's only a declaration.
12916 
12917       // Block scope. C99 6.7p7: If an identifier for an object is
12918       // declared with no linkage (C99 6.2.2p6), the type for the
12919       // object shall be complete.
12920       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12921           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12922           RequireCompleteType(Var->getLocation(), Type,
12923                               diag::err_typecheck_decl_incomplete_type))
12924         Var->setInvalidDecl();
12925 
12926       // Make sure that the type is not abstract.
12927       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12928           RequireNonAbstractType(Var->getLocation(), Type,
12929                                  diag::err_abstract_type_in_decl,
12930                                  AbstractVariableType))
12931         Var->setInvalidDecl();
12932       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12933           Var->getStorageClass() == SC_PrivateExtern) {
12934         Diag(Var->getLocation(), diag::warn_private_extern);
12935         Diag(Var->getLocation(), diag::note_private_extern);
12936       }
12937 
12938       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12939           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12940         ExternalDeclarations.push_back(Var);
12941 
12942       return;
12943 
12944     case VarDecl::TentativeDefinition:
12945       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12946       // object that has file scope without an initializer, and without a
12947       // storage-class specifier or with the storage-class specifier "static",
12948       // constitutes a tentative definition. Note: A tentative definition with
12949       // external linkage is valid (C99 6.2.2p5).
12950       if (!Var->isInvalidDecl()) {
12951         if (const IncompleteArrayType *ArrayT
12952                                     = Context.getAsIncompleteArrayType(Type)) {
12953           if (RequireCompleteSizedType(
12954                   Var->getLocation(), ArrayT->getElementType(),
12955                   diag::err_array_incomplete_or_sizeless_type))
12956             Var->setInvalidDecl();
12957         } else if (Var->getStorageClass() == SC_Static) {
12958           // C99 6.9.2p3: If the declaration of an identifier for an object is
12959           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12960           // declared type shall not be an incomplete type.
12961           // NOTE: code such as the following
12962           //     static struct s;
12963           //     struct s { int a; };
12964           // is accepted by gcc. Hence here we issue a warning instead of
12965           // an error and we do not invalidate the static declaration.
12966           // NOTE: to avoid multiple warnings, only check the first declaration.
12967           if (Var->isFirstDecl())
12968             RequireCompleteType(Var->getLocation(), Type,
12969                                 diag::ext_typecheck_decl_incomplete_type);
12970         }
12971       }
12972 
12973       // Record the tentative definition; we're done.
12974       if (!Var->isInvalidDecl())
12975         TentativeDefinitions.push_back(Var);
12976       return;
12977     }
12978 
12979     // Provide a specific diagnostic for uninitialized variable
12980     // definitions with incomplete array type.
12981     if (Type->isIncompleteArrayType()) {
12982       Diag(Var->getLocation(),
12983            diag::err_typecheck_incomplete_array_needs_initializer);
12984       Var->setInvalidDecl();
12985       return;
12986     }
12987 
12988     // Provide a specific diagnostic for uninitialized variable
12989     // definitions with reference type.
12990     if (Type->isReferenceType()) {
12991       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12992           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12993       Var->setInvalidDecl();
12994       return;
12995     }
12996 
12997     // Do not attempt to type-check the default initializer for a
12998     // variable with dependent type.
12999     if (Type->isDependentType())
13000       return;
13001 
13002     if (Var->isInvalidDecl())
13003       return;
13004 
13005     if (!Var->hasAttr<AliasAttr>()) {
13006       if (RequireCompleteType(Var->getLocation(),
13007                               Context.getBaseElementType(Type),
13008                               diag::err_typecheck_decl_incomplete_type)) {
13009         Var->setInvalidDecl();
13010         return;
13011       }
13012     } else {
13013       return;
13014     }
13015 
13016     // The variable can not have an abstract class type.
13017     if (RequireNonAbstractType(Var->getLocation(), Type,
13018                                diag::err_abstract_type_in_decl,
13019                                AbstractVariableType)) {
13020       Var->setInvalidDecl();
13021       return;
13022     }
13023 
13024     // Check for jumps past the implicit initializer.  C++0x
13025     // clarifies that this applies to a "variable with automatic
13026     // storage duration", not a "local variable".
13027     // C++11 [stmt.dcl]p3
13028     //   A program that jumps from a point where a variable with automatic
13029     //   storage duration is not in scope to a point where it is in scope is
13030     //   ill-formed unless the variable has scalar type, class type with a
13031     //   trivial default constructor and a trivial destructor, a cv-qualified
13032     //   version of one of these types, or an array of one of the preceding
13033     //   types and is declared without an initializer.
13034     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13035       if (const RecordType *Record
13036             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13037         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13038         // Mark the function (if we're in one) for further checking even if the
13039         // looser rules of C++11 do not require such checks, so that we can
13040         // diagnose incompatibilities with C++98.
13041         if (!CXXRecord->isPOD())
13042           setFunctionHasBranchProtectedScope();
13043       }
13044     }
13045     // In OpenCL, we can't initialize objects in the __local address space,
13046     // even implicitly, so don't synthesize an implicit initializer.
13047     if (getLangOpts().OpenCL &&
13048         Var->getType().getAddressSpace() == LangAS::opencl_local)
13049       return;
13050     // C++03 [dcl.init]p9:
13051     //   If no initializer is specified for an object, and the
13052     //   object is of (possibly cv-qualified) non-POD class type (or
13053     //   array thereof), the object shall be default-initialized; if
13054     //   the object is of const-qualified type, the underlying class
13055     //   type shall have a user-declared default
13056     //   constructor. Otherwise, if no initializer is specified for
13057     //   a non- static object, the object and its subobjects, if
13058     //   any, have an indeterminate initial value); if the object
13059     //   or any of its subobjects are of const-qualified type, the
13060     //   program is ill-formed.
13061     // C++0x [dcl.init]p11:
13062     //   If no initializer is specified for an object, the object is
13063     //   default-initialized; [...].
13064     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13065     InitializationKind Kind
13066       = InitializationKind::CreateDefault(Var->getLocation());
13067 
13068     InitializationSequence InitSeq(*this, Entity, Kind, None);
13069     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13070 
13071     if (Init.get()) {
13072       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13073       // This is important for template substitution.
13074       Var->setInitStyle(VarDecl::CallInit);
13075     } else if (Init.isInvalid()) {
13076       // If default-init fails, attach a recovery-expr initializer to track
13077       // that initialization was attempted and failed.
13078       auto RecoveryExpr =
13079           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13080       if (RecoveryExpr.get())
13081         Var->setInit(RecoveryExpr.get());
13082     }
13083 
13084     CheckCompleteVariableDeclaration(Var);
13085   }
13086 }
13087 
13088 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13089   // If there is no declaration, there was an error parsing it. Ignore it.
13090   if (!D)
13091     return;
13092 
13093   VarDecl *VD = dyn_cast<VarDecl>(D);
13094   if (!VD) {
13095     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13096     D->setInvalidDecl();
13097     return;
13098   }
13099 
13100   VD->setCXXForRangeDecl(true);
13101 
13102   // for-range-declaration cannot be given a storage class specifier.
13103   int Error = -1;
13104   switch (VD->getStorageClass()) {
13105   case SC_None:
13106     break;
13107   case SC_Extern:
13108     Error = 0;
13109     break;
13110   case SC_Static:
13111     Error = 1;
13112     break;
13113   case SC_PrivateExtern:
13114     Error = 2;
13115     break;
13116   case SC_Auto:
13117     Error = 3;
13118     break;
13119   case SC_Register:
13120     Error = 4;
13121     break;
13122   }
13123 
13124   // for-range-declaration cannot be given a storage class specifier con't.
13125   switch (VD->getTSCSpec()) {
13126   case TSCS_thread_local:
13127     Error = 6;
13128     break;
13129   case TSCS___thread:
13130   case TSCS__Thread_local:
13131   case TSCS_unspecified:
13132     break;
13133   }
13134 
13135   if (Error != -1) {
13136     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13137         << VD << Error;
13138     D->setInvalidDecl();
13139   }
13140 }
13141 
13142 StmtResult
13143 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13144                                  IdentifierInfo *Ident,
13145                                  ParsedAttributes &Attrs,
13146                                  SourceLocation AttrEnd) {
13147   // C++1y [stmt.iter]p1:
13148   //   A range-based for statement of the form
13149   //      for ( for-range-identifier : for-range-initializer ) statement
13150   //   is equivalent to
13151   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13152   DeclSpec DS(Attrs.getPool().getFactory());
13153 
13154   const char *PrevSpec;
13155   unsigned DiagID;
13156   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13157                      getPrintingPolicy());
13158 
13159   Declarator D(DS, DeclaratorContext::ForInit);
13160   D.SetIdentifier(Ident, IdentLoc);
13161   D.takeAttributes(Attrs, AttrEnd);
13162 
13163   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13164                 IdentLoc);
13165   Decl *Var = ActOnDeclarator(S, D);
13166   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13167   FinalizeDeclaration(Var);
13168   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13169                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13170 }
13171 
13172 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13173   if (var->isInvalidDecl()) return;
13174 
13175   MaybeAddCUDAConstantAttr(var);
13176 
13177   if (getLangOpts().OpenCL) {
13178     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13179     // initialiser
13180     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13181         !var->hasInit()) {
13182       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13183           << 1 /*Init*/;
13184       var->setInvalidDecl();
13185       return;
13186     }
13187   }
13188 
13189   // In Objective-C, don't allow jumps past the implicit initialization of a
13190   // local retaining variable.
13191   if (getLangOpts().ObjC &&
13192       var->hasLocalStorage()) {
13193     switch (var->getType().getObjCLifetime()) {
13194     case Qualifiers::OCL_None:
13195     case Qualifiers::OCL_ExplicitNone:
13196     case Qualifiers::OCL_Autoreleasing:
13197       break;
13198 
13199     case Qualifiers::OCL_Weak:
13200     case Qualifiers::OCL_Strong:
13201       setFunctionHasBranchProtectedScope();
13202       break;
13203     }
13204   }
13205 
13206   if (var->hasLocalStorage() &&
13207       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13208     setFunctionHasBranchProtectedScope();
13209 
13210   // Warn about externally-visible variables being defined without a
13211   // prior declaration.  We only want to do this for global
13212   // declarations, but we also specifically need to avoid doing it for
13213   // class members because the linkage of an anonymous class can
13214   // change if it's later given a typedef name.
13215   if (var->isThisDeclarationADefinition() &&
13216       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13217       var->isExternallyVisible() && var->hasLinkage() &&
13218       !var->isInline() && !var->getDescribedVarTemplate() &&
13219       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13220       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13221       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13222                                   var->getLocation())) {
13223     // Find a previous declaration that's not a definition.
13224     VarDecl *prev = var->getPreviousDecl();
13225     while (prev && prev->isThisDeclarationADefinition())
13226       prev = prev->getPreviousDecl();
13227 
13228     if (!prev) {
13229       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13230       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13231           << /* variable */ 0;
13232     }
13233   }
13234 
13235   // Cache the result of checking for constant initialization.
13236   Optional<bool> CacheHasConstInit;
13237   const Expr *CacheCulprit = nullptr;
13238   auto checkConstInit = [&]() mutable {
13239     if (!CacheHasConstInit)
13240       CacheHasConstInit = var->getInit()->isConstantInitializer(
13241             Context, var->getType()->isReferenceType(), &CacheCulprit);
13242     return *CacheHasConstInit;
13243   };
13244 
13245   if (var->getTLSKind() == VarDecl::TLS_Static) {
13246     if (var->getType().isDestructedType()) {
13247       // GNU C++98 edits for __thread, [basic.start.term]p3:
13248       //   The type of an object with thread storage duration shall not
13249       //   have a non-trivial destructor.
13250       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13251       if (getLangOpts().CPlusPlus11)
13252         Diag(var->getLocation(), diag::note_use_thread_local);
13253     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13254       if (!checkConstInit()) {
13255         // GNU C++98 edits for __thread, [basic.start.init]p4:
13256         //   An object of thread storage duration shall not require dynamic
13257         //   initialization.
13258         // FIXME: Need strict checking here.
13259         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13260           << CacheCulprit->getSourceRange();
13261         if (getLangOpts().CPlusPlus11)
13262           Diag(var->getLocation(), diag::note_use_thread_local);
13263       }
13264     }
13265   }
13266 
13267 
13268   if (!var->getType()->isStructureType() && var->hasInit() &&
13269       isa<InitListExpr>(var->getInit())) {
13270     const auto *ILE = cast<InitListExpr>(var->getInit());
13271     unsigned NumInits = ILE->getNumInits();
13272     if (NumInits > 2)
13273       for (unsigned I = 0; I < NumInits; ++I) {
13274         const auto *Init = ILE->getInit(I);
13275         if (!Init)
13276           break;
13277         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13278         if (!SL)
13279           break;
13280 
13281         unsigned NumConcat = SL->getNumConcatenated();
13282         // Diagnose missing comma in string array initialization.
13283         // Do not warn when all the elements in the initializer are concatenated
13284         // together. Do not warn for macros too.
13285         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13286           bool OnlyOneMissingComma = true;
13287           for (unsigned J = I + 1; J < NumInits; ++J) {
13288             const auto *Init = ILE->getInit(J);
13289             if (!Init)
13290               break;
13291             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13292             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13293               OnlyOneMissingComma = false;
13294               break;
13295             }
13296           }
13297 
13298           if (OnlyOneMissingComma) {
13299             SmallVector<FixItHint, 1> Hints;
13300             for (unsigned i = 0; i < NumConcat - 1; ++i)
13301               Hints.push_back(FixItHint::CreateInsertion(
13302                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13303 
13304             Diag(SL->getStrTokenLoc(1),
13305                  diag::warn_concatenated_literal_array_init)
13306                 << Hints;
13307             Diag(SL->getBeginLoc(),
13308                  diag::note_concatenated_string_literal_silence);
13309           }
13310           // In any case, stop now.
13311           break;
13312         }
13313       }
13314   }
13315 
13316 
13317   QualType type = var->getType();
13318 
13319   if (var->hasAttr<BlocksAttr>())
13320     getCurFunction()->addByrefBlockVar(var);
13321 
13322   Expr *Init = var->getInit();
13323   bool GlobalStorage = var->hasGlobalStorage();
13324   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13325   QualType baseType = Context.getBaseElementType(type);
13326   bool HasConstInit = true;
13327 
13328   // Check whether the initializer is sufficiently constant.
13329   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13330       !Init->isValueDependent() &&
13331       (GlobalStorage || var->isConstexpr() ||
13332        var->mightBeUsableInConstantExpressions(Context))) {
13333     // If this variable might have a constant initializer or might be usable in
13334     // constant expressions, check whether or not it actually is now.  We can't
13335     // do this lazily, because the result might depend on things that change
13336     // later, such as which constexpr functions happen to be defined.
13337     SmallVector<PartialDiagnosticAt, 8> Notes;
13338     if (!getLangOpts().CPlusPlus11) {
13339       // Prior to C++11, in contexts where a constant initializer is required,
13340       // the set of valid constant initializers is described by syntactic rules
13341       // in [expr.const]p2-6.
13342       // FIXME: Stricter checking for these rules would be useful for constinit /
13343       // -Wglobal-constructors.
13344       HasConstInit = checkConstInit();
13345 
13346       // Compute and cache the constant value, and remember that we have a
13347       // constant initializer.
13348       if (HasConstInit) {
13349         (void)var->checkForConstantInitialization(Notes);
13350         Notes.clear();
13351       } else if (CacheCulprit) {
13352         Notes.emplace_back(CacheCulprit->getExprLoc(),
13353                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13354         Notes.back().second << CacheCulprit->getSourceRange();
13355       }
13356     } else {
13357       // Evaluate the initializer to see if it's a constant initializer.
13358       HasConstInit = var->checkForConstantInitialization(Notes);
13359     }
13360 
13361     if (HasConstInit) {
13362       // FIXME: Consider replacing the initializer with a ConstantExpr.
13363     } else if (var->isConstexpr()) {
13364       SourceLocation DiagLoc = var->getLocation();
13365       // If the note doesn't add any useful information other than a source
13366       // location, fold it into the primary diagnostic.
13367       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13368                                    diag::note_invalid_subexpr_in_const_expr) {
13369         DiagLoc = Notes[0].first;
13370         Notes.clear();
13371       }
13372       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13373           << var << Init->getSourceRange();
13374       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13375         Diag(Notes[I].first, Notes[I].second);
13376     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13377       auto *Attr = var->getAttr<ConstInitAttr>();
13378       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13379           << Init->getSourceRange();
13380       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13381           << Attr->getRange() << Attr->isConstinit();
13382       for (auto &it : Notes)
13383         Diag(it.first, it.second);
13384     } else if (IsGlobal &&
13385                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13386                                            var->getLocation())) {
13387       // Warn about globals which don't have a constant initializer.  Don't
13388       // warn about globals with a non-trivial destructor because we already
13389       // warned about them.
13390       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13391       if (!(RD && !RD->hasTrivialDestructor())) {
13392         // checkConstInit() here permits trivial default initialization even in
13393         // C++11 onwards, where such an initializer is not a constant initializer
13394         // but nonetheless doesn't require a global constructor.
13395         if (!checkConstInit())
13396           Diag(var->getLocation(), diag::warn_global_constructor)
13397               << Init->getSourceRange();
13398       }
13399     }
13400   }
13401 
13402   // Apply section attributes and pragmas to global variables.
13403   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13404       !inTemplateInstantiation()) {
13405     PragmaStack<StringLiteral *> *Stack = nullptr;
13406     int SectionFlags = ASTContext::PSF_Read;
13407     if (var->getType().isConstQualified()) {
13408       if (HasConstInit)
13409         Stack = &ConstSegStack;
13410       else {
13411         Stack = &BSSSegStack;
13412         SectionFlags |= ASTContext::PSF_Write;
13413       }
13414     } else if (var->hasInit() && HasConstInit) {
13415       Stack = &DataSegStack;
13416       SectionFlags |= ASTContext::PSF_Write;
13417     } else {
13418       Stack = &BSSSegStack;
13419       SectionFlags |= ASTContext::PSF_Write;
13420     }
13421     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13422       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13423         SectionFlags |= ASTContext::PSF_Implicit;
13424       UnifySection(SA->getName(), SectionFlags, var);
13425     } else if (Stack->CurrentValue) {
13426       SectionFlags |= ASTContext::PSF_Implicit;
13427       auto SectionName = Stack->CurrentValue->getString();
13428       var->addAttr(SectionAttr::CreateImplicit(
13429           Context, SectionName, Stack->CurrentPragmaLocation,
13430           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13431       if (UnifySection(SectionName, SectionFlags, var))
13432         var->dropAttr<SectionAttr>();
13433     }
13434 
13435     // Apply the init_seg attribute if this has an initializer.  If the
13436     // initializer turns out to not be dynamic, we'll end up ignoring this
13437     // attribute.
13438     if (CurInitSeg && var->getInit())
13439       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13440                                                CurInitSegLoc,
13441                                                AttributeCommonInfo::AS_Pragma));
13442   }
13443 
13444   // All the following checks are C++ only.
13445   if (!getLangOpts().CPlusPlus) {
13446     // If this variable must be emitted, add it as an initializer for the
13447     // current module.
13448     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13449       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13450     return;
13451   }
13452 
13453   // Require the destructor.
13454   if (!type->isDependentType())
13455     if (const RecordType *recordType = baseType->getAs<RecordType>())
13456       FinalizeVarWithDestructor(var, recordType);
13457 
13458   // If this variable must be emitted, add it as an initializer for the current
13459   // module.
13460   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13461     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13462 
13463   // Build the bindings if this is a structured binding declaration.
13464   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13465     CheckCompleteDecompositionDeclaration(DD);
13466 }
13467 
13468 /// Check if VD needs to be dllexport/dllimport due to being in a
13469 /// dllexport/import function.
13470 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13471   assert(VD->isStaticLocal());
13472 
13473   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13474 
13475   // Find outermost function when VD is in lambda function.
13476   while (FD && !getDLLAttr(FD) &&
13477          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13478          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13479     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13480   }
13481 
13482   if (!FD)
13483     return;
13484 
13485   // Static locals inherit dll attributes from their function.
13486   if (Attr *A = getDLLAttr(FD)) {
13487     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13488     NewAttr->setInherited(true);
13489     VD->addAttr(NewAttr);
13490   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13491     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13492     NewAttr->setInherited(true);
13493     VD->addAttr(NewAttr);
13494 
13495     // Export this function to enforce exporting this static variable even
13496     // if it is not used in this compilation unit.
13497     if (!FD->hasAttr<DLLExportAttr>())
13498       FD->addAttr(NewAttr);
13499 
13500   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13501     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13502     NewAttr->setInherited(true);
13503     VD->addAttr(NewAttr);
13504   }
13505 }
13506 
13507 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13508 /// any semantic actions necessary after any initializer has been attached.
13509 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13510   // Note that we are no longer parsing the initializer for this declaration.
13511   ParsingInitForAutoVars.erase(ThisDecl);
13512 
13513   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13514   if (!VD)
13515     return;
13516 
13517   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13518   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13519       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13520     if (PragmaClangBSSSection.Valid)
13521       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13522           Context, PragmaClangBSSSection.SectionName,
13523           PragmaClangBSSSection.PragmaLocation,
13524           AttributeCommonInfo::AS_Pragma));
13525     if (PragmaClangDataSection.Valid)
13526       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13527           Context, PragmaClangDataSection.SectionName,
13528           PragmaClangDataSection.PragmaLocation,
13529           AttributeCommonInfo::AS_Pragma));
13530     if (PragmaClangRodataSection.Valid)
13531       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13532           Context, PragmaClangRodataSection.SectionName,
13533           PragmaClangRodataSection.PragmaLocation,
13534           AttributeCommonInfo::AS_Pragma));
13535     if (PragmaClangRelroSection.Valid)
13536       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13537           Context, PragmaClangRelroSection.SectionName,
13538           PragmaClangRelroSection.PragmaLocation,
13539           AttributeCommonInfo::AS_Pragma));
13540   }
13541 
13542   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13543     for (auto *BD : DD->bindings()) {
13544       FinalizeDeclaration(BD);
13545     }
13546   }
13547 
13548   checkAttributesAfterMerging(*this, *VD);
13549 
13550   // Perform TLS alignment check here after attributes attached to the variable
13551   // which may affect the alignment have been processed. Only perform the check
13552   // if the target has a maximum TLS alignment (zero means no constraints).
13553   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13554     // Protect the check so that it's not performed on dependent types and
13555     // dependent alignments (we can't determine the alignment in that case).
13556     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13557       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13558       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13559         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13560           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13561           << (unsigned)MaxAlignChars.getQuantity();
13562       }
13563     }
13564   }
13565 
13566   if (VD->isStaticLocal())
13567     CheckStaticLocalForDllExport(VD);
13568 
13569   // Perform check for initializers of device-side global variables.
13570   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13571   // 7.5). We must also apply the same checks to all __shared__
13572   // variables whether they are local or not. CUDA also allows
13573   // constant initializers for __constant__ and __device__ variables.
13574   if (getLangOpts().CUDA)
13575     checkAllowedCUDAInitializer(VD);
13576 
13577   // Grab the dllimport or dllexport attribute off of the VarDecl.
13578   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13579 
13580   // Imported static data members cannot be defined out-of-line.
13581   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13582     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13583         VD->isThisDeclarationADefinition()) {
13584       // We allow definitions of dllimport class template static data members
13585       // with a warning.
13586       CXXRecordDecl *Context =
13587         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13588       bool IsClassTemplateMember =
13589           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13590           Context->getDescribedClassTemplate();
13591 
13592       Diag(VD->getLocation(),
13593            IsClassTemplateMember
13594                ? diag::warn_attribute_dllimport_static_field_definition
13595                : diag::err_attribute_dllimport_static_field_definition);
13596       Diag(IA->getLocation(), diag::note_attribute);
13597       if (!IsClassTemplateMember)
13598         VD->setInvalidDecl();
13599     }
13600   }
13601 
13602   // dllimport/dllexport variables cannot be thread local, their TLS index
13603   // isn't exported with the variable.
13604   if (DLLAttr && VD->getTLSKind()) {
13605     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13606     if (F && getDLLAttr(F)) {
13607       assert(VD->isStaticLocal());
13608       // But if this is a static local in a dlimport/dllexport function, the
13609       // function will never be inlined, which means the var would never be
13610       // imported, so having it marked import/export is safe.
13611     } else {
13612       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13613                                                                     << DLLAttr;
13614       VD->setInvalidDecl();
13615     }
13616   }
13617 
13618   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13619     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13620       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13621           << Attr;
13622       VD->dropAttr<UsedAttr>();
13623     }
13624   }
13625   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13626     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13627       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13628           << Attr;
13629       VD->dropAttr<RetainAttr>();
13630     }
13631   }
13632 
13633   const DeclContext *DC = VD->getDeclContext();
13634   // If there's a #pragma GCC visibility in scope, and this isn't a class
13635   // member, set the visibility of this variable.
13636   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13637     AddPushedVisibilityAttribute(VD);
13638 
13639   // FIXME: Warn on unused var template partial specializations.
13640   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13641     MarkUnusedFileScopedDecl(VD);
13642 
13643   // Now we have parsed the initializer and can update the table of magic
13644   // tag values.
13645   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13646       !VD->getType()->isIntegralOrEnumerationType())
13647     return;
13648 
13649   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13650     const Expr *MagicValueExpr = VD->getInit();
13651     if (!MagicValueExpr) {
13652       continue;
13653     }
13654     Optional<llvm::APSInt> MagicValueInt;
13655     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13656       Diag(I->getRange().getBegin(),
13657            diag::err_type_tag_for_datatype_not_ice)
13658         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13659       continue;
13660     }
13661     if (MagicValueInt->getActiveBits() > 64) {
13662       Diag(I->getRange().getBegin(),
13663            diag::err_type_tag_for_datatype_too_large)
13664         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13665       continue;
13666     }
13667     uint64_t MagicValue = MagicValueInt->getZExtValue();
13668     RegisterTypeTagForDatatype(I->getArgumentKind(),
13669                                MagicValue,
13670                                I->getMatchingCType(),
13671                                I->getLayoutCompatible(),
13672                                I->getMustBeNull());
13673   }
13674 }
13675 
13676 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13677   auto *VD = dyn_cast<VarDecl>(DD);
13678   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13679 }
13680 
13681 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13682                                                    ArrayRef<Decl *> Group) {
13683   SmallVector<Decl*, 8> Decls;
13684 
13685   if (DS.isTypeSpecOwned())
13686     Decls.push_back(DS.getRepAsDecl());
13687 
13688   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13689   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13690   bool DiagnosedMultipleDecomps = false;
13691   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13692   bool DiagnosedNonDeducedAuto = false;
13693 
13694   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13695     if (Decl *D = Group[i]) {
13696       // For declarators, there are some additional syntactic-ish checks we need
13697       // to perform.
13698       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13699         if (!FirstDeclaratorInGroup)
13700           FirstDeclaratorInGroup = DD;
13701         if (!FirstDecompDeclaratorInGroup)
13702           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13703         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13704             !hasDeducedAuto(DD))
13705           FirstNonDeducedAutoInGroup = DD;
13706 
13707         if (FirstDeclaratorInGroup != DD) {
13708           // A decomposition declaration cannot be combined with any other
13709           // declaration in the same group.
13710           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13711             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13712                  diag::err_decomp_decl_not_alone)
13713                 << FirstDeclaratorInGroup->getSourceRange()
13714                 << DD->getSourceRange();
13715             DiagnosedMultipleDecomps = true;
13716           }
13717 
13718           // A declarator that uses 'auto' in any way other than to declare a
13719           // variable with a deduced type cannot be combined with any other
13720           // declarator in the same group.
13721           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13722             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13723                  diag::err_auto_non_deduced_not_alone)
13724                 << FirstNonDeducedAutoInGroup->getType()
13725                        ->hasAutoForTrailingReturnType()
13726                 << FirstDeclaratorInGroup->getSourceRange()
13727                 << DD->getSourceRange();
13728             DiagnosedNonDeducedAuto = true;
13729           }
13730         }
13731       }
13732 
13733       Decls.push_back(D);
13734     }
13735   }
13736 
13737   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13738     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13739       handleTagNumbering(Tag, S);
13740       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13741           getLangOpts().CPlusPlus)
13742         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13743     }
13744   }
13745 
13746   return BuildDeclaratorGroup(Decls);
13747 }
13748 
13749 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13750 /// group, performing any necessary semantic checking.
13751 Sema::DeclGroupPtrTy
13752 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13753   // C++14 [dcl.spec.auto]p7: (DR1347)
13754   //   If the type that replaces the placeholder type is not the same in each
13755   //   deduction, the program is ill-formed.
13756   if (Group.size() > 1) {
13757     QualType Deduced;
13758     VarDecl *DeducedDecl = nullptr;
13759     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13760       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13761       if (!D || D->isInvalidDecl())
13762         break;
13763       DeducedType *DT = D->getType()->getContainedDeducedType();
13764       if (!DT || DT->getDeducedType().isNull())
13765         continue;
13766       if (Deduced.isNull()) {
13767         Deduced = DT->getDeducedType();
13768         DeducedDecl = D;
13769       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13770         auto *AT = dyn_cast<AutoType>(DT);
13771         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13772                         diag::err_auto_different_deductions)
13773                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13774                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13775                    << D->getDeclName();
13776         if (DeducedDecl->hasInit())
13777           Dia << DeducedDecl->getInit()->getSourceRange();
13778         if (D->getInit())
13779           Dia << D->getInit()->getSourceRange();
13780         D->setInvalidDecl();
13781         break;
13782       }
13783     }
13784   }
13785 
13786   ActOnDocumentableDecls(Group);
13787 
13788   return DeclGroupPtrTy::make(
13789       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13790 }
13791 
13792 void Sema::ActOnDocumentableDecl(Decl *D) {
13793   ActOnDocumentableDecls(D);
13794 }
13795 
13796 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13797   // Don't parse the comment if Doxygen diagnostics are ignored.
13798   if (Group.empty() || !Group[0])
13799     return;
13800 
13801   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13802                       Group[0]->getLocation()) &&
13803       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13804                       Group[0]->getLocation()))
13805     return;
13806 
13807   if (Group.size() >= 2) {
13808     // This is a decl group.  Normally it will contain only declarations
13809     // produced from declarator list.  But in case we have any definitions or
13810     // additional declaration references:
13811     //   'typedef struct S {} S;'
13812     //   'typedef struct S *S;'
13813     //   'struct S *pS;'
13814     // FinalizeDeclaratorGroup adds these as separate declarations.
13815     Decl *MaybeTagDecl = Group[0];
13816     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13817       Group = Group.slice(1);
13818     }
13819   }
13820 
13821   // FIMXE: We assume every Decl in the group is in the same file.
13822   // This is false when preprocessor constructs the group from decls in
13823   // different files (e. g. macros or #include).
13824   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13825 }
13826 
13827 /// Common checks for a parameter-declaration that should apply to both function
13828 /// parameters and non-type template parameters.
13829 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13830   // Check that there are no default arguments inside the type of this
13831   // parameter.
13832   if (getLangOpts().CPlusPlus)
13833     CheckExtraCXXDefaultArguments(D);
13834 
13835   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13836   if (D.getCXXScopeSpec().isSet()) {
13837     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13838       << D.getCXXScopeSpec().getRange();
13839   }
13840 
13841   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13842   // simple identifier except [...irrelevant cases...].
13843   switch (D.getName().getKind()) {
13844   case UnqualifiedIdKind::IK_Identifier:
13845     break;
13846 
13847   case UnqualifiedIdKind::IK_OperatorFunctionId:
13848   case UnqualifiedIdKind::IK_ConversionFunctionId:
13849   case UnqualifiedIdKind::IK_LiteralOperatorId:
13850   case UnqualifiedIdKind::IK_ConstructorName:
13851   case UnqualifiedIdKind::IK_DestructorName:
13852   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13853   case UnqualifiedIdKind::IK_DeductionGuideName:
13854     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13855       << GetNameForDeclarator(D).getName();
13856     break;
13857 
13858   case UnqualifiedIdKind::IK_TemplateId:
13859   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13860     // GetNameForDeclarator would not produce a useful name in this case.
13861     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13862     break;
13863   }
13864 }
13865 
13866 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13867 /// to introduce parameters into function prototype scope.
13868 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13869   const DeclSpec &DS = D.getDeclSpec();
13870 
13871   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13872 
13873   // C++03 [dcl.stc]p2 also permits 'auto'.
13874   StorageClass SC = SC_None;
13875   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13876     SC = SC_Register;
13877     // In C++11, the 'register' storage class specifier is deprecated.
13878     // In C++17, it is not allowed, but we tolerate it as an extension.
13879     if (getLangOpts().CPlusPlus11) {
13880       Diag(DS.getStorageClassSpecLoc(),
13881            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13882                                      : diag::warn_deprecated_register)
13883         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13884     }
13885   } else if (getLangOpts().CPlusPlus &&
13886              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13887     SC = SC_Auto;
13888   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13889     Diag(DS.getStorageClassSpecLoc(),
13890          diag::err_invalid_storage_class_in_func_decl);
13891     D.getMutableDeclSpec().ClearStorageClassSpecs();
13892   }
13893 
13894   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13895     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13896       << DeclSpec::getSpecifierName(TSCS);
13897   if (DS.isInlineSpecified())
13898     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13899         << getLangOpts().CPlusPlus17;
13900   if (DS.hasConstexprSpecifier())
13901     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13902         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13903 
13904   DiagnoseFunctionSpecifiers(DS);
13905 
13906   CheckFunctionOrTemplateParamDeclarator(S, D);
13907 
13908   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13909   QualType parmDeclType = TInfo->getType();
13910 
13911   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13912   IdentifierInfo *II = D.getIdentifier();
13913   if (II) {
13914     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13915                    ForVisibleRedeclaration);
13916     LookupName(R, S);
13917     if (R.isSingleResult()) {
13918       NamedDecl *PrevDecl = R.getFoundDecl();
13919       if (PrevDecl->isTemplateParameter()) {
13920         // Maybe we will complain about the shadowed template parameter.
13921         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13922         // Just pretend that we didn't see the previous declaration.
13923         PrevDecl = nullptr;
13924       } else if (S->isDeclScope(PrevDecl)) {
13925         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13926         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13927 
13928         // Recover by removing the name
13929         II = nullptr;
13930         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13931         D.setInvalidType(true);
13932       }
13933     }
13934   }
13935 
13936   // Temporarily put parameter variables in the translation unit, not
13937   // the enclosing context.  This prevents them from accidentally
13938   // looking like class members in C++.
13939   ParmVarDecl *New =
13940       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13941                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13942 
13943   if (D.isInvalidType())
13944     New->setInvalidDecl();
13945 
13946   assert(S->isFunctionPrototypeScope());
13947   assert(S->getFunctionPrototypeDepth() >= 1);
13948   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13949                     S->getNextFunctionPrototypeIndex());
13950 
13951   // Add the parameter declaration into this scope.
13952   S->AddDecl(New);
13953   if (II)
13954     IdResolver.AddDecl(New);
13955 
13956   ProcessDeclAttributes(S, New, D);
13957 
13958   if (D.getDeclSpec().isModulePrivateSpecified())
13959     Diag(New->getLocation(), diag::err_module_private_local)
13960         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13961         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13962 
13963   if (New->hasAttr<BlocksAttr>()) {
13964     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13965   }
13966 
13967   if (getLangOpts().OpenCL)
13968     deduceOpenCLAddressSpace(New);
13969 
13970   return New;
13971 }
13972 
13973 /// Synthesizes a variable for a parameter arising from a
13974 /// typedef.
13975 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13976                                               SourceLocation Loc,
13977                                               QualType T) {
13978   /* FIXME: setting StartLoc == Loc.
13979      Would it be worth to modify callers so as to provide proper source
13980      location for the unnamed parameters, embedding the parameter's type? */
13981   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13982                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13983                                            SC_None, nullptr);
13984   Param->setImplicit();
13985   return Param;
13986 }
13987 
13988 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13989   // Don't diagnose unused-parameter errors in template instantiations; we
13990   // will already have done so in the template itself.
13991   if (inTemplateInstantiation())
13992     return;
13993 
13994   for (const ParmVarDecl *Parameter : Parameters) {
13995     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13996         !Parameter->hasAttr<UnusedAttr>()) {
13997       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13998         << Parameter->getDeclName();
13999     }
14000   }
14001 }
14002 
14003 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14004     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14005   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14006     return;
14007 
14008   // Warn if the return value is pass-by-value and larger than the specified
14009   // threshold.
14010   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14011     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14012     if (Size > LangOpts.NumLargeByValueCopy)
14013       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14014   }
14015 
14016   // Warn if any parameter is pass-by-value and larger than the specified
14017   // threshold.
14018   for (const ParmVarDecl *Parameter : Parameters) {
14019     QualType T = Parameter->getType();
14020     if (T->isDependentType() || !T.isPODType(Context))
14021       continue;
14022     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14023     if (Size > LangOpts.NumLargeByValueCopy)
14024       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14025           << Parameter << Size;
14026   }
14027 }
14028 
14029 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14030                                   SourceLocation NameLoc, IdentifierInfo *Name,
14031                                   QualType T, TypeSourceInfo *TSInfo,
14032                                   StorageClass SC) {
14033   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14034   if (getLangOpts().ObjCAutoRefCount &&
14035       T.getObjCLifetime() == Qualifiers::OCL_None &&
14036       T->isObjCLifetimeType()) {
14037 
14038     Qualifiers::ObjCLifetime lifetime;
14039 
14040     // Special cases for arrays:
14041     //   - if it's const, use __unsafe_unretained
14042     //   - otherwise, it's an error
14043     if (T->isArrayType()) {
14044       if (!T.isConstQualified()) {
14045         if (DelayedDiagnostics.shouldDelayDiagnostics())
14046           DelayedDiagnostics.add(
14047               sema::DelayedDiagnostic::makeForbiddenType(
14048               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14049         else
14050           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14051               << TSInfo->getTypeLoc().getSourceRange();
14052       }
14053       lifetime = Qualifiers::OCL_ExplicitNone;
14054     } else {
14055       lifetime = T->getObjCARCImplicitLifetime();
14056     }
14057     T = Context.getLifetimeQualifiedType(T, lifetime);
14058   }
14059 
14060   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14061                                          Context.getAdjustedParameterType(T),
14062                                          TSInfo, SC, nullptr);
14063 
14064   // Make a note if we created a new pack in the scope of a lambda, so that
14065   // we know that references to that pack must also be expanded within the
14066   // lambda scope.
14067   if (New->isParameterPack())
14068     if (auto *LSI = getEnclosingLambda())
14069       LSI->LocalPacks.push_back(New);
14070 
14071   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14072       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14073     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14074                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14075 
14076   // Parameters can not be abstract class types.
14077   // For record types, this is done by the AbstractClassUsageDiagnoser once
14078   // the class has been completely parsed.
14079   if (!CurContext->isRecord() &&
14080       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14081                              AbstractParamType))
14082     New->setInvalidDecl();
14083 
14084   // Parameter declarators cannot be interface types. All ObjC objects are
14085   // passed by reference.
14086   if (T->isObjCObjectType()) {
14087     SourceLocation TypeEndLoc =
14088         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14089     Diag(NameLoc,
14090          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14091       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14092     T = Context.getObjCObjectPointerType(T);
14093     New->setType(T);
14094   }
14095 
14096   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14097   // duration shall not be qualified by an address-space qualifier."
14098   // Since all parameters have automatic store duration, they can not have
14099   // an address space.
14100   if (T.getAddressSpace() != LangAS::Default &&
14101       // OpenCL allows function arguments declared to be an array of a type
14102       // to be qualified with an address space.
14103       !(getLangOpts().OpenCL &&
14104         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14105     Diag(NameLoc, diag::err_arg_with_address_space);
14106     New->setInvalidDecl();
14107   }
14108 
14109   // PPC MMA non-pointer types are not allowed as function argument types.
14110   if (Context.getTargetInfo().getTriple().isPPC64() &&
14111       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14112     New->setInvalidDecl();
14113   }
14114 
14115   return New;
14116 }
14117 
14118 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14119                                            SourceLocation LocAfterDecls) {
14120   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14121 
14122   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14123   // for a K&R function.
14124   if (!FTI.hasPrototype) {
14125     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14126       --i;
14127       if (FTI.Params[i].Param == nullptr) {
14128         SmallString<256> Code;
14129         llvm::raw_svector_ostream(Code)
14130             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14131         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14132             << FTI.Params[i].Ident
14133             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14134 
14135         // Implicitly declare the argument as type 'int' for lack of a better
14136         // type.
14137         AttributeFactory attrs;
14138         DeclSpec DS(attrs);
14139         const char* PrevSpec; // unused
14140         unsigned DiagID; // unused
14141         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14142                            DiagID, Context.getPrintingPolicy());
14143         // Use the identifier location for the type source range.
14144         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14145         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14146         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14147         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14148         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14149       }
14150     }
14151   }
14152 }
14153 
14154 Decl *
14155 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14156                               MultiTemplateParamsArg TemplateParameterLists,
14157                               SkipBodyInfo *SkipBody) {
14158   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14159   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14160   Scope *ParentScope = FnBodyScope->getParent();
14161 
14162   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14163   // we define a non-templated function definition, we will create a declaration
14164   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14165   // The base function declaration will have the equivalent of an `omp declare
14166   // variant` annotation which specifies the mangled definition as a
14167   // specialization function under the OpenMP context defined as part of the
14168   // `omp begin declare variant`.
14169   SmallVector<FunctionDecl *, 4> Bases;
14170   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14171     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14172         ParentScope, D, TemplateParameterLists, Bases);
14173 
14174   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14175   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14176   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14177 
14178   if (!Bases.empty())
14179     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14180 
14181   return Dcl;
14182 }
14183 
14184 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14185   Consumer.HandleInlineFunctionDefinition(D);
14186 }
14187 
14188 static bool
14189 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14190                                 const FunctionDecl *&PossiblePrototype) {
14191   // Don't warn about invalid declarations.
14192   if (FD->isInvalidDecl())
14193     return false;
14194 
14195   // Or declarations that aren't global.
14196   if (!FD->isGlobal())
14197     return false;
14198 
14199   if (!FD->isExternallyVisible())
14200     return false;
14201 
14202   // Don't warn about C++ member functions.
14203   if (isa<CXXMethodDecl>(FD))
14204     return false;
14205 
14206   // Don't warn about 'main'.
14207   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14208     if (IdentifierInfo *II = FD->getIdentifier())
14209       if (II->isStr("main") || II->isStr("efi_main"))
14210         return false;
14211 
14212   // Don't warn about inline functions.
14213   if (FD->isInlined())
14214     return false;
14215 
14216   // Don't warn about function templates.
14217   if (FD->getDescribedFunctionTemplate())
14218     return false;
14219 
14220   // Don't warn about function template specializations.
14221   if (FD->isFunctionTemplateSpecialization())
14222     return false;
14223 
14224   // Don't warn for OpenCL kernels.
14225   if (FD->hasAttr<OpenCLKernelAttr>())
14226     return false;
14227 
14228   // Don't warn on explicitly deleted functions.
14229   if (FD->isDeleted())
14230     return false;
14231 
14232   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14233        Prev; Prev = Prev->getPreviousDecl()) {
14234     // Ignore any declarations that occur in function or method
14235     // scope, because they aren't visible from the header.
14236     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14237       continue;
14238 
14239     PossiblePrototype = Prev;
14240     return Prev->getType()->isFunctionNoProtoType();
14241   }
14242 
14243   return true;
14244 }
14245 
14246 void
14247 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14248                                    const FunctionDecl *EffectiveDefinition,
14249                                    SkipBodyInfo *SkipBody) {
14250   const FunctionDecl *Definition = EffectiveDefinition;
14251   if (!Definition &&
14252       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14253     return;
14254 
14255   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14256     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14257       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14258         // A merged copy of the same function, instantiated as a member of
14259         // the same class, is OK.
14260         if (declaresSameEntity(OrigFD, OrigDef) &&
14261             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14262                                cast<Decl>(FD->getLexicalDeclContext())))
14263           return;
14264       }
14265     }
14266   }
14267 
14268   if (canRedefineFunction(Definition, getLangOpts()))
14269     return;
14270 
14271   // Don't emit an error when this is redefinition of a typo-corrected
14272   // definition.
14273   if (TypoCorrectedFunctionDefinitions.count(Definition))
14274     return;
14275 
14276   // If we don't have a visible definition of the function, and it's inline or
14277   // a template, skip the new definition.
14278   if (SkipBody && !hasVisibleDefinition(Definition) &&
14279       (Definition->getFormalLinkage() == InternalLinkage ||
14280        Definition->isInlined() ||
14281        Definition->getDescribedFunctionTemplate() ||
14282        Definition->getNumTemplateParameterLists())) {
14283     SkipBody->ShouldSkip = true;
14284     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14285     if (auto *TD = Definition->getDescribedFunctionTemplate())
14286       makeMergedDefinitionVisible(TD);
14287     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14288     return;
14289   }
14290 
14291   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14292       Definition->getStorageClass() == SC_Extern)
14293     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14294         << FD << getLangOpts().CPlusPlus;
14295   else
14296     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14297 
14298   Diag(Definition->getLocation(), diag::note_previous_definition);
14299   FD->setInvalidDecl();
14300 }
14301 
14302 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14303                                    Sema &S) {
14304   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14305 
14306   LambdaScopeInfo *LSI = S.PushLambdaScope();
14307   LSI->CallOperator = CallOperator;
14308   LSI->Lambda = LambdaClass;
14309   LSI->ReturnType = CallOperator->getReturnType();
14310   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14311 
14312   if (LCD == LCD_None)
14313     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14314   else if (LCD == LCD_ByCopy)
14315     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14316   else if (LCD == LCD_ByRef)
14317     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14318   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14319 
14320   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14321   LSI->Mutable = !CallOperator->isConst();
14322 
14323   // Add the captures to the LSI so they can be noted as already
14324   // captured within tryCaptureVar.
14325   auto I = LambdaClass->field_begin();
14326   for (const auto &C : LambdaClass->captures()) {
14327     if (C.capturesVariable()) {
14328       VarDecl *VD = C.getCapturedVar();
14329       if (VD->isInitCapture())
14330         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14331       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14332       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14333           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14334           /*EllipsisLoc*/C.isPackExpansion()
14335                          ? C.getEllipsisLoc() : SourceLocation(),
14336           I->getType(), /*Invalid*/false);
14337 
14338     } else if (C.capturesThis()) {
14339       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14340                           C.getCaptureKind() == LCK_StarThis);
14341     } else {
14342       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14343                              I->getType());
14344     }
14345     ++I;
14346   }
14347 }
14348 
14349 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14350                                     SkipBodyInfo *SkipBody) {
14351   if (!D) {
14352     // Parsing the function declaration failed in some way. Push on a fake scope
14353     // anyway so we can try to parse the function body.
14354     PushFunctionScope();
14355     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14356     return D;
14357   }
14358 
14359   FunctionDecl *FD = nullptr;
14360 
14361   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14362     FD = FunTmpl->getTemplatedDecl();
14363   else
14364     FD = cast<FunctionDecl>(D);
14365 
14366   // Do not push if it is a lambda because one is already pushed when building
14367   // the lambda in ActOnStartOfLambdaDefinition().
14368   if (!isLambdaCallOperator(FD))
14369     PushExpressionEvaluationContext(
14370         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14371                           : ExprEvalContexts.back().Context);
14372 
14373   // Check for defining attributes before the check for redefinition.
14374   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14375     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14376     FD->dropAttr<AliasAttr>();
14377     FD->setInvalidDecl();
14378   }
14379   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14380     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14381     FD->dropAttr<IFuncAttr>();
14382     FD->setInvalidDecl();
14383   }
14384 
14385   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14386     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14387         Ctor->isDefaultConstructor() &&
14388         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14389       // If this is an MS ABI dllexport default constructor, instantiate any
14390       // default arguments.
14391       InstantiateDefaultCtorDefaultArgs(Ctor);
14392     }
14393   }
14394 
14395   // See if this is a redefinition. If 'will have body' (or similar) is already
14396   // set, then these checks were already performed when it was set.
14397   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14398       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14399     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14400 
14401     // If we're skipping the body, we're done. Don't enter the scope.
14402     if (SkipBody && SkipBody->ShouldSkip)
14403       return D;
14404   }
14405 
14406   // Mark this function as "will have a body eventually".  This lets users to
14407   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14408   // this function.
14409   FD->setWillHaveBody();
14410 
14411   // If we are instantiating a generic lambda call operator, push
14412   // a LambdaScopeInfo onto the function stack.  But use the information
14413   // that's already been calculated (ActOnLambdaExpr) to prime the current
14414   // LambdaScopeInfo.
14415   // When the template operator is being specialized, the LambdaScopeInfo,
14416   // has to be properly restored so that tryCaptureVariable doesn't try
14417   // and capture any new variables. In addition when calculating potential
14418   // captures during transformation of nested lambdas, it is necessary to
14419   // have the LSI properly restored.
14420   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14421     assert(inTemplateInstantiation() &&
14422            "There should be an active template instantiation on the stack "
14423            "when instantiating a generic lambda!");
14424     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14425   } else {
14426     // Enter a new function scope
14427     PushFunctionScope();
14428   }
14429 
14430   // Builtin functions cannot be defined.
14431   if (unsigned BuiltinID = FD->getBuiltinID()) {
14432     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14433         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14434       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14435       FD->setInvalidDecl();
14436     }
14437   }
14438 
14439   // The return type of a function definition must be complete
14440   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14441   QualType ResultType = FD->getReturnType();
14442   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14443       !FD->isInvalidDecl() &&
14444       RequireCompleteType(FD->getLocation(), ResultType,
14445                           diag::err_func_def_incomplete_result))
14446     FD->setInvalidDecl();
14447 
14448   if (FnBodyScope)
14449     PushDeclContext(FnBodyScope, FD);
14450 
14451   // Check the validity of our function parameters
14452   CheckParmsForFunctionDef(FD->parameters(),
14453                            /*CheckParameterNames=*/true);
14454 
14455   // Add non-parameter declarations already in the function to the current
14456   // scope.
14457   if (FnBodyScope) {
14458     for (Decl *NPD : FD->decls()) {
14459       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14460       if (!NonParmDecl)
14461         continue;
14462       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14463              "parameters should not be in newly created FD yet");
14464 
14465       // If the decl has a name, make it accessible in the current scope.
14466       if (NonParmDecl->getDeclName())
14467         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14468 
14469       // Similarly, dive into enums and fish their constants out, making them
14470       // accessible in this scope.
14471       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14472         for (auto *EI : ED->enumerators())
14473           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14474       }
14475     }
14476   }
14477 
14478   // Introduce our parameters into the function scope
14479   for (auto Param : FD->parameters()) {
14480     Param->setOwningFunction(FD);
14481 
14482     // If this has an identifier, add it to the scope stack.
14483     if (Param->getIdentifier() && FnBodyScope) {
14484       CheckShadow(FnBodyScope, Param);
14485 
14486       PushOnScopeChains(Param, FnBodyScope);
14487     }
14488   }
14489 
14490   // Ensure that the function's exception specification is instantiated.
14491   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14492     ResolveExceptionSpec(D->getLocation(), FPT);
14493 
14494   // dllimport cannot be applied to non-inline function definitions.
14495   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14496       !FD->isTemplateInstantiation()) {
14497     assert(!FD->hasAttr<DLLExportAttr>());
14498     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14499     FD->setInvalidDecl();
14500     return D;
14501   }
14502   // We want to attach documentation to original Decl (which might be
14503   // a function template).
14504   ActOnDocumentableDecl(D);
14505   if (getCurLexicalContext()->isObjCContainer() &&
14506       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14507       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14508     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14509 
14510   return D;
14511 }
14512 
14513 /// Given the set of return statements within a function body,
14514 /// compute the variables that are subject to the named return value
14515 /// optimization.
14516 ///
14517 /// Each of the variables that is subject to the named return value
14518 /// optimization will be marked as NRVO variables in the AST, and any
14519 /// return statement that has a marked NRVO variable as its NRVO candidate can
14520 /// use the named return value optimization.
14521 ///
14522 /// This function applies a very simplistic algorithm for NRVO: if every return
14523 /// statement in the scope of a variable has the same NRVO candidate, that
14524 /// candidate is an NRVO variable.
14525 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14526   ReturnStmt **Returns = Scope->Returns.data();
14527 
14528   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14529     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14530       if (!NRVOCandidate->isNRVOVariable())
14531         Returns[I]->setNRVOCandidate(nullptr);
14532     }
14533   }
14534 }
14535 
14536 bool Sema::canDelayFunctionBody(const Declarator &D) {
14537   // We can't delay parsing the body of a constexpr function template (yet).
14538   if (D.getDeclSpec().hasConstexprSpecifier())
14539     return false;
14540 
14541   // We can't delay parsing the body of a function template with a deduced
14542   // return type (yet).
14543   if (D.getDeclSpec().hasAutoTypeSpec()) {
14544     // If the placeholder introduces a non-deduced trailing return type,
14545     // we can still delay parsing it.
14546     if (D.getNumTypeObjects()) {
14547       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14548       if (Outer.Kind == DeclaratorChunk::Function &&
14549           Outer.Fun.hasTrailingReturnType()) {
14550         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14551         return Ty.isNull() || !Ty->isUndeducedType();
14552       }
14553     }
14554     return false;
14555   }
14556 
14557   return true;
14558 }
14559 
14560 bool Sema::canSkipFunctionBody(Decl *D) {
14561   // We cannot skip the body of a function (or function template) which is
14562   // constexpr, since we may need to evaluate its body in order to parse the
14563   // rest of the file.
14564   // We cannot skip the body of a function with an undeduced return type,
14565   // because any callers of that function need to know the type.
14566   if (const FunctionDecl *FD = D->getAsFunction()) {
14567     if (FD->isConstexpr())
14568       return false;
14569     // We can't simply call Type::isUndeducedType here, because inside template
14570     // auto can be deduced to a dependent type, which is not considered
14571     // "undeduced".
14572     if (FD->getReturnType()->getContainedDeducedType())
14573       return false;
14574   }
14575   return Consumer.shouldSkipFunctionBody(D);
14576 }
14577 
14578 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14579   if (!Decl)
14580     return nullptr;
14581   if (FunctionDecl *FD = Decl->getAsFunction())
14582     FD->setHasSkippedBody();
14583   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14584     MD->setHasSkippedBody();
14585   return Decl;
14586 }
14587 
14588 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14589   return ActOnFinishFunctionBody(D, BodyArg, false);
14590 }
14591 
14592 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14593 /// body.
14594 class ExitFunctionBodyRAII {
14595 public:
14596   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14597   ~ExitFunctionBodyRAII() {
14598     if (!IsLambda)
14599       S.PopExpressionEvaluationContext();
14600   }
14601 
14602 private:
14603   Sema &S;
14604   bool IsLambda = false;
14605 };
14606 
14607 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14608   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14609 
14610   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14611     if (EscapeInfo.count(BD))
14612       return EscapeInfo[BD];
14613 
14614     bool R = false;
14615     const BlockDecl *CurBD = BD;
14616 
14617     do {
14618       R = !CurBD->doesNotEscape();
14619       if (R)
14620         break;
14621       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14622     } while (CurBD);
14623 
14624     return EscapeInfo[BD] = R;
14625   };
14626 
14627   // If the location where 'self' is implicitly retained is inside a escaping
14628   // block, emit a diagnostic.
14629   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14630        S.ImplicitlyRetainedSelfLocs)
14631     if (IsOrNestedInEscapingBlock(P.second))
14632       S.Diag(P.first, diag::warn_implicitly_retains_self)
14633           << FixItHint::CreateInsertion(P.first, "self->");
14634 }
14635 
14636 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14637                                     bool IsInstantiation) {
14638   FunctionScopeInfo *FSI = getCurFunction();
14639   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14640 
14641   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14642     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14643 
14644   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14645   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14646 
14647   if (getLangOpts().Coroutines && FSI->isCoroutine())
14648     CheckCompletedCoroutineBody(FD, Body);
14649 
14650   {
14651     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14652     // one is already popped when finishing the lambda in BuildLambdaExpr().
14653     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14654     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14655 
14656     if (FD) {
14657       FD->setBody(Body);
14658       FD->setWillHaveBody(false);
14659 
14660       if (getLangOpts().CPlusPlus14) {
14661         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14662             FD->getReturnType()->isUndeducedType()) {
14663           // If the function has a deduced result type but contains no 'return'
14664           // statements, the result type as written must be exactly 'auto', and
14665           // the deduced result type is 'void'.
14666           if (!FD->getReturnType()->getAs<AutoType>()) {
14667             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14668                 << FD->getReturnType();
14669             FD->setInvalidDecl();
14670           } else {
14671             // Substitute 'void' for the 'auto' in the type.
14672             TypeLoc ResultType = getReturnTypeLoc(FD);
14673             Context.adjustDeducedFunctionResultType(
14674                 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14675           }
14676         }
14677       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14678         // In C++11, we don't use 'auto' deduction rules for lambda call
14679         // operators because we don't support return type deduction.
14680         auto *LSI = getCurLambda();
14681         if (LSI->HasImplicitReturnType) {
14682           deduceClosureReturnType(*LSI);
14683 
14684           // C++11 [expr.prim.lambda]p4:
14685           //   [...] if there are no return statements in the compound-statement
14686           //   [the deduced type is] the type void
14687           QualType RetType =
14688               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14689 
14690           // Update the return type to the deduced type.
14691           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14692           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14693                                               Proto->getExtProtoInfo()));
14694         }
14695       }
14696 
14697       // If the function implicitly returns zero (like 'main') or is naked,
14698       // don't complain about missing return statements.
14699       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14700         WP.disableCheckFallThrough();
14701 
14702       // MSVC permits the use of pure specifier (=0) on function definition,
14703       // defined at class scope, warn about this non-standard construct.
14704       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14705         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14706 
14707       if (!FD->isInvalidDecl()) {
14708         // Don't diagnose unused parameters of defaulted, deleted or naked
14709         // functions.
14710         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14711             !FD->hasAttr<NakedAttr>())
14712           DiagnoseUnusedParameters(FD->parameters());
14713         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14714                                                FD->getReturnType(), FD);
14715 
14716         // If this is a structor, we need a vtable.
14717         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14718           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14719         else if (CXXDestructorDecl *Destructor =
14720                      dyn_cast<CXXDestructorDecl>(FD))
14721           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14722 
14723         // Try to apply the named return value optimization. We have to check
14724         // if we can do this here because lambdas keep return statements around
14725         // to deduce an implicit return type.
14726         if (FD->getReturnType()->isRecordType() &&
14727             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14728           computeNRVO(Body, FSI);
14729       }
14730 
14731       // GNU warning -Wmissing-prototypes:
14732       //   Warn if a global function is defined without a previous
14733       //   prototype declaration. This warning is issued even if the
14734       //   definition itself provides a prototype. The aim is to detect
14735       //   global functions that fail to be declared in header files.
14736       const FunctionDecl *PossiblePrototype = nullptr;
14737       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14738         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14739 
14740         if (PossiblePrototype) {
14741           // We found a declaration that is not a prototype,
14742           // but that could be a zero-parameter prototype
14743           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14744             TypeLoc TL = TI->getTypeLoc();
14745             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14746               Diag(PossiblePrototype->getLocation(),
14747                    diag::note_declaration_not_a_prototype)
14748                   << (FD->getNumParams() != 0)
14749                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14750                                                     FTL.getRParenLoc(), "void")
14751                                               : FixItHint{});
14752           }
14753         } else {
14754           // Returns true if the token beginning at this Loc is `const`.
14755           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14756                                   const LangOptions &LangOpts) {
14757             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14758             if (LocInfo.first.isInvalid())
14759               return false;
14760 
14761             bool Invalid = false;
14762             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14763             if (Invalid)
14764               return false;
14765 
14766             if (LocInfo.second > Buffer.size())
14767               return false;
14768 
14769             const char *LexStart = Buffer.data() + LocInfo.second;
14770             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14771 
14772             return StartTok.consume_front("const") &&
14773                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14774                     StartTok.startswith("/*") || StartTok.startswith("//"));
14775           };
14776 
14777           auto findBeginLoc = [&]() {
14778             // If the return type has `const` qualifier, we want to insert
14779             // `static` before `const` (and not before the typename).
14780             if ((FD->getReturnType()->isAnyPointerType() &&
14781                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14782                 FD->getReturnType().isConstQualified()) {
14783               // But only do this if we can determine where the `const` is.
14784 
14785               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14786                                getLangOpts()))
14787 
14788                 return FD->getBeginLoc();
14789             }
14790             return FD->getTypeSpecStartLoc();
14791           };
14792           Diag(FD->getTypeSpecStartLoc(),
14793                diag::note_static_for_internal_linkage)
14794               << /* function */ 1
14795               << (FD->getStorageClass() == SC_None
14796                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14797                       : FixItHint{});
14798         }
14799 
14800         // GNU warning -Wstrict-prototypes
14801         //   Warn if K&R function is defined without a previous declaration.
14802         //   This warning is issued only if the definition itself does not
14803         //   provide a prototype. Only K&R definitions do not provide a
14804         //   prototype.
14805         if (!FD->hasWrittenPrototype()) {
14806           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14807           TypeLoc TL = TI->getTypeLoc();
14808           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14809           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14810         }
14811       }
14812 
14813       // Warn on CPUDispatch with an actual body.
14814       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14815         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14816           if (!CmpndBody->body_empty())
14817             Diag(CmpndBody->body_front()->getBeginLoc(),
14818                  diag::warn_dispatch_body_ignored);
14819 
14820       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14821         const CXXMethodDecl *KeyFunction;
14822         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14823             MD->isVirtual() &&
14824             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14825             MD == KeyFunction->getCanonicalDecl()) {
14826           // Update the key-function state if necessary for this ABI.
14827           if (FD->isInlined() &&
14828               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14829             Context.setNonKeyFunction(MD);
14830 
14831             // If the newly-chosen key function is already defined, then we
14832             // need to mark the vtable as used retroactively.
14833             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14834             const FunctionDecl *Definition;
14835             if (KeyFunction && KeyFunction->isDefined(Definition))
14836               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14837           } else {
14838             // We just defined they key function; mark the vtable as used.
14839             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14840           }
14841         }
14842       }
14843 
14844       assert(
14845           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14846           "Function parsing confused");
14847     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14848       assert(MD == getCurMethodDecl() && "Method parsing confused");
14849       MD->setBody(Body);
14850       if (!MD->isInvalidDecl()) {
14851         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14852                                                MD->getReturnType(), MD);
14853 
14854         if (Body)
14855           computeNRVO(Body, FSI);
14856       }
14857       if (FSI->ObjCShouldCallSuper) {
14858         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14859             << MD->getSelector().getAsString();
14860         FSI->ObjCShouldCallSuper = false;
14861       }
14862       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14863         const ObjCMethodDecl *InitMethod = nullptr;
14864         bool isDesignated =
14865             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14866         assert(isDesignated && InitMethod);
14867         (void)isDesignated;
14868 
14869         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14870           auto IFace = MD->getClassInterface();
14871           if (!IFace)
14872             return false;
14873           auto SuperD = IFace->getSuperClass();
14874           if (!SuperD)
14875             return false;
14876           return SuperD->getIdentifier() ==
14877                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14878         };
14879         // Don't issue this warning for unavailable inits or direct subclasses
14880         // of NSObject.
14881         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14882           Diag(MD->getLocation(),
14883                diag::warn_objc_designated_init_missing_super_call);
14884           Diag(InitMethod->getLocation(),
14885                diag::note_objc_designated_init_marked_here);
14886         }
14887         FSI->ObjCWarnForNoDesignatedInitChain = false;
14888       }
14889       if (FSI->ObjCWarnForNoInitDelegation) {
14890         // Don't issue this warning for unavaialable inits.
14891         if (!MD->isUnavailable())
14892           Diag(MD->getLocation(),
14893                diag::warn_objc_secondary_init_missing_init_call);
14894         FSI->ObjCWarnForNoInitDelegation = false;
14895       }
14896 
14897       diagnoseImplicitlyRetainedSelf(*this);
14898     } else {
14899       // Parsing the function declaration failed in some way. Pop the fake scope
14900       // we pushed on.
14901       PopFunctionScopeInfo(ActivePolicy, dcl);
14902       return nullptr;
14903     }
14904 
14905     if (Body && FSI->HasPotentialAvailabilityViolations)
14906       DiagnoseUnguardedAvailabilityViolations(dcl);
14907 
14908     assert(!FSI->ObjCShouldCallSuper &&
14909            "This should only be set for ObjC methods, which should have been "
14910            "handled in the block above.");
14911 
14912     // Verify and clean out per-function state.
14913     if (Body && (!FD || !FD->isDefaulted())) {
14914       // C++ constructors that have function-try-blocks can't have return
14915       // statements in the handlers of that block. (C++ [except.handle]p14)
14916       // Verify this.
14917       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14918         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14919 
14920       // Verify that gotos and switch cases don't jump into scopes illegally.
14921       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14922         DiagnoseInvalidJumps(Body);
14923 
14924       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14925         if (!Destructor->getParent()->isDependentType())
14926           CheckDestructor(Destructor);
14927 
14928         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14929                                                Destructor->getParent());
14930       }
14931 
14932       // If any errors have occurred, clear out any temporaries that may have
14933       // been leftover. This ensures that these temporaries won't be picked up
14934       // for deletion in some later function.
14935       if (hasUncompilableErrorOccurred() ||
14936           getDiagnostics().getSuppressAllDiagnostics()) {
14937         DiscardCleanupsInEvaluationContext();
14938       }
14939       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14940         // Since the body is valid, issue any analysis-based warnings that are
14941         // enabled.
14942         ActivePolicy = &WP;
14943       }
14944 
14945       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14946           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14947         FD->setInvalidDecl();
14948 
14949       if (FD && FD->hasAttr<NakedAttr>()) {
14950         for (const Stmt *S : Body->children()) {
14951           // Allow local register variables without initializer as they don't
14952           // require prologue.
14953           bool RegisterVariables = false;
14954           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14955             for (const auto *Decl : DS->decls()) {
14956               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14957                 RegisterVariables =
14958                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14959                 if (!RegisterVariables)
14960                   break;
14961               }
14962             }
14963           }
14964           if (RegisterVariables)
14965             continue;
14966           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14967             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14968             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14969             FD->setInvalidDecl();
14970             break;
14971           }
14972         }
14973       }
14974 
14975       assert(ExprCleanupObjects.size() ==
14976                  ExprEvalContexts.back().NumCleanupObjects &&
14977              "Leftover temporaries in function");
14978       assert(!Cleanup.exprNeedsCleanups() &&
14979              "Unaccounted cleanups in function");
14980       assert(MaybeODRUseExprs.empty() &&
14981              "Leftover expressions for odr-use checking");
14982     }
14983   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14984     // the declaration context below. Otherwise, we're unable to transform
14985     // 'this' expressions when transforming immediate context functions.
14986 
14987   if (!IsInstantiation)
14988     PopDeclContext();
14989 
14990   PopFunctionScopeInfo(ActivePolicy, dcl);
14991   // If any errors have occurred, clear out any temporaries that may have
14992   // been leftover. This ensures that these temporaries won't be picked up for
14993   // deletion in some later function.
14994   if (hasUncompilableErrorOccurred()) {
14995     DiscardCleanupsInEvaluationContext();
14996   }
14997 
14998   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
14999                                   !LangOpts.OMPTargetTriples.empty())) ||
15000              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15001     auto ES = getEmissionStatus(FD);
15002     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15003         ES == Sema::FunctionEmissionStatus::Unknown)
15004       DeclsToCheckForDeferredDiags.insert(FD);
15005   }
15006 
15007   if (FD && !FD->isDeleted())
15008     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15009 
15010   return dcl;
15011 }
15012 
15013 /// When we finish delayed parsing of an attribute, we must attach it to the
15014 /// relevant Decl.
15015 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15016                                        ParsedAttributes &Attrs) {
15017   // Always attach attributes to the underlying decl.
15018   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15019     D = TD->getTemplatedDecl();
15020   ProcessDeclAttributeList(S, D, Attrs);
15021 
15022   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15023     if (Method->isStatic())
15024       checkThisInStaticMemberFunctionAttributes(Method);
15025 }
15026 
15027 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15028 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15029 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15030                                           IdentifierInfo &II, Scope *S) {
15031   // Find the scope in which the identifier is injected and the corresponding
15032   // DeclContext.
15033   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15034   // In that case, we inject the declaration into the translation unit scope
15035   // instead.
15036   Scope *BlockScope = S;
15037   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15038     BlockScope = BlockScope->getParent();
15039 
15040   Scope *ContextScope = BlockScope;
15041   while (!ContextScope->getEntity())
15042     ContextScope = ContextScope->getParent();
15043   ContextRAII SavedContext(*this, ContextScope->getEntity());
15044 
15045   // Before we produce a declaration for an implicitly defined
15046   // function, see whether there was a locally-scoped declaration of
15047   // this name as a function or variable. If so, use that
15048   // (non-visible) declaration, and complain about it.
15049   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15050   if (ExternCPrev) {
15051     // We still need to inject the function into the enclosing block scope so
15052     // that later (non-call) uses can see it.
15053     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15054 
15055     // C89 footnote 38:
15056     //   If in fact it is not defined as having type "function returning int",
15057     //   the behavior is undefined.
15058     if (!isa<FunctionDecl>(ExternCPrev) ||
15059         !Context.typesAreCompatible(
15060             cast<FunctionDecl>(ExternCPrev)->getType(),
15061             Context.getFunctionNoProtoType(Context.IntTy))) {
15062       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15063           << ExternCPrev << !getLangOpts().C99;
15064       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15065       return ExternCPrev;
15066     }
15067   }
15068 
15069   // Extension in C99.  Legal in C90, but warn about it.
15070   unsigned diag_id;
15071   if (II.getName().startswith("__builtin_"))
15072     diag_id = diag::warn_builtin_unknown;
15073   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15074   else if (getLangOpts().OpenCL)
15075     diag_id = diag::err_opencl_implicit_function_decl;
15076   else if (getLangOpts().C99)
15077     diag_id = diag::ext_implicit_function_decl;
15078   else
15079     diag_id = diag::warn_implicit_function_decl;
15080 
15081   TypoCorrection Corrected;
15082   // Because typo correction is expensive, only do it if the implicit
15083   // function declaration is going to be treated as an error.
15084   //
15085   // Perform the corection before issuing the main diagnostic, as some consumers
15086   // use typo-correction callbacks to enhance the main diagnostic.
15087   if (S && !ExternCPrev &&
15088       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15089     DeclFilterCCC<FunctionDecl> CCC{};
15090     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15091                             S, nullptr, CCC, CTK_NonError);
15092   }
15093 
15094   Diag(Loc, diag_id) << &II;
15095   if (Corrected)
15096     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15097                  /*ErrorRecovery*/ false);
15098 
15099   // If we found a prior declaration of this function, don't bother building
15100   // another one. We've already pushed that one into scope, so there's nothing
15101   // more to do.
15102   if (ExternCPrev)
15103     return ExternCPrev;
15104 
15105   // Set a Declarator for the implicit definition: int foo();
15106   const char *Dummy;
15107   AttributeFactory attrFactory;
15108   DeclSpec DS(attrFactory);
15109   unsigned DiagID;
15110   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15111                                   Context.getPrintingPolicy());
15112   (void)Error; // Silence warning.
15113   assert(!Error && "Error setting up implicit decl!");
15114   SourceLocation NoLoc;
15115   Declarator D(DS, DeclaratorContext::Block);
15116   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15117                                              /*IsAmbiguous=*/false,
15118                                              /*LParenLoc=*/NoLoc,
15119                                              /*Params=*/nullptr,
15120                                              /*NumParams=*/0,
15121                                              /*EllipsisLoc=*/NoLoc,
15122                                              /*RParenLoc=*/NoLoc,
15123                                              /*RefQualifierIsLvalueRef=*/true,
15124                                              /*RefQualifierLoc=*/NoLoc,
15125                                              /*MutableLoc=*/NoLoc, EST_None,
15126                                              /*ESpecRange=*/SourceRange(),
15127                                              /*Exceptions=*/nullptr,
15128                                              /*ExceptionRanges=*/nullptr,
15129                                              /*NumExceptions=*/0,
15130                                              /*NoexceptExpr=*/nullptr,
15131                                              /*ExceptionSpecTokens=*/nullptr,
15132                                              /*DeclsInPrototype=*/None, Loc,
15133                                              Loc, D),
15134                 std::move(DS.getAttributes()), SourceLocation());
15135   D.SetIdentifier(&II, Loc);
15136 
15137   // Insert this function into the enclosing block scope.
15138   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15139   FD->setImplicit();
15140 
15141   AddKnownFunctionAttributes(FD);
15142 
15143   return FD;
15144 }
15145 
15146 /// If this function is a C++ replaceable global allocation function
15147 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15148 /// adds any function attributes that we know a priori based on the standard.
15149 ///
15150 /// We need to check for duplicate attributes both here and where user-written
15151 /// attributes are applied to declarations.
15152 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15153     FunctionDecl *FD) {
15154   if (FD->isInvalidDecl())
15155     return;
15156 
15157   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15158       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15159     return;
15160 
15161   Optional<unsigned> AlignmentParam;
15162   bool IsNothrow = false;
15163   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15164     return;
15165 
15166   // C++2a [basic.stc.dynamic.allocation]p4:
15167   //   An allocation function that has a non-throwing exception specification
15168   //   indicates failure by returning a null pointer value. Any other allocation
15169   //   function never returns a null pointer value and indicates failure only by
15170   //   throwing an exception [...]
15171   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15172     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15173 
15174   // C++2a [basic.stc.dynamic.allocation]p2:
15175   //   An allocation function attempts to allocate the requested amount of
15176   //   storage. [...] If the request succeeds, the value returned by a
15177   //   replaceable allocation function is a [...] pointer value p0 different
15178   //   from any previously returned value p1 [...]
15179   //
15180   // However, this particular information is being added in codegen,
15181   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15182 
15183   // C++2a [basic.stc.dynamic.allocation]p2:
15184   //   An allocation function attempts to allocate the requested amount of
15185   //   storage. If it is successful, it returns the address of the start of a
15186   //   block of storage whose length in bytes is at least as large as the
15187   //   requested size.
15188   if (!FD->hasAttr<AllocSizeAttr>()) {
15189     FD->addAttr(AllocSizeAttr::CreateImplicit(
15190         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15191         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15192   }
15193 
15194   // C++2a [basic.stc.dynamic.allocation]p3:
15195   //   For an allocation function [...], the pointer returned on a successful
15196   //   call shall represent the address of storage that is aligned as follows:
15197   //   (3.1) If the allocation function takes an argument of type
15198   //         std​::​align_­val_­t, the storage will have the alignment
15199   //         specified by the value of this argument.
15200   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15201     FD->addAttr(AllocAlignAttr::CreateImplicit(
15202         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15203   }
15204 
15205   // FIXME:
15206   // C++2a [basic.stc.dynamic.allocation]p3:
15207   //   For an allocation function [...], the pointer returned on a successful
15208   //   call shall represent the address of storage that is aligned as follows:
15209   //   (3.2) Otherwise, if the allocation function is named operator new[],
15210   //         the storage is aligned for any object that does not have
15211   //         new-extended alignment ([basic.align]) and is no larger than the
15212   //         requested size.
15213   //   (3.3) Otherwise, the storage is aligned for any object that does not
15214   //         have new-extended alignment and is of the requested size.
15215 }
15216 
15217 /// Adds any function attributes that we know a priori based on
15218 /// the declaration of this function.
15219 ///
15220 /// These attributes can apply both to implicitly-declared builtins
15221 /// (like __builtin___printf_chk) or to library-declared functions
15222 /// like NSLog or printf.
15223 ///
15224 /// We need to check for duplicate attributes both here and where user-written
15225 /// attributes are applied to declarations.
15226 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15227   if (FD->isInvalidDecl())
15228     return;
15229 
15230   // If this is a built-in function, map its builtin attributes to
15231   // actual attributes.
15232   if (unsigned BuiltinID = FD->getBuiltinID()) {
15233     // Handle printf-formatting attributes.
15234     unsigned FormatIdx;
15235     bool HasVAListArg;
15236     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15237       if (!FD->hasAttr<FormatAttr>()) {
15238         const char *fmt = "printf";
15239         unsigned int NumParams = FD->getNumParams();
15240         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15241             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15242           fmt = "NSString";
15243         FD->addAttr(FormatAttr::CreateImplicit(Context,
15244                                                &Context.Idents.get(fmt),
15245                                                FormatIdx+1,
15246                                                HasVAListArg ? 0 : FormatIdx+2,
15247                                                FD->getLocation()));
15248       }
15249     }
15250     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15251                                              HasVAListArg)) {
15252      if (!FD->hasAttr<FormatAttr>())
15253        FD->addAttr(FormatAttr::CreateImplicit(Context,
15254                                               &Context.Idents.get("scanf"),
15255                                               FormatIdx+1,
15256                                               HasVAListArg ? 0 : FormatIdx+2,
15257                                               FD->getLocation()));
15258     }
15259 
15260     // Handle automatically recognized callbacks.
15261     SmallVector<int, 4> Encoding;
15262     if (!FD->hasAttr<CallbackAttr>() &&
15263         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15264       FD->addAttr(CallbackAttr::CreateImplicit(
15265           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15266 
15267     // Mark const if we don't care about errno and that is the only thing
15268     // preventing the function from being const. This allows IRgen to use LLVM
15269     // intrinsics for such functions.
15270     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15271         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15272       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15273 
15274     // We make "fma" on GNU or Windows const because we know it does not set
15275     // errno in those environments even though it could set errno based on the
15276     // C standard.
15277     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15278     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15279         !FD->hasAttr<ConstAttr>()) {
15280       switch (BuiltinID) {
15281       case Builtin::BI__builtin_fma:
15282       case Builtin::BI__builtin_fmaf:
15283       case Builtin::BI__builtin_fmal:
15284       case Builtin::BIfma:
15285       case Builtin::BIfmaf:
15286       case Builtin::BIfmal:
15287         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15288         break;
15289       default:
15290         break;
15291       }
15292     }
15293 
15294     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15295         !FD->hasAttr<ReturnsTwiceAttr>())
15296       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15297                                          FD->getLocation()));
15298     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15299       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15300     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15301       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15302     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15303       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15304     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15305         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15306       // Add the appropriate attribute, depending on the CUDA compilation mode
15307       // and which target the builtin belongs to. For example, during host
15308       // compilation, aux builtins are __device__, while the rest are __host__.
15309       if (getLangOpts().CUDAIsDevice !=
15310           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15311         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15312       else
15313         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15314     }
15315 
15316     // Add known guaranteed alignment for allocation functions.
15317     switch (BuiltinID) {
15318     case Builtin::BIaligned_alloc:
15319       if (!FD->hasAttr<AllocAlignAttr>())
15320         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15321                                                    FD->getLocation()));
15322       break;
15323     default:
15324       break;
15325     }
15326   }
15327 
15328   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15329 
15330   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15331   // throw, add an implicit nothrow attribute to any extern "C" function we come
15332   // across.
15333   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15334       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15335     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15336     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15337       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15338   }
15339 
15340   IdentifierInfo *Name = FD->getIdentifier();
15341   if (!Name)
15342     return;
15343   if ((!getLangOpts().CPlusPlus &&
15344        FD->getDeclContext()->isTranslationUnit()) ||
15345       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15346        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15347        LinkageSpecDecl::lang_c)) {
15348     // Okay: this could be a libc/libm/Objective-C function we know
15349     // about.
15350   } else
15351     return;
15352 
15353   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15354     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15355     // target-specific builtins, perhaps?
15356     if (!FD->hasAttr<FormatAttr>())
15357       FD->addAttr(FormatAttr::CreateImplicit(Context,
15358                                              &Context.Idents.get("printf"), 2,
15359                                              Name->isStr("vasprintf") ? 0 : 3,
15360                                              FD->getLocation()));
15361   }
15362 
15363   if (Name->isStr("__CFStringMakeConstantString")) {
15364     // We already have a __builtin___CFStringMakeConstantString,
15365     // but builds that use -fno-constant-cfstrings don't go through that.
15366     if (!FD->hasAttr<FormatArgAttr>())
15367       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15368                                                 FD->getLocation()));
15369   }
15370 }
15371 
15372 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15373                                     TypeSourceInfo *TInfo) {
15374   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15375   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15376 
15377   if (!TInfo) {
15378     assert(D.isInvalidType() && "no declarator info for valid type");
15379     TInfo = Context.getTrivialTypeSourceInfo(T);
15380   }
15381 
15382   // Scope manipulation handled by caller.
15383   TypedefDecl *NewTD =
15384       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15385                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15386 
15387   // Bail out immediately if we have an invalid declaration.
15388   if (D.isInvalidType()) {
15389     NewTD->setInvalidDecl();
15390     return NewTD;
15391   }
15392 
15393   if (D.getDeclSpec().isModulePrivateSpecified()) {
15394     if (CurContext->isFunctionOrMethod())
15395       Diag(NewTD->getLocation(), diag::err_module_private_local)
15396           << 2 << NewTD
15397           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15398           << FixItHint::CreateRemoval(
15399                  D.getDeclSpec().getModulePrivateSpecLoc());
15400     else
15401       NewTD->setModulePrivate();
15402   }
15403 
15404   // C++ [dcl.typedef]p8:
15405   //   If the typedef declaration defines an unnamed class (or
15406   //   enum), the first typedef-name declared by the declaration
15407   //   to be that class type (or enum type) is used to denote the
15408   //   class type (or enum type) for linkage purposes only.
15409   // We need to check whether the type was declared in the declaration.
15410   switch (D.getDeclSpec().getTypeSpecType()) {
15411   case TST_enum:
15412   case TST_struct:
15413   case TST_interface:
15414   case TST_union:
15415   case TST_class: {
15416     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15417     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15418     break;
15419   }
15420 
15421   default:
15422     break;
15423   }
15424 
15425   return NewTD;
15426 }
15427 
15428 /// Check that this is a valid underlying type for an enum declaration.
15429 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15430   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15431   QualType T = TI->getType();
15432 
15433   if (T->isDependentType())
15434     return false;
15435 
15436   // This doesn't use 'isIntegralType' despite the error message mentioning
15437   // integral type because isIntegralType would also allow enum types in C.
15438   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15439     if (BT->isInteger())
15440       return false;
15441 
15442   if (T->isBitIntType())
15443     return false;
15444 
15445   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15446 }
15447 
15448 /// Check whether this is a valid redeclaration of a previous enumeration.
15449 /// \return true if the redeclaration was invalid.
15450 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15451                                   QualType EnumUnderlyingTy, bool IsFixed,
15452                                   const EnumDecl *Prev) {
15453   if (IsScoped != Prev->isScoped()) {
15454     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15455       << Prev->isScoped();
15456     Diag(Prev->getLocation(), diag::note_previous_declaration);
15457     return true;
15458   }
15459 
15460   if (IsFixed && Prev->isFixed()) {
15461     if (!EnumUnderlyingTy->isDependentType() &&
15462         !Prev->getIntegerType()->isDependentType() &&
15463         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15464                                         Prev->getIntegerType())) {
15465       // TODO: Highlight the underlying type of the redeclaration.
15466       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15467         << EnumUnderlyingTy << Prev->getIntegerType();
15468       Diag(Prev->getLocation(), diag::note_previous_declaration)
15469           << Prev->getIntegerTypeRange();
15470       return true;
15471     }
15472   } else if (IsFixed != Prev->isFixed()) {
15473     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15474       << Prev->isFixed();
15475     Diag(Prev->getLocation(), diag::note_previous_declaration);
15476     return true;
15477   }
15478 
15479   return false;
15480 }
15481 
15482 /// Get diagnostic %select index for tag kind for
15483 /// redeclaration diagnostic message.
15484 /// WARNING: Indexes apply to particular diagnostics only!
15485 ///
15486 /// \returns diagnostic %select index.
15487 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15488   switch (Tag) {
15489   case TTK_Struct: return 0;
15490   case TTK_Interface: return 1;
15491   case TTK_Class:  return 2;
15492   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15493   }
15494 }
15495 
15496 /// Determine if tag kind is a class-key compatible with
15497 /// class for redeclaration (class, struct, or __interface).
15498 ///
15499 /// \returns true iff the tag kind is compatible.
15500 static bool isClassCompatTagKind(TagTypeKind Tag)
15501 {
15502   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15503 }
15504 
15505 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15506                                              TagTypeKind TTK) {
15507   if (isa<TypedefDecl>(PrevDecl))
15508     return NTK_Typedef;
15509   else if (isa<TypeAliasDecl>(PrevDecl))
15510     return NTK_TypeAlias;
15511   else if (isa<ClassTemplateDecl>(PrevDecl))
15512     return NTK_Template;
15513   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15514     return NTK_TypeAliasTemplate;
15515   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15516     return NTK_TemplateTemplateArgument;
15517   switch (TTK) {
15518   case TTK_Struct:
15519   case TTK_Interface:
15520   case TTK_Class:
15521     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15522   case TTK_Union:
15523     return NTK_NonUnion;
15524   case TTK_Enum:
15525     return NTK_NonEnum;
15526   }
15527   llvm_unreachable("invalid TTK");
15528 }
15529 
15530 /// Determine whether a tag with a given kind is acceptable
15531 /// as a redeclaration of the given tag declaration.
15532 ///
15533 /// \returns true if the new tag kind is acceptable, false otherwise.
15534 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15535                                         TagTypeKind NewTag, bool isDefinition,
15536                                         SourceLocation NewTagLoc,
15537                                         const IdentifierInfo *Name) {
15538   // C++ [dcl.type.elab]p3:
15539   //   The class-key or enum keyword present in the
15540   //   elaborated-type-specifier shall agree in kind with the
15541   //   declaration to which the name in the elaborated-type-specifier
15542   //   refers. This rule also applies to the form of
15543   //   elaborated-type-specifier that declares a class-name or
15544   //   friend class since it can be construed as referring to the
15545   //   definition of the class. Thus, in any
15546   //   elaborated-type-specifier, the enum keyword shall be used to
15547   //   refer to an enumeration (7.2), the union class-key shall be
15548   //   used to refer to a union (clause 9), and either the class or
15549   //   struct class-key shall be used to refer to a class (clause 9)
15550   //   declared using the class or struct class-key.
15551   TagTypeKind OldTag = Previous->getTagKind();
15552   if (OldTag != NewTag &&
15553       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15554     return false;
15555 
15556   // Tags are compatible, but we might still want to warn on mismatched tags.
15557   // Non-class tags can't be mismatched at this point.
15558   if (!isClassCompatTagKind(NewTag))
15559     return true;
15560 
15561   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15562   // by our warning analysis. We don't want to warn about mismatches with (eg)
15563   // declarations in system headers that are designed to be specialized, but if
15564   // a user asks us to warn, we should warn if their code contains mismatched
15565   // declarations.
15566   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15567     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15568                                       Loc);
15569   };
15570   if (IsIgnoredLoc(NewTagLoc))
15571     return true;
15572 
15573   auto IsIgnored = [&](const TagDecl *Tag) {
15574     return IsIgnoredLoc(Tag->getLocation());
15575   };
15576   while (IsIgnored(Previous)) {
15577     Previous = Previous->getPreviousDecl();
15578     if (!Previous)
15579       return true;
15580     OldTag = Previous->getTagKind();
15581   }
15582 
15583   bool isTemplate = false;
15584   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15585     isTemplate = Record->getDescribedClassTemplate();
15586 
15587   if (inTemplateInstantiation()) {
15588     if (OldTag != NewTag) {
15589       // In a template instantiation, do not offer fix-its for tag mismatches
15590       // since they usually mess up the template instead of fixing the problem.
15591       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15592         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15593         << getRedeclDiagFromTagKind(OldTag);
15594       // FIXME: Note previous location?
15595     }
15596     return true;
15597   }
15598 
15599   if (isDefinition) {
15600     // On definitions, check all previous tags and issue a fix-it for each
15601     // one that doesn't match the current tag.
15602     if (Previous->getDefinition()) {
15603       // Don't suggest fix-its for redefinitions.
15604       return true;
15605     }
15606 
15607     bool previousMismatch = false;
15608     for (const TagDecl *I : Previous->redecls()) {
15609       if (I->getTagKind() != NewTag) {
15610         // Ignore previous declarations for which the warning was disabled.
15611         if (IsIgnored(I))
15612           continue;
15613 
15614         if (!previousMismatch) {
15615           previousMismatch = true;
15616           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15617             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15618             << getRedeclDiagFromTagKind(I->getTagKind());
15619         }
15620         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15621           << getRedeclDiagFromTagKind(NewTag)
15622           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15623                TypeWithKeyword::getTagTypeKindName(NewTag));
15624       }
15625     }
15626     return true;
15627   }
15628 
15629   // Identify the prevailing tag kind: this is the kind of the definition (if
15630   // there is a non-ignored definition), or otherwise the kind of the prior
15631   // (non-ignored) declaration.
15632   const TagDecl *PrevDef = Previous->getDefinition();
15633   if (PrevDef && IsIgnored(PrevDef))
15634     PrevDef = nullptr;
15635   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15636   if (Redecl->getTagKind() != NewTag) {
15637     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15638       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15639       << getRedeclDiagFromTagKind(OldTag);
15640     Diag(Redecl->getLocation(), diag::note_previous_use);
15641 
15642     // If there is a previous definition, suggest a fix-it.
15643     if (PrevDef) {
15644       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15645         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15646         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15647              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15648     }
15649   }
15650 
15651   return true;
15652 }
15653 
15654 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15655 /// from an outer enclosing namespace or file scope inside a friend declaration.
15656 /// This should provide the commented out code in the following snippet:
15657 ///   namespace N {
15658 ///     struct X;
15659 ///     namespace M {
15660 ///       struct Y { friend struct /*N::*/ X; };
15661 ///     }
15662 ///   }
15663 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15664                                          SourceLocation NameLoc) {
15665   // While the decl is in a namespace, do repeated lookup of that name and see
15666   // if we get the same namespace back.  If we do not, continue until
15667   // translation unit scope, at which point we have a fully qualified NNS.
15668   SmallVector<IdentifierInfo *, 4> Namespaces;
15669   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15670   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15671     // This tag should be declared in a namespace, which can only be enclosed by
15672     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15673     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15674     if (!Namespace || Namespace->isAnonymousNamespace())
15675       return FixItHint();
15676     IdentifierInfo *II = Namespace->getIdentifier();
15677     Namespaces.push_back(II);
15678     NamedDecl *Lookup = SemaRef.LookupSingleName(
15679         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15680     if (Lookup == Namespace)
15681       break;
15682   }
15683 
15684   // Once we have all the namespaces, reverse them to go outermost first, and
15685   // build an NNS.
15686   SmallString<64> Insertion;
15687   llvm::raw_svector_ostream OS(Insertion);
15688   if (DC->isTranslationUnit())
15689     OS << "::";
15690   std::reverse(Namespaces.begin(), Namespaces.end());
15691   for (auto *II : Namespaces)
15692     OS << II->getName() << "::";
15693   return FixItHint::CreateInsertion(NameLoc, Insertion);
15694 }
15695 
15696 /// Determine whether a tag originally declared in context \p OldDC can
15697 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15698 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15699 /// using-declaration).
15700 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15701                                          DeclContext *NewDC) {
15702   OldDC = OldDC->getRedeclContext();
15703   NewDC = NewDC->getRedeclContext();
15704 
15705   if (OldDC->Equals(NewDC))
15706     return true;
15707 
15708   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15709   // encloses the other).
15710   if (S.getLangOpts().MSVCCompat &&
15711       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15712     return true;
15713 
15714   return false;
15715 }
15716 
15717 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15718 /// former case, Name will be non-null.  In the later case, Name will be null.
15719 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15720 /// reference/declaration/definition of a tag.
15721 ///
15722 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15723 /// trailing-type-specifier) other than one in an alias-declaration.
15724 ///
15725 /// \param SkipBody If non-null, will be set to indicate if the caller should
15726 /// skip the definition of this tag and treat it as if it were a declaration.
15727 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15728                      SourceLocation KWLoc, CXXScopeSpec &SS,
15729                      IdentifierInfo *Name, SourceLocation NameLoc,
15730                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15731                      SourceLocation ModulePrivateLoc,
15732                      MultiTemplateParamsArg TemplateParameterLists,
15733                      bool &OwnedDecl, bool &IsDependent,
15734                      SourceLocation ScopedEnumKWLoc,
15735                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15736                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15737                      SkipBodyInfo *SkipBody) {
15738   // If this is not a definition, it must have a name.
15739   IdentifierInfo *OrigName = Name;
15740   assert((Name != nullptr || TUK == TUK_Definition) &&
15741          "Nameless record must be a definition!");
15742   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15743 
15744   OwnedDecl = false;
15745   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15746   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15747 
15748   // FIXME: Check member specializations more carefully.
15749   bool isMemberSpecialization = false;
15750   bool Invalid = false;
15751 
15752   // We only need to do this matching if we have template parameters
15753   // or a scope specifier, which also conveniently avoids this work
15754   // for non-C++ cases.
15755   if (TemplateParameterLists.size() > 0 ||
15756       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15757     if (TemplateParameterList *TemplateParams =
15758             MatchTemplateParametersToScopeSpecifier(
15759                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15760                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15761       if (Kind == TTK_Enum) {
15762         Diag(KWLoc, diag::err_enum_template);
15763         return nullptr;
15764       }
15765 
15766       if (TemplateParams->size() > 0) {
15767         // This is a declaration or definition of a class template (which may
15768         // be a member of another template).
15769 
15770         if (Invalid)
15771           return nullptr;
15772 
15773         OwnedDecl = false;
15774         DeclResult Result = CheckClassTemplate(
15775             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15776             AS, ModulePrivateLoc,
15777             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15778             TemplateParameterLists.data(), SkipBody);
15779         return Result.get();
15780       } else {
15781         // The "template<>" header is extraneous.
15782         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15783           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15784         isMemberSpecialization = true;
15785       }
15786     }
15787 
15788     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15789         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15790       return nullptr;
15791   }
15792 
15793   // Figure out the underlying type if this a enum declaration. We need to do
15794   // this early, because it's needed to detect if this is an incompatible
15795   // redeclaration.
15796   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15797   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15798 
15799   if (Kind == TTK_Enum) {
15800     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15801       // No underlying type explicitly specified, or we failed to parse the
15802       // type, default to int.
15803       EnumUnderlying = Context.IntTy.getTypePtr();
15804     } else if (UnderlyingType.get()) {
15805       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15806       // integral type; any cv-qualification is ignored.
15807       TypeSourceInfo *TI = nullptr;
15808       GetTypeFromParser(UnderlyingType.get(), &TI);
15809       EnumUnderlying = TI;
15810 
15811       if (CheckEnumUnderlyingType(TI))
15812         // Recover by falling back to int.
15813         EnumUnderlying = Context.IntTy.getTypePtr();
15814 
15815       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15816                                           UPPC_FixedUnderlyingType))
15817         EnumUnderlying = Context.IntTy.getTypePtr();
15818 
15819     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15820       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15821       // of 'int'. However, if this is an unfixed forward declaration, don't set
15822       // the underlying type unless the user enables -fms-compatibility. This
15823       // makes unfixed forward declared enums incomplete and is more conforming.
15824       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15825         EnumUnderlying = Context.IntTy.getTypePtr();
15826     }
15827   }
15828 
15829   DeclContext *SearchDC = CurContext;
15830   DeclContext *DC = CurContext;
15831   bool isStdBadAlloc = false;
15832   bool isStdAlignValT = false;
15833 
15834   RedeclarationKind Redecl = forRedeclarationInCurContext();
15835   if (TUK == TUK_Friend || TUK == TUK_Reference)
15836     Redecl = NotForRedeclaration;
15837 
15838   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15839   /// implemented asks for structural equivalence checking, the returned decl
15840   /// here is passed back to the parser, allowing the tag body to be parsed.
15841   auto createTagFromNewDecl = [&]() -> TagDecl * {
15842     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15843     // If there is an identifier, use the location of the identifier as the
15844     // location of the decl, otherwise use the location of the struct/union
15845     // keyword.
15846     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15847     TagDecl *New = nullptr;
15848 
15849     if (Kind == TTK_Enum) {
15850       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15851                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15852       // If this is an undefined enum, bail.
15853       if (TUK != TUK_Definition && !Invalid)
15854         return nullptr;
15855       if (EnumUnderlying) {
15856         EnumDecl *ED = cast<EnumDecl>(New);
15857         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15858           ED->setIntegerTypeSourceInfo(TI);
15859         else
15860           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15861         ED->setPromotionType(ED->getIntegerType());
15862       }
15863     } else { // struct/union
15864       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15865                                nullptr);
15866     }
15867 
15868     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15869       // Add alignment attributes if necessary; these attributes are checked
15870       // when the ASTContext lays out the structure.
15871       //
15872       // It is important for implementing the correct semantics that this
15873       // happen here (in ActOnTag). The #pragma pack stack is
15874       // maintained as a result of parser callbacks which can occur at
15875       // many points during the parsing of a struct declaration (because
15876       // the #pragma tokens are effectively skipped over during the
15877       // parsing of the struct).
15878       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15879         AddAlignmentAttributesForRecord(RD);
15880         AddMsStructLayoutForRecord(RD);
15881       }
15882     }
15883     New->setLexicalDeclContext(CurContext);
15884     return New;
15885   };
15886 
15887   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15888   if (Name && SS.isNotEmpty()) {
15889     // We have a nested-name tag ('struct foo::bar').
15890 
15891     // Check for invalid 'foo::'.
15892     if (SS.isInvalid()) {
15893       Name = nullptr;
15894       goto CreateNewDecl;
15895     }
15896 
15897     // If this is a friend or a reference to a class in a dependent
15898     // context, don't try to make a decl for it.
15899     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15900       DC = computeDeclContext(SS, false);
15901       if (!DC) {
15902         IsDependent = true;
15903         return nullptr;
15904       }
15905     } else {
15906       DC = computeDeclContext(SS, true);
15907       if (!DC) {
15908         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15909           << SS.getRange();
15910         return nullptr;
15911       }
15912     }
15913 
15914     if (RequireCompleteDeclContext(SS, DC))
15915       return nullptr;
15916 
15917     SearchDC = DC;
15918     // Look-up name inside 'foo::'.
15919     LookupQualifiedName(Previous, DC);
15920 
15921     if (Previous.isAmbiguous())
15922       return nullptr;
15923 
15924     if (Previous.empty()) {
15925       // Name lookup did not find anything. However, if the
15926       // nested-name-specifier refers to the current instantiation,
15927       // and that current instantiation has any dependent base
15928       // classes, we might find something at instantiation time: treat
15929       // this as a dependent elaborated-type-specifier.
15930       // But this only makes any sense for reference-like lookups.
15931       if (Previous.wasNotFoundInCurrentInstantiation() &&
15932           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15933         IsDependent = true;
15934         return nullptr;
15935       }
15936 
15937       // A tag 'foo::bar' must already exist.
15938       Diag(NameLoc, diag::err_not_tag_in_scope)
15939         << Kind << Name << DC << SS.getRange();
15940       Name = nullptr;
15941       Invalid = true;
15942       goto CreateNewDecl;
15943     }
15944   } else if (Name) {
15945     // C++14 [class.mem]p14:
15946     //   If T is the name of a class, then each of the following shall have a
15947     //   name different from T:
15948     //    -- every member of class T that is itself a type
15949     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15950         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15951       return nullptr;
15952 
15953     // If this is a named struct, check to see if there was a previous forward
15954     // declaration or definition.
15955     // FIXME: We're looking into outer scopes here, even when we
15956     // shouldn't be. Doing so can result in ambiguities that we
15957     // shouldn't be diagnosing.
15958     LookupName(Previous, S);
15959 
15960     // When declaring or defining a tag, ignore ambiguities introduced
15961     // by types using'ed into this scope.
15962     if (Previous.isAmbiguous() &&
15963         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15964       LookupResult::Filter F = Previous.makeFilter();
15965       while (F.hasNext()) {
15966         NamedDecl *ND = F.next();
15967         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15968                 SearchDC->getRedeclContext()))
15969           F.erase();
15970       }
15971       F.done();
15972     }
15973 
15974     // C++11 [namespace.memdef]p3:
15975     //   If the name in a friend declaration is neither qualified nor
15976     //   a template-id and the declaration is a function or an
15977     //   elaborated-type-specifier, the lookup to determine whether
15978     //   the entity has been previously declared shall not consider
15979     //   any scopes outside the innermost enclosing namespace.
15980     //
15981     // MSVC doesn't implement the above rule for types, so a friend tag
15982     // declaration may be a redeclaration of a type declared in an enclosing
15983     // scope.  They do implement this rule for friend functions.
15984     //
15985     // Does it matter that this should be by scope instead of by
15986     // semantic context?
15987     if (!Previous.empty() && TUK == TUK_Friend) {
15988       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15989       LookupResult::Filter F = Previous.makeFilter();
15990       bool FriendSawTagOutsideEnclosingNamespace = false;
15991       while (F.hasNext()) {
15992         NamedDecl *ND = F.next();
15993         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15994         if (DC->isFileContext() &&
15995             !EnclosingNS->Encloses(ND->getDeclContext())) {
15996           if (getLangOpts().MSVCCompat)
15997             FriendSawTagOutsideEnclosingNamespace = true;
15998           else
15999             F.erase();
16000         }
16001       }
16002       F.done();
16003 
16004       // Diagnose this MSVC extension in the easy case where lookup would have
16005       // unambiguously found something outside the enclosing namespace.
16006       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16007         NamedDecl *ND = Previous.getFoundDecl();
16008         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16009             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16010       }
16011     }
16012 
16013     // Note:  there used to be some attempt at recovery here.
16014     if (Previous.isAmbiguous())
16015       return nullptr;
16016 
16017     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16018       // FIXME: This makes sure that we ignore the contexts associated
16019       // with C structs, unions, and enums when looking for a matching
16020       // tag declaration or definition. See the similar lookup tweak
16021       // in Sema::LookupName; is there a better way to deal with this?
16022       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
16023         SearchDC = SearchDC->getParent();
16024     }
16025   }
16026 
16027   if (Previous.isSingleResult() &&
16028       Previous.getFoundDecl()->isTemplateParameter()) {
16029     // Maybe we will complain about the shadowed template parameter.
16030     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16031     // Just pretend that we didn't see the previous declaration.
16032     Previous.clear();
16033   }
16034 
16035   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16036       DC->Equals(getStdNamespace())) {
16037     if (Name->isStr("bad_alloc")) {
16038       // This is a declaration of or a reference to "std::bad_alloc".
16039       isStdBadAlloc = true;
16040 
16041       // If std::bad_alloc has been implicitly declared (but made invisible to
16042       // name lookup), fill in this implicit declaration as the previous
16043       // declaration, so that the declarations get chained appropriately.
16044       if (Previous.empty() && StdBadAlloc)
16045         Previous.addDecl(getStdBadAlloc());
16046     } else if (Name->isStr("align_val_t")) {
16047       isStdAlignValT = true;
16048       if (Previous.empty() && StdAlignValT)
16049         Previous.addDecl(getStdAlignValT());
16050     }
16051   }
16052 
16053   // If we didn't find a previous declaration, and this is a reference
16054   // (or friend reference), move to the correct scope.  In C++, we
16055   // also need to do a redeclaration lookup there, just in case
16056   // there's a shadow friend decl.
16057   if (Name && Previous.empty() &&
16058       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16059     if (Invalid) goto CreateNewDecl;
16060     assert(SS.isEmpty());
16061 
16062     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16063       // C++ [basic.scope.pdecl]p5:
16064       //   -- for an elaborated-type-specifier of the form
16065       //
16066       //          class-key identifier
16067       //
16068       //      if the elaborated-type-specifier is used in the
16069       //      decl-specifier-seq or parameter-declaration-clause of a
16070       //      function defined in namespace scope, the identifier is
16071       //      declared as a class-name in the namespace that contains
16072       //      the declaration; otherwise, except as a friend
16073       //      declaration, the identifier is declared in the smallest
16074       //      non-class, non-function-prototype scope that contains the
16075       //      declaration.
16076       //
16077       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16078       // C structs and unions.
16079       //
16080       // It is an error in C++ to declare (rather than define) an enum
16081       // type, including via an elaborated type specifier.  We'll
16082       // diagnose that later; for now, declare the enum in the same
16083       // scope as we would have picked for any other tag type.
16084       //
16085       // GNU C also supports this behavior as part of its incomplete
16086       // enum types extension, while GNU C++ does not.
16087       //
16088       // Find the context where we'll be declaring the tag.
16089       // FIXME: We would like to maintain the current DeclContext as the
16090       // lexical context,
16091       SearchDC = getTagInjectionContext(SearchDC);
16092 
16093       // Find the scope where we'll be declaring the tag.
16094       S = getTagInjectionScope(S, getLangOpts());
16095     } else {
16096       assert(TUK == TUK_Friend);
16097       // C++ [namespace.memdef]p3:
16098       //   If a friend declaration in a non-local class first declares a
16099       //   class or function, the friend class or function is a member of
16100       //   the innermost enclosing namespace.
16101       SearchDC = SearchDC->getEnclosingNamespaceContext();
16102     }
16103 
16104     // In C++, we need to do a redeclaration lookup to properly
16105     // diagnose some problems.
16106     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16107     // hidden declaration so that we don't get ambiguity errors when using a
16108     // type declared by an elaborated-type-specifier.  In C that is not correct
16109     // and we should instead merge compatible types found by lookup.
16110     if (getLangOpts().CPlusPlus) {
16111       // FIXME: This can perform qualified lookups into function contexts,
16112       // which are meaningless.
16113       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16114       LookupQualifiedName(Previous, SearchDC);
16115     } else {
16116       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16117       LookupName(Previous, S);
16118     }
16119   }
16120 
16121   // If we have a known previous declaration to use, then use it.
16122   if (Previous.empty() && SkipBody && SkipBody->Previous)
16123     Previous.addDecl(SkipBody->Previous);
16124 
16125   if (!Previous.empty()) {
16126     NamedDecl *PrevDecl = Previous.getFoundDecl();
16127     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16128 
16129     // It's okay to have a tag decl in the same scope as a typedef
16130     // which hides a tag decl in the same scope.  Finding this
16131     // with a redeclaration lookup can only actually happen in C++.
16132     //
16133     // This is also okay for elaborated-type-specifiers, which is
16134     // technically forbidden by the current standard but which is
16135     // okay according to the likely resolution of an open issue;
16136     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16137     if (getLangOpts().CPlusPlus) {
16138       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16139         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16140           TagDecl *Tag = TT->getDecl();
16141           if (Tag->getDeclName() == Name &&
16142               Tag->getDeclContext()->getRedeclContext()
16143                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16144             PrevDecl = Tag;
16145             Previous.clear();
16146             Previous.addDecl(Tag);
16147             Previous.resolveKind();
16148           }
16149         }
16150       }
16151     }
16152 
16153     // If this is a redeclaration of a using shadow declaration, it must
16154     // declare a tag in the same context. In MSVC mode, we allow a
16155     // redefinition if either context is within the other.
16156     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16157       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16158       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16159           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16160           !(OldTag && isAcceptableTagRedeclContext(
16161                           *this, OldTag->getDeclContext(), SearchDC))) {
16162         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16163         Diag(Shadow->getTargetDecl()->getLocation(),
16164              diag::note_using_decl_target);
16165         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16166             << 0;
16167         // Recover by ignoring the old declaration.
16168         Previous.clear();
16169         goto CreateNewDecl;
16170       }
16171     }
16172 
16173     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16174       // If this is a use of a previous tag, or if the tag is already declared
16175       // in the same scope (so that the definition/declaration completes or
16176       // rementions the tag), reuse the decl.
16177       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16178           isDeclInScope(DirectPrevDecl, SearchDC, S,
16179                         SS.isNotEmpty() || isMemberSpecialization)) {
16180         // Make sure that this wasn't declared as an enum and now used as a
16181         // struct or something similar.
16182         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16183                                           TUK == TUK_Definition, KWLoc,
16184                                           Name)) {
16185           bool SafeToContinue
16186             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16187                Kind != TTK_Enum);
16188           if (SafeToContinue)
16189             Diag(KWLoc, diag::err_use_with_wrong_tag)
16190               << Name
16191               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16192                                               PrevTagDecl->getKindName());
16193           else
16194             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16195           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16196 
16197           if (SafeToContinue)
16198             Kind = PrevTagDecl->getTagKind();
16199           else {
16200             // Recover by making this an anonymous redefinition.
16201             Name = nullptr;
16202             Previous.clear();
16203             Invalid = true;
16204           }
16205         }
16206 
16207         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16208           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16209           if (TUK == TUK_Reference || TUK == TUK_Friend)
16210             return PrevTagDecl;
16211 
16212           QualType EnumUnderlyingTy;
16213           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16214             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16215           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16216             EnumUnderlyingTy = QualType(T, 0);
16217 
16218           // All conflicts with previous declarations are recovered by
16219           // returning the previous declaration, unless this is a definition,
16220           // in which case we want the caller to bail out.
16221           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16222                                      ScopedEnum, EnumUnderlyingTy,
16223                                      IsFixed, PrevEnum))
16224             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16225         }
16226 
16227         // C++11 [class.mem]p1:
16228         //   A member shall not be declared twice in the member-specification,
16229         //   except that a nested class or member class template can be declared
16230         //   and then later defined.
16231         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16232             S->isDeclScope(PrevDecl)) {
16233           Diag(NameLoc, diag::ext_member_redeclared);
16234           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16235         }
16236 
16237         if (!Invalid) {
16238           // If this is a use, just return the declaration we found, unless
16239           // we have attributes.
16240           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16241             if (!Attrs.empty()) {
16242               // FIXME: Diagnose these attributes. For now, we create a new
16243               // declaration to hold them.
16244             } else if (TUK == TUK_Reference &&
16245                        (PrevTagDecl->getFriendObjectKind() ==
16246                             Decl::FOK_Undeclared ||
16247                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16248                        SS.isEmpty()) {
16249               // This declaration is a reference to an existing entity, but
16250               // has different visibility from that entity: it either makes
16251               // a friend visible or it makes a type visible in a new module.
16252               // In either case, create a new declaration. We only do this if
16253               // the declaration would have meant the same thing if no prior
16254               // declaration were found, that is, if it was found in the same
16255               // scope where we would have injected a declaration.
16256               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16257                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16258                 return PrevTagDecl;
16259               // This is in the injected scope, create a new declaration in
16260               // that scope.
16261               S = getTagInjectionScope(S, getLangOpts());
16262             } else {
16263               return PrevTagDecl;
16264             }
16265           }
16266 
16267           // Diagnose attempts to redefine a tag.
16268           if (TUK == TUK_Definition) {
16269             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16270               // If we're defining a specialization and the previous definition
16271               // is from an implicit instantiation, don't emit an error
16272               // here; we'll catch this in the general case below.
16273               bool IsExplicitSpecializationAfterInstantiation = false;
16274               if (isMemberSpecialization) {
16275                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16276                   IsExplicitSpecializationAfterInstantiation =
16277                     RD->getTemplateSpecializationKind() !=
16278                     TSK_ExplicitSpecialization;
16279                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16280                   IsExplicitSpecializationAfterInstantiation =
16281                     ED->getTemplateSpecializationKind() !=
16282                     TSK_ExplicitSpecialization;
16283               }
16284 
16285               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16286               // not keep more that one definition around (merge them). However,
16287               // ensure the decl passes the structural compatibility check in
16288               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16289               NamedDecl *Hidden = nullptr;
16290               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16291                 // There is a definition of this tag, but it is not visible. We
16292                 // explicitly make use of C++'s one definition rule here, and
16293                 // assume that this definition is identical to the hidden one
16294                 // we already have. Make the existing definition visible and
16295                 // use it in place of this one.
16296                 if (!getLangOpts().CPlusPlus) {
16297                   // Postpone making the old definition visible until after we
16298                   // complete parsing the new one and do the structural
16299                   // comparison.
16300                   SkipBody->CheckSameAsPrevious = true;
16301                   SkipBody->New = createTagFromNewDecl();
16302                   SkipBody->Previous = Def;
16303                   return Def;
16304                 } else {
16305                   SkipBody->ShouldSkip = true;
16306                   SkipBody->Previous = Def;
16307                   makeMergedDefinitionVisible(Hidden);
16308                   // Carry on and handle it like a normal definition. We'll
16309                   // skip starting the definitiion later.
16310                 }
16311               } else if (!IsExplicitSpecializationAfterInstantiation) {
16312                 // A redeclaration in function prototype scope in C isn't
16313                 // visible elsewhere, so merely issue a warning.
16314                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16315                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16316                 else
16317                   Diag(NameLoc, diag::err_redefinition) << Name;
16318                 notePreviousDefinition(Def,
16319                                        NameLoc.isValid() ? NameLoc : KWLoc);
16320                 // If this is a redefinition, recover by making this
16321                 // struct be anonymous, which will make any later
16322                 // references get the previous definition.
16323                 Name = nullptr;
16324                 Previous.clear();
16325                 Invalid = true;
16326               }
16327             } else {
16328               // If the type is currently being defined, complain
16329               // about a nested redefinition.
16330               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16331               if (TD->isBeingDefined()) {
16332                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16333                 Diag(PrevTagDecl->getLocation(),
16334                      diag::note_previous_definition);
16335                 Name = nullptr;
16336                 Previous.clear();
16337                 Invalid = true;
16338               }
16339             }
16340 
16341             // Okay, this is definition of a previously declared or referenced
16342             // tag. We're going to create a new Decl for it.
16343           }
16344 
16345           // Okay, we're going to make a redeclaration.  If this is some kind
16346           // of reference, make sure we build the redeclaration in the same DC
16347           // as the original, and ignore the current access specifier.
16348           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16349             SearchDC = PrevTagDecl->getDeclContext();
16350             AS = AS_none;
16351           }
16352         }
16353         // If we get here we have (another) forward declaration or we
16354         // have a definition.  Just create a new decl.
16355 
16356       } else {
16357         // If we get here, this is a definition of a new tag type in a nested
16358         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16359         // new decl/type.  We set PrevDecl to NULL so that the entities
16360         // have distinct types.
16361         Previous.clear();
16362       }
16363       // If we get here, we're going to create a new Decl. If PrevDecl
16364       // is non-NULL, it's a definition of the tag declared by
16365       // PrevDecl. If it's NULL, we have a new definition.
16366 
16367     // Otherwise, PrevDecl is not a tag, but was found with tag
16368     // lookup.  This is only actually possible in C++, where a few
16369     // things like templates still live in the tag namespace.
16370     } else {
16371       // Use a better diagnostic if an elaborated-type-specifier
16372       // found the wrong kind of type on the first
16373       // (non-redeclaration) lookup.
16374       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16375           !Previous.isForRedeclaration()) {
16376         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16377         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16378                                                        << Kind;
16379         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16380         Invalid = true;
16381 
16382       // Otherwise, only diagnose if the declaration is in scope.
16383       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16384                                 SS.isNotEmpty() || isMemberSpecialization)) {
16385         // do nothing
16386 
16387       // Diagnose implicit declarations introduced by elaborated types.
16388       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16389         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16390         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16391         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16392         Invalid = true;
16393 
16394       // Otherwise it's a declaration.  Call out a particularly common
16395       // case here.
16396       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16397         unsigned Kind = 0;
16398         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16399         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16400           << Name << Kind << TND->getUnderlyingType();
16401         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16402         Invalid = true;
16403 
16404       // Otherwise, diagnose.
16405       } else {
16406         // The tag name clashes with something else in the target scope,
16407         // issue an error and recover by making this tag be anonymous.
16408         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16409         notePreviousDefinition(PrevDecl, NameLoc);
16410         Name = nullptr;
16411         Invalid = true;
16412       }
16413 
16414       // The existing declaration isn't relevant to us; we're in a
16415       // new scope, so clear out the previous declaration.
16416       Previous.clear();
16417     }
16418   }
16419 
16420 CreateNewDecl:
16421 
16422   TagDecl *PrevDecl = nullptr;
16423   if (Previous.isSingleResult())
16424     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16425 
16426   // If there is an identifier, use the location of the identifier as the
16427   // location of the decl, otherwise use the location of the struct/union
16428   // keyword.
16429   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16430 
16431   // Otherwise, create a new declaration. If there is a previous
16432   // declaration of the same entity, the two will be linked via
16433   // PrevDecl.
16434   TagDecl *New;
16435 
16436   if (Kind == TTK_Enum) {
16437     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16438     // enum X { A, B, C } D;    D should chain to X.
16439     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16440                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16441                            ScopedEnumUsesClassTag, IsFixed);
16442 
16443     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16444       StdAlignValT = cast<EnumDecl>(New);
16445 
16446     // If this is an undefined enum, warn.
16447     if (TUK != TUK_Definition && !Invalid) {
16448       TagDecl *Def;
16449       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16450         // C++0x: 7.2p2: opaque-enum-declaration.
16451         // Conflicts are diagnosed above. Do nothing.
16452       }
16453       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16454         Diag(Loc, diag::ext_forward_ref_enum_def)
16455           << New;
16456         Diag(Def->getLocation(), diag::note_previous_definition);
16457       } else {
16458         unsigned DiagID = diag::ext_forward_ref_enum;
16459         if (getLangOpts().MSVCCompat)
16460           DiagID = diag::ext_ms_forward_ref_enum;
16461         else if (getLangOpts().CPlusPlus)
16462           DiagID = diag::err_forward_ref_enum;
16463         Diag(Loc, DiagID);
16464       }
16465     }
16466 
16467     if (EnumUnderlying) {
16468       EnumDecl *ED = cast<EnumDecl>(New);
16469       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16470         ED->setIntegerTypeSourceInfo(TI);
16471       else
16472         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16473       ED->setPromotionType(ED->getIntegerType());
16474       assert(ED->isComplete() && "enum with type should be complete");
16475     }
16476   } else {
16477     // struct/union/class
16478 
16479     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16480     // struct X { int A; } D;    D should chain to X.
16481     if (getLangOpts().CPlusPlus) {
16482       // FIXME: Look for a way to use RecordDecl for simple structs.
16483       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16484                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16485 
16486       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16487         StdBadAlloc = cast<CXXRecordDecl>(New);
16488     } else
16489       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16490                                cast_or_null<RecordDecl>(PrevDecl));
16491   }
16492 
16493   // C++11 [dcl.type]p3:
16494   //   A type-specifier-seq shall not define a class or enumeration [...].
16495   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16496       TUK == TUK_Definition) {
16497     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16498       << Context.getTagDeclType(New);
16499     Invalid = true;
16500   }
16501 
16502   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16503       DC->getDeclKind() == Decl::Enum) {
16504     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16505       << Context.getTagDeclType(New);
16506     Invalid = true;
16507   }
16508 
16509   // Maybe add qualifier info.
16510   if (SS.isNotEmpty()) {
16511     if (SS.isSet()) {
16512       // If this is either a declaration or a definition, check the
16513       // nested-name-specifier against the current context.
16514       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16515           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16516                                        isMemberSpecialization))
16517         Invalid = true;
16518 
16519       New->setQualifierInfo(SS.getWithLocInContext(Context));
16520       if (TemplateParameterLists.size() > 0) {
16521         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16522       }
16523     }
16524     else
16525       Invalid = true;
16526   }
16527 
16528   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16529     // Add alignment attributes if necessary; these attributes are checked when
16530     // the ASTContext lays out the structure.
16531     //
16532     // It is important for implementing the correct semantics that this
16533     // happen here (in ActOnTag). The #pragma pack stack is
16534     // maintained as a result of parser callbacks which can occur at
16535     // many points during the parsing of a struct declaration (because
16536     // the #pragma tokens are effectively skipped over during the
16537     // parsing of the struct).
16538     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16539       AddAlignmentAttributesForRecord(RD);
16540       AddMsStructLayoutForRecord(RD);
16541     }
16542   }
16543 
16544   if (ModulePrivateLoc.isValid()) {
16545     if (isMemberSpecialization)
16546       Diag(New->getLocation(), diag::err_module_private_specialization)
16547         << 2
16548         << FixItHint::CreateRemoval(ModulePrivateLoc);
16549     // __module_private__ does not apply to local classes. However, we only
16550     // diagnose this as an error when the declaration specifiers are
16551     // freestanding. Here, we just ignore the __module_private__.
16552     else if (!SearchDC->isFunctionOrMethod())
16553       New->setModulePrivate();
16554   }
16555 
16556   // If this is a specialization of a member class (of a class template),
16557   // check the specialization.
16558   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16559     Invalid = true;
16560 
16561   // If we're declaring or defining a tag in function prototype scope in C,
16562   // note that this type can only be used within the function and add it to
16563   // the list of decls to inject into the function definition scope.
16564   if ((Name || Kind == TTK_Enum) &&
16565       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16566     if (getLangOpts().CPlusPlus) {
16567       // C++ [dcl.fct]p6:
16568       //   Types shall not be defined in return or parameter types.
16569       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16570         Diag(Loc, diag::err_type_defined_in_param_type)
16571             << Name;
16572         Invalid = true;
16573       }
16574     } else if (!PrevDecl) {
16575       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16576     }
16577   }
16578 
16579   if (Invalid)
16580     New->setInvalidDecl();
16581 
16582   // Set the lexical context. If the tag has a C++ scope specifier, the
16583   // lexical context will be different from the semantic context.
16584   New->setLexicalDeclContext(CurContext);
16585 
16586   // Mark this as a friend decl if applicable.
16587   // In Microsoft mode, a friend declaration also acts as a forward
16588   // declaration so we always pass true to setObjectOfFriendDecl to make
16589   // the tag name visible.
16590   if (TUK == TUK_Friend)
16591     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16592 
16593   // Set the access specifier.
16594   if (!Invalid && SearchDC->isRecord())
16595     SetMemberAccessSpecifier(New, PrevDecl, AS);
16596 
16597   if (PrevDecl)
16598     CheckRedeclarationInModule(New, PrevDecl);
16599 
16600   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16601     New->startDefinition();
16602 
16603   ProcessDeclAttributeList(S, New, Attrs);
16604   AddPragmaAttributes(S, New);
16605 
16606   // If this has an identifier, add it to the scope stack.
16607   if (TUK == TUK_Friend) {
16608     // We might be replacing an existing declaration in the lookup tables;
16609     // if so, borrow its access specifier.
16610     if (PrevDecl)
16611       New->setAccess(PrevDecl->getAccess());
16612 
16613     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16614     DC->makeDeclVisibleInContext(New);
16615     if (Name) // can be null along some error paths
16616       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16617         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16618   } else if (Name) {
16619     S = getNonFieldDeclScope(S);
16620     PushOnScopeChains(New, S, true);
16621   } else {
16622     CurContext->addDecl(New);
16623   }
16624 
16625   // If this is the C FILE type, notify the AST context.
16626   if (IdentifierInfo *II = New->getIdentifier())
16627     if (!New->isInvalidDecl() &&
16628         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16629         II->isStr("FILE"))
16630       Context.setFILEDecl(New);
16631 
16632   if (PrevDecl)
16633     mergeDeclAttributes(New, PrevDecl);
16634 
16635   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16636     inferGslOwnerPointerAttribute(CXXRD);
16637 
16638   // If there's a #pragma GCC visibility in scope, set the visibility of this
16639   // record.
16640   AddPushedVisibilityAttribute(New);
16641 
16642   if (isMemberSpecialization && !New->isInvalidDecl())
16643     CompleteMemberSpecialization(New, Previous);
16644 
16645   OwnedDecl = true;
16646   // In C++, don't return an invalid declaration. We can't recover well from
16647   // the cases where we make the type anonymous.
16648   if (Invalid && getLangOpts().CPlusPlus) {
16649     if (New->isBeingDefined())
16650       if (auto RD = dyn_cast<RecordDecl>(New))
16651         RD->completeDefinition();
16652     return nullptr;
16653   } else if (SkipBody && SkipBody->ShouldSkip) {
16654     return SkipBody->Previous;
16655   } else {
16656     return New;
16657   }
16658 }
16659 
16660 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16661   AdjustDeclIfTemplate(TagD);
16662   TagDecl *Tag = cast<TagDecl>(TagD);
16663 
16664   // Enter the tag context.
16665   PushDeclContext(S, Tag);
16666 
16667   ActOnDocumentableDecl(TagD);
16668 
16669   // If there's a #pragma GCC visibility in scope, set the visibility of this
16670   // record.
16671   AddPushedVisibilityAttribute(Tag);
16672 }
16673 
16674 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16675                                     SkipBodyInfo &SkipBody) {
16676   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16677     return false;
16678 
16679   // Make the previous decl visible.
16680   makeMergedDefinitionVisible(SkipBody.Previous);
16681   return true;
16682 }
16683 
16684 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16685   assert(isa<ObjCContainerDecl>(IDecl) &&
16686          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16687   DeclContext *OCD = cast<DeclContext>(IDecl);
16688   assert(OCD->getLexicalParent() == CurContext &&
16689       "The next DeclContext should be lexically contained in the current one.");
16690   CurContext = OCD;
16691   return IDecl;
16692 }
16693 
16694 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16695                                            SourceLocation FinalLoc,
16696                                            bool IsFinalSpelledSealed,
16697                                            bool IsAbstract,
16698                                            SourceLocation LBraceLoc) {
16699   AdjustDeclIfTemplate(TagD);
16700   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16701 
16702   FieldCollector->StartClass();
16703 
16704   if (!Record->getIdentifier())
16705     return;
16706 
16707   if (IsAbstract)
16708     Record->markAbstract();
16709 
16710   if (FinalLoc.isValid()) {
16711     Record->addAttr(FinalAttr::Create(
16712         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16713         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16714   }
16715   // C++ [class]p2:
16716   //   [...] The class-name is also inserted into the scope of the
16717   //   class itself; this is known as the injected-class-name. For
16718   //   purposes of access checking, the injected-class-name is treated
16719   //   as if it were a public member name.
16720   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16721       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16722       Record->getLocation(), Record->getIdentifier(),
16723       /*PrevDecl=*/nullptr,
16724       /*DelayTypeCreation=*/true);
16725   Context.getTypeDeclType(InjectedClassName, Record);
16726   InjectedClassName->setImplicit();
16727   InjectedClassName->setAccess(AS_public);
16728   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16729       InjectedClassName->setDescribedClassTemplate(Template);
16730   PushOnScopeChains(InjectedClassName, S);
16731   assert(InjectedClassName->isInjectedClassName() &&
16732          "Broken injected-class-name");
16733 }
16734 
16735 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16736                                     SourceRange BraceRange) {
16737   AdjustDeclIfTemplate(TagD);
16738   TagDecl *Tag = cast<TagDecl>(TagD);
16739   Tag->setBraceRange(BraceRange);
16740 
16741   // Make sure we "complete" the definition even it is invalid.
16742   if (Tag->isBeingDefined()) {
16743     assert(Tag->isInvalidDecl() && "We should already have completed it");
16744     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16745       RD->completeDefinition();
16746   }
16747 
16748   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16749     FieldCollector->FinishClass();
16750     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16751       auto *Def = RD->getDefinition();
16752       assert(Def && "The record is expected to have a completed definition");
16753       unsigned NumInitMethods = 0;
16754       for (auto *Method : Def->methods()) {
16755         if (!Method->getIdentifier())
16756             continue;
16757         if (Method->getName() == "__init")
16758           NumInitMethods++;
16759       }
16760       if (NumInitMethods > 1 || !Def->hasInitMethod())
16761         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16762     }
16763   }
16764 
16765   // Exit this scope of this tag's definition.
16766   PopDeclContext();
16767 
16768   if (getCurLexicalContext()->isObjCContainer() &&
16769       Tag->getDeclContext()->isFileContext())
16770     Tag->setTopLevelDeclInObjCContainer();
16771 
16772   // Notify the consumer that we've defined a tag.
16773   if (!Tag->isInvalidDecl())
16774     Consumer.HandleTagDeclDefinition(Tag);
16775 
16776   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16777   // from XLs and instead matches the XL #pragma pack(1) behavior.
16778   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16779       AlignPackStack.hasValue()) {
16780     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16781     // Only diagnose #pragma align(packed).
16782     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16783       return;
16784     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16785     if (!RD)
16786       return;
16787     // Only warn if there is at least 1 bitfield member.
16788     if (llvm::any_of(RD->fields(),
16789                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16790       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16791   }
16792 }
16793 
16794 void Sema::ActOnObjCContainerFinishDefinition() {
16795   // Exit this scope of this interface definition.
16796   PopDeclContext();
16797 }
16798 
16799 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16800   assert(DC == CurContext && "Mismatch of container contexts");
16801   OriginalLexicalContext = DC;
16802   ActOnObjCContainerFinishDefinition();
16803 }
16804 
16805 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16806   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16807   OriginalLexicalContext = nullptr;
16808 }
16809 
16810 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16811   AdjustDeclIfTemplate(TagD);
16812   TagDecl *Tag = cast<TagDecl>(TagD);
16813   Tag->setInvalidDecl();
16814 
16815   // Make sure we "complete" the definition even it is invalid.
16816   if (Tag->isBeingDefined()) {
16817     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16818       RD->completeDefinition();
16819   }
16820 
16821   // We're undoing ActOnTagStartDefinition here, not
16822   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16823   // the FieldCollector.
16824 
16825   PopDeclContext();
16826 }
16827 
16828 // Note that FieldName may be null for anonymous bitfields.
16829 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16830                                 IdentifierInfo *FieldName,
16831                                 QualType FieldTy, bool IsMsStruct,
16832                                 Expr *BitWidth, bool *ZeroWidth) {
16833   assert(BitWidth);
16834   if (BitWidth->containsErrors())
16835     return ExprError();
16836 
16837   // Default to true; that shouldn't confuse checks for emptiness
16838   if (ZeroWidth)
16839     *ZeroWidth = true;
16840 
16841   // C99 6.7.2.1p4 - verify the field type.
16842   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16843   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16844     // Handle incomplete and sizeless types with a specific error.
16845     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16846                                  diag::err_field_incomplete_or_sizeless))
16847       return ExprError();
16848     if (FieldName)
16849       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16850         << FieldName << FieldTy << BitWidth->getSourceRange();
16851     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16852       << FieldTy << BitWidth->getSourceRange();
16853   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16854                                              UPPC_BitFieldWidth))
16855     return ExprError();
16856 
16857   // If the bit-width is type- or value-dependent, don't try to check
16858   // it now.
16859   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16860     return BitWidth;
16861 
16862   llvm::APSInt Value;
16863   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16864   if (ICE.isInvalid())
16865     return ICE;
16866   BitWidth = ICE.get();
16867 
16868   if (Value != 0 && ZeroWidth)
16869     *ZeroWidth = false;
16870 
16871   // Zero-width bitfield is ok for anonymous field.
16872   if (Value == 0 && FieldName)
16873     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16874 
16875   if (Value.isSigned() && Value.isNegative()) {
16876     if (FieldName)
16877       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16878                << FieldName << toString(Value, 10);
16879     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16880       << toString(Value, 10);
16881   }
16882 
16883   // The size of the bit-field must not exceed our maximum permitted object
16884   // size.
16885   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16886     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16887            << !FieldName << FieldName << toString(Value, 10);
16888   }
16889 
16890   if (!FieldTy->isDependentType()) {
16891     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16892     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16893     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16894 
16895     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16896     // ABI.
16897     bool CStdConstraintViolation =
16898         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16899     bool MSBitfieldViolation =
16900         Value.ugt(TypeStorageSize) &&
16901         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16902     if (CStdConstraintViolation || MSBitfieldViolation) {
16903       unsigned DiagWidth =
16904           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16905       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16906              << (bool)FieldName << FieldName << toString(Value, 10)
16907              << !CStdConstraintViolation << DiagWidth;
16908     }
16909 
16910     // Warn on types where the user might conceivably expect to get all
16911     // specified bits as value bits: that's all integral types other than
16912     // 'bool'.
16913     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16914       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16915           << FieldName << toString(Value, 10)
16916           << (unsigned)TypeWidth;
16917     }
16918   }
16919 
16920   return BitWidth;
16921 }
16922 
16923 /// ActOnField - Each field of a C struct/union is passed into this in order
16924 /// to create a FieldDecl object for it.
16925 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16926                        Declarator &D, Expr *BitfieldWidth) {
16927   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16928                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16929                                /*InitStyle=*/ICIS_NoInit, AS_public);
16930   return Res;
16931 }
16932 
16933 /// HandleField - Analyze a field of a C struct or a C++ data member.
16934 ///
16935 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16936                              SourceLocation DeclStart,
16937                              Declarator &D, Expr *BitWidth,
16938                              InClassInitStyle InitStyle,
16939                              AccessSpecifier AS) {
16940   if (D.isDecompositionDeclarator()) {
16941     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16942     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16943       << Decomp.getSourceRange();
16944     return nullptr;
16945   }
16946 
16947   IdentifierInfo *II = D.getIdentifier();
16948   SourceLocation Loc = DeclStart;
16949   if (II) Loc = D.getIdentifierLoc();
16950 
16951   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16952   QualType T = TInfo->getType();
16953   if (getLangOpts().CPlusPlus) {
16954     CheckExtraCXXDefaultArguments(D);
16955 
16956     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16957                                         UPPC_DataMemberType)) {
16958       D.setInvalidType();
16959       T = Context.IntTy;
16960       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16961     }
16962   }
16963 
16964   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16965 
16966   if (D.getDeclSpec().isInlineSpecified())
16967     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16968         << getLangOpts().CPlusPlus17;
16969   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16970     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16971          diag::err_invalid_thread)
16972       << DeclSpec::getSpecifierName(TSCS);
16973 
16974   // Check to see if this name was declared as a member previously
16975   NamedDecl *PrevDecl = nullptr;
16976   LookupResult Previous(*this, II, Loc, LookupMemberName,
16977                         ForVisibleRedeclaration);
16978   LookupName(Previous, S);
16979   switch (Previous.getResultKind()) {
16980     case LookupResult::Found:
16981     case LookupResult::FoundUnresolvedValue:
16982       PrevDecl = Previous.getAsSingle<NamedDecl>();
16983       break;
16984 
16985     case LookupResult::FoundOverloaded:
16986       PrevDecl = Previous.getRepresentativeDecl();
16987       break;
16988 
16989     case LookupResult::NotFound:
16990     case LookupResult::NotFoundInCurrentInstantiation:
16991     case LookupResult::Ambiguous:
16992       break;
16993   }
16994   Previous.suppressDiagnostics();
16995 
16996   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16997     // Maybe we will complain about the shadowed template parameter.
16998     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16999     // Just pretend that we didn't see the previous declaration.
17000     PrevDecl = nullptr;
17001   }
17002 
17003   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17004     PrevDecl = nullptr;
17005 
17006   bool Mutable
17007     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17008   SourceLocation TSSL = D.getBeginLoc();
17009   FieldDecl *NewFD
17010     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17011                      TSSL, AS, PrevDecl, &D);
17012 
17013   if (NewFD->isInvalidDecl())
17014     Record->setInvalidDecl();
17015 
17016   if (D.getDeclSpec().isModulePrivateSpecified())
17017     NewFD->setModulePrivate();
17018 
17019   if (NewFD->isInvalidDecl() && PrevDecl) {
17020     // Don't introduce NewFD into scope; there's already something
17021     // with the same name in the same scope.
17022   } else if (II) {
17023     PushOnScopeChains(NewFD, S);
17024   } else
17025     Record->addDecl(NewFD);
17026 
17027   return NewFD;
17028 }
17029 
17030 /// Build a new FieldDecl and check its well-formedness.
17031 ///
17032 /// This routine builds a new FieldDecl given the fields name, type,
17033 /// record, etc. \p PrevDecl should refer to any previous declaration
17034 /// with the same name and in the same scope as the field to be
17035 /// created.
17036 ///
17037 /// \returns a new FieldDecl.
17038 ///
17039 /// \todo The Declarator argument is a hack. It will be removed once
17040 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17041                                 TypeSourceInfo *TInfo,
17042                                 RecordDecl *Record, SourceLocation Loc,
17043                                 bool Mutable, Expr *BitWidth,
17044                                 InClassInitStyle InitStyle,
17045                                 SourceLocation TSSL,
17046                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17047                                 Declarator *D) {
17048   IdentifierInfo *II = Name.getAsIdentifierInfo();
17049   bool InvalidDecl = false;
17050   if (D) InvalidDecl = D->isInvalidType();
17051 
17052   // If we receive a broken type, recover by assuming 'int' and
17053   // marking this declaration as invalid.
17054   if (T.isNull() || T->containsErrors()) {
17055     InvalidDecl = true;
17056     T = Context.IntTy;
17057   }
17058 
17059   QualType EltTy = Context.getBaseElementType(T);
17060   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17061     if (RequireCompleteSizedType(Loc, EltTy,
17062                                  diag::err_field_incomplete_or_sizeless)) {
17063       // Fields of incomplete type force their record to be invalid.
17064       Record->setInvalidDecl();
17065       InvalidDecl = true;
17066     } else {
17067       NamedDecl *Def;
17068       EltTy->isIncompleteType(&Def);
17069       if (Def && Def->isInvalidDecl()) {
17070         Record->setInvalidDecl();
17071         InvalidDecl = true;
17072       }
17073     }
17074   }
17075 
17076   // TR 18037 does not allow fields to be declared with address space
17077   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17078       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17079     Diag(Loc, diag::err_field_with_address_space);
17080     Record->setInvalidDecl();
17081     InvalidDecl = true;
17082   }
17083 
17084   if (LangOpts.OpenCL) {
17085     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17086     // used as structure or union field: image, sampler, event or block types.
17087     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17088         T->isBlockPointerType()) {
17089       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17090       Record->setInvalidDecl();
17091       InvalidDecl = true;
17092     }
17093     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17094     // is enabled.
17095     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17096                         "__cl_clang_bitfields", LangOpts)) {
17097       Diag(Loc, diag::err_opencl_bitfields);
17098       InvalidDecl = true;
17099     }
17100   }
17101 
17102   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17103   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17104       T.hasQualifiers()) {
17105     InvalidDecl = true;
17106     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17107   }
17108 
17109   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17110   // than a variably modified type.
17111   if (!InvalidDecl && T->isVariablyModifiedType()) {
17112     if (!tryToFixVariablyModifiedVarType(
17113             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17114       InvalidDecl = true;
17115   }
17116 
17117   // Fields can not have abstract class types
17118   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17119                                              diag::err_abstract_type_in_decl,
17120                                              AbstractFieldType))
17121     InvalidDecl = true;
17122 
17123   bool ZeroWidth = false;
17124   if (InvalidDecl)
17125     BitWidth = nullptr;
17126   // If this is declared as a bit-field, check the bit-field.
17127   if (BitWidth) {
17128     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17129                               &ZeroWidth).get();
17130     if (!BitWidth) {
17131       InvalidDecl = true;
17132       BitWidth = nullptr;
17133       ZeroWidth = false;
17134     }
17135   }
17136 
17137   // Check that 'mutable' is consistent with the type of the declaration.
17138   if (!InvalidDecl && Mutable) {
17139     unsigned DiagID = 0;
17140     if (T->isReferenceType())
17141       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17142                                         : diag::err_mutable_reference;
17143     else if (T.isConstQualified())
17144       DiagID = diag::err_mutable_const;
17145 
17146     if (DiagID) {
17147       SourceLocation ErrLoc = Loc;
17148       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17149         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17150       Diag(ErrLoc, DiagID);
17151       if (DiagID != diag::ext_mutable_reference) {
17152         Mutable = false;
17153         InvalidDecl = true;
17154       }
17155     }
17156   }
17157 
17158   // C++11 [class.union]p8 (DR1460):
17159   //   At most one variant member of a union may have a
17160   //   brace-or-equal-initializer.
17161   if (InitStyle != ICIS_NoInit)
17162     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17163 
17164   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17165                                        BitWidth, Mutable, InitStyle);
17166   if (InvalidDecl)
17167     NewFD->setInvalidDecl();
17168 
17169   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17170     Diag(Loc, diag::err_duplicate_member) << II;
17171     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17172     NewFD->setInvalidDecl();
17173   }
17174 
17175   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17176     if (Record->isUnion()) {
17177       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17178         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17179         if (RDecl->getDefinition()) {
17180           // C++ [class.union]p1: An object of a class with a non-trivial
17181           // constructor, a non-trivial copy constructor, a non-trivial
17182           // destructor, or a non-trivial copy assignment operator
17183           // cannot be a member of a union, nor can an array of such
17184           // objects.
17185           if (CheckNontrivialField(NewFD))
17186             NewFD->setInvalidDecl();
17187         }
17188       }
17189 
17190       // C++ [class.union]p1: If a union contains a member of reference type,
17191       // the program is ill-formed, except when compiling with MSVC extensions
17192       // enabled.
17193       if (EltTy->isReferenceType()) {
17194         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17195                                     diag::ext_union_member_of_reference_type :
17196                                     diag::err_union_member_of_reference_type)
17197           << NewFD->getDeclName() << EltTy;
17198         if (!getLangOpts().MicrosoftExt)
17199           NewFD->setInvalidDecl();
17200       }
17201     }
17202   }
17203 
17204   // FIXME: We need to pass in the attributes given an AST
17205   // representation, not a parser representation.
17206   if (D) {
17207     // FIXME: The current scope is almost... but not entirely... correct here.
17208     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17209 
17210     if (NewFD->hasAttrs())
17211       CheckAlignasUnderalignment(NewFD);
17212   }
17213 
17214   // In auto-retain/release, infer strong retension for fields of
17215   // retainable type.
17216   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17217     NewFD->setInvalidDecl();
17218 
17219   if (T.isObjCGCWeak())
17220     Diag(Loc, diag::warn_attribute_weak_on_field);
17221 
17222   // PPC MMA non-pointer types are not allowed as field types.
17223   if (Context.getTargetInfo().getTriple().isPPC64() &&
17224       CheckPPCMMAType(T, NewFD->getLocation()))
17225     NewFD->setInvalidDecl();
17226 
17227   NewFD->setAccess(AS);
17228   return NewFD;
17229 }
17230 
17231 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17232   assert(FD);
17233   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17234 
17235   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17236     return false;
17237 
17238   QualType EltTy = Context.getBaseElementType(FD->getType());
17239   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17240     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17241     if (RDecl->getDefinition()) {
17242       // We check for copy constructors before constructors
17243       // because otherwise we'll never get complaints about
17244       // copy constructors.
17245 
17246       CXXSpecialMember member = CXXInvalid;
17247       // We're required to check for any non-trivial constructors. Since the
17248       // implicit default constructor is suppressed if there are any
17249       // user-declared constructors, we just need to check that there is a
17250       // trivial default constructor and a trivial copy constructor. (We don't
17251       // worry about move constructors here, since this is a C++98 check.)
17252       if (RDecl->hasNonTrivialCopyConstructor())
17253         member = CXXCopyConstructor;
17254       else if (!RDecl->hasTrivialDefaultConstructor())
17255         member = CXXDefaultConstructor;
17256       else if (RDecl->hasNonTrivialCopyAssignment())
17257         member = CXXCopyAssignment;
17258       else if (RDecl->hasNonTrivialDestructor())
17259         member = CXXDestructor;
17260 
17261       if (member != CXXInvalid) {
17262         if (!getLangOpts().CPlusPlus11 &&
17263             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17264           // Objective-C++ ARC: it is an error to have a non-trivial field of
17265           // a union. However, system headers in Objective-C programs
17266           // occasionally have Objective-C lifetime objects within unions,
17267           // and rather than cause the program to fail, we make those
17268           // members unavailable.
17269           SourceLocation Loc = FD->getLocation();
17270           if (getSourceManager().isInSystemHeader(Loc)) {
17271             if (!FD->hasAttr<UnavailableAttr>())
17272               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17273                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17274             return false;
17275           }
17276         }
17277 
17278         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17279                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17280                diag::err_illegal_union_or_anon_struct_member)
17281           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17282         DiagnoseNontrivial(RDecl, member);
17283         return !getLangOpts().CPlusPlus11;
17284       }
17285     }
17286   }
17287 
17288   return false;
17289 }
17290 
17291 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17292 ///  AST enum value.
17293 static ObjCIvarDecl::AccessControl
17294 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17295   switch (ivarVisibility) {
17296   default: llvm_unreachable("Unknown visitibility kind");
17297   case tok::objc_private: return ObjCIvarDecl::Private;
17298   case tok::objc_public: return ObjCIvarDecl::Public;
17299   case tok::objc_protected: return ObjCIvarDecl::Protected;
17300   case tok::objc_package: return ObjCIvarDecl::Package;
17301   }
17302 }
17303 
17304 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17305 /// in order to create an IvarDecl object for it.
17306 Decl *Sema::ActOnIvar(Scope *S,
17307                                 SourceLocation DeclStart,
17308                                 Declarator &D, Expr *BitfieldWidth,
17309                                 tok::ObjCKeywordKind Visibility) {
17310 
17311   IdentifierInfo *II = D.getIdentifier();
17312   Expr *BitWidth = (Expr*)BitfieldWidth;
17313   SourceLocation Loc = DeclStart;
17314   if (II) Loc = D.getIdentifierLoc();
17315 
17316   // FIXME: Unnamed fields can be handled in various different ways, for
17317   // example, unnamed unions inject all members into the struct namespace!
17318 
17319   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17320   QualType T = TInfo->getType();
17321 
17322   if (BitWidth) {
17323     // 6.7.2.1p3, 6.7.2.1p4
17324     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17325     if (!BitWidth)
17326       D.setInvalidType();
17327   } else {
17328     // Not a bitfield.
17329 
17330     // validate II.
17331 
17332   }
17333   if (T->isReferenceType()) {
17334     Diag(Loc, diag::err_ivar_reference_type);
17335     D.setInvalidType();
17336   }
17337   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17338   // than a variably modified type.
17339   else if (T->isVariablyModifiedType()) {
17340     if (!tryToFixVariablyModifiedVarType(
17341             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17342       D.setInvalidType();
17343   }
17344 
17345   // Get the visibility (access control) for this ivar.
17346   ObjCIvarDecl::AccessControl ac =
17347     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17348                                         : ObjCIvarDecl::None;
17349   // Must set ivar's DeclContext to its enclosing interface.
17350   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17351   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17352     return nullptr;
17353   ObjCContainerDecl *EnclosingContext;
17354   if (ObjCImplementationDecl *IMPDecl =
17355       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17356     if (LangOpts.ObjCRuntime.isFragile()) {
17357     // Case of ivar declared in an implementation. Context is that of its class.
17358       EnclosingContext = IMPDecl->getClassInterface();
17359       assert(EnclosingContext && "Implementation has no class interface!");
17360     }
17361     else
17362       EnclosingContext = EnclosingDecl;
17363   } else {
17364     if (ObjCCategoryDecl *CDecl =
17365         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17366       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17367         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17368         return nullptr;
17369       }
17370     }
17371     EnclosingContext = EnclosingDecl;
17372   }
17373 
17374   // Construct the decl.
17375   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17376                                              DeclStart, Loc, II, T,
17377                                              TInfo, ac, (Expr *)BitfieldWidth);
17378 
17379   if (II) {
17380     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17381                                            ForVisibleRedeclaration);
17382     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17383         && !isa<TagDecl>(PrevDecl)) {
17384       Diag(Loc, diag::err_duplicate_member) << II;
17385       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17386       NewID->setInvalidDecl();
17387     }
17388   }
17389 
17390   // Process attributes attached to the ivar.
17391   ProcessDeclAttributes(S, NewID, D);
17392 
17393   if (D.isInvalidType())
17394     NewID->setInvalidDecl();
17395 
17396   // In ARC, infer 'retaining' for ivars of retainable type.
17397   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17398     NewID->setInvalidDecl();
17399 
17400   if (D.getDeclSpec().isModulePrivateSpecified())
17401     NewID->setModulePrivate();
17402 
17403   if (II) {
17404     // FIXME: When interfaces are DeclContexts, we'll need to add
17405     // these to the interface.
17406     S->AddDecl(NewID);
17407     IdResolver.AddDecl(NewID);
17408   }
17409 
17410   if (LangOpts.ObjCRuntime.isNonFragile() &&
17411       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17412     Diag(Loc, diag::warn_ivars_in_interface);
17413 
17414   return NewID;
17415 }
17416 
17417 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17418 /// class and class extensions. For every class \@interface and class
17419 /// extension \@interface, if the last ivar is a bitfield of any type,
17420 /// then add an implicit `char :0` ivar to the end of that interface.
17421 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17422                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17423   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17424     return;
17425 
17426   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17427   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17428 
17429   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17430     return;
17431   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17432   if (!ID) {
17433     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17434       if (!CD->IsClassExtension())
17435         return;
17436     }
17437     // No need to add this to end of @implementation.
17438     else
17439       return;
17440   }
17441   // All conditions are met. Add a new bitfield to the tail end of ivars.
17442   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17443   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17444 
17445   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17446                               DeclLoc, DeclLoc, nullptr,
17447                               Context.CharTy,
17448                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17449                                                                DeclLoc),
17450                               ObjCIvarDecl::Private, BW,
17451                               true);
17452   AllIvarDecls.push_back(Ivar);
17453 }
17454 
17455 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17456                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17457                        SourceLocation RBrac,
17458                        const ParsedAttributesView &Attrs) {
17459   assert(EnclosingDecl && "missing record or interface decl");
17460 
17461   // If this is an Objective-C @implementation or category and we have
17462   // new fields here we should reset the layout of the interface since
17463   // it will now change.
17464   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17465     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17466     switch (DC->getKind()) {
17467     default: break;
17468     case Decl::ObjCCategory:
17469       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17470       break;
17471     case Decl::ObjCImplementation:
17472       Context.
17473         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17474       break;
17475     }
17476   }
17477 
17478   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17479   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17480 
17481   // Start counting up the number of named members; make sure to include
17482   // members of anonymous structs and unions in the total.
17483   unsigned NumNamedMembers = 0;
17484   if (Record) {
17485     for (const auto *I : Record->decls()) {
17486       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17487         if (IFD->getDeclName())
17488           ++NumNamedMembers;
17489     }
17490   }
17491 
17492   // Verify that all the fields are okay.
17493   SmallVector<FieldDecl*, 32> RecFields;
17494 
17495   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17496        i != end; ++i) {
17497     FieldDecl *FD = cast<FieldDecl>(*i);
17498 
17499     // Get the type for the field.
17500     const Type *FDTy = FD->getType().getTypePtr();
17501 
17502     if (!FD->isAnonymousStructOrUnion()) {
17503       // Remember all fields written by the user.
17504       RecFields.push_back(FD);
17505     }
17506 
17507     // If the field is already invalid for some reason, don't emit more
17508     // diagnostics about it.
17509     if (FD->isInvalidDecl()) {
17510       EnclosingDecl->setInvalidDecl();
17511       continue;
17512     }
17513 
17514     // C99 6.7.2.1p2:
17515     //   A structure or union shall not contain a member with
17516     //   incomplete or function type (hence, a structure shall not
17517     //   contain an instance of itself, but may contain a pointer to
17518     //   an instance of itself), except that the last member of a
17519     //   structure with more than one named member may have incomplete
17520     //   array type; such a structure (and any union containing,
17521     //   possibly recursively, a member that is such a structure)
17522     //   shall not be a member of a structure or an element of an
17523     //   array.
17524     bool IsLastField = (i + 1 == Fields.end());
17525     if (FDTy->isFunctionType()) {
17526       // Field declared as a function.
17527       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17528         << FD->getDeclName();
17529       FD->setInvalidDecl();
17530       EnclosingDecl->setInvalidDecl();
17531       continue;
17532     } else if (FDTy->isIncompleteArrayType() &&
17533                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17534       if (Record) {
17535         // Flexible array member.
17536         // Microsoft and g++ is more permissive regarding flexible array.
17537         // It will accept flexible array in union and also
17538         // as the sole element of a struct/class.
17539         unsigned DiagID = 0;
17540         if (!Record->isUnion() && !IsLastField) {
17541           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17542             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17543           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17544           FD->setInvalidDecl();
17545           EnclosingDecl->setInvalidDecl();
17546           continue;
17547         } else if (Record->isUnion())
17548           DiagID = getLangOpts().MicrosoftExt
17549                        ? diag::ext_flexible_array_union_ms
17550                        : getLangOpts().CPlusPlus
17551                              ? diag::ext_flexible_array_union_gnu
17552                              : diag::err_flexible_array_union;
17553         else if (NumNamedMembers < 1)
17554           DiagID = getLangOpts().MicrosoftExt
17555                        ? diag::ext_flexible_array_empty_aggregate_ms
17556                        : getLangOpts().CPlusPlus
17557                              ? diag::ext_flexible_array_empty_aggregate_gnu
17558                              : diag::err_flexible_array_empty_aggregate;
17559 
17560         if (DiagID)
17561           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17562                                           << Record->getTagKind();
17563         // While the layout of types that contain virtual bases is not specified
17564         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17565         // virtual bases after the derived members.  This would make a flexible
17566         // array member declared at the end of an object not adjacent to the end
17567         // of the type.
17568         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17569           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17570               << FD->getDeclName() << Record->getTagKind();
17571         if (!getLangOpts().C99)
17572           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17573             << FD->getDeclName() << Record->getTagKind();
17574 
17575         // If the element type has a non-trivial destructor, we would not
17576         // implicitly destroy the elements, so disallow it for now.
17577         //
17578         // FIXME: GCC allows this. We should probably either implicitly delete
17579         // the destructor of the containing class, or just allow this.
17580         QualType BaseElem = Context.getBaseElementType(FD->getType());
17581         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17582           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17583             << FD->getDeclName() << FD->getType();
17584           FD->setInvalidDecl();
17585           EnclosingDecl->setInvalidDecl();
17586           continue;
17587         }
17588         // Okay, we have a legal flexible array member at the end of the struct.
17589         Record->setHasFlexibleArrayMember(true);
17590       } else {
17591         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17592         // unless they are followed by another ivar. That check is done
17593         // elsewhere, after synthesized ivars are known.
17594       }
17595     } else if (!FDTy->isDependentType() &&
17596                RequireCompleteSizedType(
17597                    FD->getLocation(), FD->getType(),
17598                    diag::err_field_incomplete_or_sizeless)) {
17599       // Incomplete type
17600       FD->setInvalidDecl();
17601       EnclosingDecl->setInvalidDecl();
17602       continue;
17603     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17604       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17605         // A type which contains a flexible array member is considered to be a
17606         // flexible array member.
17607         Record->setHasFlexibleArrayMember(true);
17608         if (!Record->isUnion()) {
17609           // If this is a struct/class and this is not the last element, reject
17610           // it.  Note that GCC supports variable sized arrays in the middle of
17611           // structures.
17612           if (!IsLastField)
17613             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17614               << FD->getDeclName() << FD->getType();
17615           else {
17616             // We support flexible arrays at the end of structs in
17617             // other structs as an extension.
17618             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17619               << FD->getDeclName();
17620           }
17621         }
17622       }
17623       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17624           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17625                                  diag::err_abstract_type_in_decl,
17626                                  AbstractIvarType)) {
17627         // Ivars can not have abstract class types
17628         FD->setInvalidDecl();
17629       }
17630       if (Record && FDTTy->getDecl()->hasObjectMember())
17631         Record->setHasObjectMember(true);
17632       if (Record && FDTTy->getDecl()->hasVolatileMember())
17633         Record->setHasVolatileMember(true);
17634     } else if (FDTy->isObjCObjectType()) {
17635       /// A field cannot be an Objective-c object
17636       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17637         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17638       QualType T = Context.getObjCObjectPointerType(FD->getType());
17639       FD->setType(T);
17640     } else if (Record && Record->isUnion() &&
17641                FD->getType().hasNonTrivialObjCLifetime() &&
17642                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17643                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17644                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17645                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17646       // For backward compatibility, fields of C unions declared in system
17647       // headers that have non-trivial ObjC ownership qualifications are marked
17648       // as unavailable unless the qualifier is explicit and __strong. This can
17649       // break ABI compatibility between programs compiled with ARC and MRR, but
17650       // is a better option than rejecting programs using those unions under
17651       // ARC.
17652       FD->addAttr(UnavailableAttr::CreateImplicit(
17653           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17654           FD->getLocation()));
17655     } else if (getLangOpts().ObjC &&
17656                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17657                !Record->hasObjectMember()) {
17658       if (FD->getType()->isObjCObjectPointerType() ||
17659           FD->getType().isObjCGCStrong())
17660         Record->setHasObjectMember(true);
17661       else if (Context.getAsArrayType(FD->getType())) {
17662         QualType BaseType = Context.getBaseElementType(FD->getType());
17663         if (BaseType->isRecordType() &&
17664             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17665           Record->setHasObjectMember(true);
17666         else if (BaseType->isObjCObjectPointerType() ||
17667                  BaseType.isObjCGCStrong())
17668                Record->setHasObjectMember(true);
17669       }
17670     }
17671 
17672     if (Record && !getLangOpts().CPlusPlus &&
17673         !shouldIgnoreForRecordTriviality(FD)) {
17674       QualType FT = FD->getType();
17675       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17676         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17677         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17678             Record->isUnion())
17679           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17680       }
17681       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17682       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17683         Record->setNonTrivialToPrimitiveCopy(true);
17684         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17685           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17686       }
17687       if (FT.isDestructedType()) {
17688         Record->setNonTrivialToPrimitiveDestroy(true);
17689         Record->setParamDestroyedInCallee(true);
17690         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17691           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17692       }
17693 
17694       if (const auto *RT = FT->getAs<RecordType>()) {
17695         if (RT->getDecl()->getArgPassingRestrictions() ==
17696             RecordDecl::APK_CanNeverPassInRegs)
17697           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17698       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17699         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17700     }
17701 
17702     if (Record && FD->getType().isVolatileQualified())
17703       Record->setHasVolatileMember(true);
17704     // Keep track of the number of named members.
17705     if (FD->getIdentifier())
17706       ++NumNamedMembers;
17707   }
17708 
17709   // Okay, we successfully defined 'Record'.
17710   if (Record) {
17711     bool Completed = false;
17712     if (CXXRecord) {
17713       if (!CXXRecord->isInvalidDecl()) {
17714         // Set access bits correctly on the directly-declared conversions.
17715         for (CXXRecordDecl::conversion_iterator
17716                I = CXXRecord->conversion_begin(),
17717                E = CXXRecord->conversion_end(); I != E; ++I)
17718           I.setAccess((*I)->getAccess());
17719       }
17720 
17721       // Add any implicitly-declared members to this class.
17722       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17723 
17724       if (!CXXRecord->isDependentType()) {
17725         if (!CXXRecord->isInvalidDecl()) {
17726           // If we have virtual base classes, we may end up finding multiple
17727           // final overriders for a given virtual function. Check for this
17728           // problem now.
17729           if (CXXRecord->getNumVBases()) {
17730             CXXFinalOverriderMap FinalOverriders;
17731             CXXRecord->getFinalOverriders(FinalOverriders);
17732 
17733             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17734                                              MEnd = FinalOverriders.end();
17735                  M != MEnd; ++M) {
17736               for (OverridingMethods::iterator SO = M->second.begin(),
17737                                             SOEnd = M->second.end();
17738                    SO != SOEnd; ++SO) {
17739                 assert(SO->second.size() > 0 &&
17740                        "Virtual function without overriding functions?");
17741                 if (SO->second.size() == 1)
17742                   continue;
17743 
17744                 // C++ [class.virtual]p2:
17745                 //   In a derived class, if a virtual member function of a base
17746                 //   class subobject has more than one final overrider the
17747                 //   program is ill-formed.
17748                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17749                   << (const NamedDecl *)M->first << Record;
17750                 Diag(M->first->getLocation(),
17751                      diag::note_overridden_virtual_function);
17752                 for (OverridingMethods::overriding_iterator
17753                           OM = SO->second.begin(),
17754                        OMEnd = SO->second.end();
17755                      OM != OMEnd; ++OM)
17756                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17757                     << (const NamedDecl *)M->first << OM->Method->getParent();
17758 
17759                 Record->setInvalidDecl();
17760               }
17761             }
17762             CXXRecord->completeDefinition(&FinalOverriders);
17763             Completed = true;
17764           }
17765         }
17766       }
17767     }
17768 
17769     if (!Completed)
17770       Record->completeDefinition();
17771 
17772     // Handle attributes before checking the layout.
17773     ProcessDeclAttributeList(S, Record, Attrs);
17774 
17775     // We may have deferred checking for a deleted destructor. Check now.
17776     if (CXXRecord) {
17777       auto *Dtor = CXXRecord->getDestructor();
17778       if (Dtor && Dtor->isImplicit() &&
17779           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17780         CXXRecord->setImplicitDestructorIsDeleted();
17781         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17782       }
17783     }
17784 
17785     if (Record->hasAttrs()) {
17786       CheckAlignasUnderalignment(Record);
17787 
17788       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17789         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17790                                            IA->getRange(), IA->getBestCase(),
17791                                            IA->getInheritanceModel());
17792     }
17793 
17794     // Check if the structure/union declaration is a type that can have zero
17795     // size in C. For C this is a language extension, for C++ it may cause
17796     // compatibility problems.
17797     bool CheckForZeroSize;
17798     if (!getLangOpts().CPlusPlus) {
17799       CheckForZeroSize = true;
17800     } else {
17801       // For C++ filter out types that cannot be referenced in C code.
17802       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17803       CheckForZeroSize =
17804           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17805           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17806           CXXRecord->isCLike();
17807     }
17808     if (CheckForZeroSize) {
17809       bool ZeroSize = true;
17810       bool IsEmpty = true;
17811       unsigned NonBitFields = 0;
17812       for (RecordDecl::field_iterator I = Record->field_begin(),
17813                                       E = Record->field_end();
17814            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17815         IsEmpty = false;
17816         if (I->isUnnamedBitfield()) {
17817           if (!I->isZeroLengthBitField(Context))
17818             ZeroSize = false;
17819         } else {
17820           ++NonBitFields;
17821           QualType FieldType = I->getType();
17822           if (FieldType->isIncompleteType() ||
17823               !Context.getTypeSizeInChars(FieldType).isZero())
17824             ZeroSize = false;
17825         }
17826       }
17827 
17828       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17829       // allowed in C++, but warn if its declaration is inside
17830       // extern "C" block.
17831       if (ZeroSize) {
17832         Diag(RecLoc, getLangOpts().CPlusPlus ?
17833                          diag::warn_zero_size_struct_union_in_extern_c :
17834                          diag::warn_zero_size_struct_union_compat)
17835           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17836       }
17837 
17838       // Structs without named members are extension in C (C99 6.7.2.1p7),
17839       // but are accepted by GCC.
17840       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17841         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17842                                diag::ext_no_named_members_in_struct_union)
17843           << Record->isUnion();
17844       }
17845     }
17846   } else {
17847     ObjCIvarDecl **ClsFields =
17848       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17849     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17850       ID->setEndOfDefinitionLoc(RBrac);
17851       // Add ivar's to class's DeclContext.
17852       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17853         ClsFields[i]->setLexicalDeclContext(ID);
17854         ID->addDecl(ClsFields[i]);
17855       }
17856       // Must enforce the rule that ivars in the base classes may not be
17857       // duplicates.
17858       if (ID->getSuperClass())
17859         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17860     } else if (ObjCImplementationDecl *IMPDecl =
17861                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17862       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17863       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17864         // Ivar declared in @implementation never belongs to the implementation.
17865         // Only it is in implementation's lexical context.
17866         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17867       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17868       IMPDecl->setIvarLBraceLoc(LBrac);
17869       IMPDecl->setIvarRBraceLoc(RBrac);
17870     } else if (ObjCCategoryDecl *CDecl =
17871                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17872       // case of ivars in class extension; all other cases have been
17873       // reported as errors elsewhere.
17874       // FIXME. Class extension does not have a LocEnd field.
17875       // CDecl->setLocEnd(RBrac);
17876       // Add ivar's to class extension's DeclContext.
17877       // Diagnose redeclaration of private ivars.
17878       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17879       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17880         if (IDecl) {
17881           if (const ObjCIvarDecl *ClsIvar =
17882               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17883             Diag(ClsFields[i]->getLocation(),
17884                  diag::err_duplicate_ivar_declaration);
17885             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17886             continue;
17887           }
17888           for (const auto *Ext : IDecl->known_extensions()) {
17889             if (const ObjCIvarDecl *ClsExtIvar
17890                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17891               Diag(ClsFields[i]->getLocation(),
17892                    diag::err_duplicate_ivar_declaration);
17893               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17894               continue;
17895             }
17896           }
17897         }
17898         ClsFields[i]->setLexicalDeclContext(CDecl);
17899         CDecl->addDecl(ClsFields[i]);
17900       }
17901       CDecl->setIvarLBraceLoc(LBrac);
17902       CDecl->setIvarRBraceLoc(RBrac);
17903     }
17904   }
17905 }
17906 
17907 /// Determine whether the given integral value is representable within
17908 /// the given type T.
17909 static bool isRepresentableIntegerValue(ASTContext &Context,
17910                                         llvm::APSInt &Value,
17911                                         QualType T) {
17912   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17913          "Integral type required!");
17914   unsigned BitWidth = Context.getIntWidth(T);
17915 
17916   if (Value.isUnsigned() || Value.isNonNegative()) {
17917     if (T->isSignedIntegerOrEnumerationType())
17918       --BitWidth;
17919     return Value.getActiveBits() <= BitWidth;
17920   }
17921   return Value.getMinSignedBits() <= BitWidth;
17922 }
17923 
17924 // Given an integral type, return the next larger integral type
17925 // (or a NULL type of no such type exists).
17926 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17927   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17928   // enum checking below.
17929   assert((T->isIntegralType(Context) ||
17930          T->isEnumeralType()) && "Integral type required!");
17931   const unsigned NumTypes = 4;
17932   QualType SignedIntegralTypes[NumTypes] = {
17933     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17934   };
17935   QualType UnsignedIntegralTypes[NumTypes] = {
17936     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17937     Context.UnsignedLongLongTy
17938   };
17939 
17940   unsigned BitWidth = Context.getTypeSize(T);
17941   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17942                                                         : UnsignedIntegralTypes;
17943   for (unsigned I = 0; I != NumTypes; ++I)
17944     if (Context.getTypeSize(Types[I]) > BitWidth)
17945       return Types[I];
17946 
17947   return QualType();
17948 }
17949 
17950 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17951                                           EnumConstantDecl *LastEnumConst,
17952                                           SourceLocation IdLoc,
17953                                           IdentifierInfo *Id,
17954                                           Expr *Val) {
17955   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17956   llvm::APSInt EnumVal(IntWidth);
17957   QualType EltTy;
17958 
17959   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17960     Val = nullptr;
17961 
17962   if (Val)
17963     Val = DefaultLvalueConversion(Val).get();
17964 
17965   if (Val) {
17966     if (Enum->isDependentType() || Val->isTypeDependent() ||
17967         Val->containsErrors())
17968       EltTy = Context.DependentTy;
17969     else {
17970       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17971       // underlying type, but do allow it in all other contexts.
17972       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17973         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17974         // constant-expression in the enumerator-definition shall be a converted
17975         // constant expression of the underlying type.
17976         EltTy = Enum->getIntegerType();
17977         ExprResult Converted =
17978           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17979                                            CCEK_Enumerator);
17980         if (Converted.isInvalid())
17981           Val = nullptr;
17982         else
17983           Val = Converted.get();
17984       } else if (!Val->isValueDependent() &&
17985                  !(Val =
17986                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17987                            .get())) {
17988         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17989       } else {
17990         if (Enum->isComplete()) {
17991           EltTy = Enum->getIntegerType();
17992 
17993           // In Obj-C and Microsoft mode, require the enumeration value to be
17994           // representable in the underlying type of the enumeration. In C++11,
17995           // we perform a non-narrowing conversion as part of converted constant
17996           // expression checking.
17997           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17998             if (Context.getTargetInfo()
17999                     .getTriple()
18000                     .isWindowsMSVCEnvironment()) {
18001               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18002             } else {
18003               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18004             }
18005           }
18006 
18007           // Cast to the underlying type.
18008           Val = ImpCastExprToType(Val, EltTy,
18009                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18010                                                          : CK_IntegralCast)
18011                     .get();
18012         } else if (getLangOpts().CPlusPlus) {
18013           // C++11 [dcl.enum]p5:
18014           //   If the underlying type is not fixed, the type of each enumerator
18015           //   is the type of its initializing value:
18016           //     - If an initializer is specified for an enumerator, the
18017           //       initializing value has the same type as the expression.
18018           EltTy = Val->getType();
18019         } else {
18020           // C99 6.7.2.2p2:
18021           //   The expression that defines the value of an enumeration constant
18022           //   shall be an integer constant expression that has a value
18023           //   representable as an int.
18024 
18025           // Complain if the value is not representable in an int.
18026           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18027             Diag(IdLoc, diag::ext_enum_value_not_int)
18028               << toString(EnumVal, 10) << Val->getSourceRange()
18029               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18030           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18031             // Force the type of the expression to 'int'.
18032             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18033           }
18034           EltTy = Val->getType();
18035         }
18036       }
18037     }
18038   }
18039 
18040   if (!Val) {
18041     if (Enum->isDependentType())
18042       EltTy = Context.DependentTy;
18043     else if (!LastEnumConst) {
18044       // C++0x [dcl.enum]p5:
18045       //   If the underlying type is not fixed, the type of each enumerator
18046       //   is the type of its initializing value:
18047       //     - If no initializer is specified for the first enumerator, the
18048       //       initializing value has an unspecified integral type.
18049       //
18050       // GCC uses 'int' for its unspecified integral type, as does
18051       // C99 6.7.2.2p3.
18052       if (Enum->isFixed()) {
18053         EltTy = Enum->getIntegerType();
18054       }
18055       else {
18056         EltTy = Context.IntTy;
18057       }
18058     } else {
18059       // Assign the last value + 1.
18060       EnumVal = LastEnumConst->getInitVal();
18061       ++EnumVal;
18062       EltTy = LastEnumConst->getType();
18063 
18064       // Check for overflow on increment.
18065       if (EnumVal < LastEnumConst->getInitVal()) {
18066         // C++0x [dcl.enum]p5:
18067         //   If the underlying type is not fixed, the type of each enumerator
18068         //   is the type of its initializing value:
18069         //
18070         //     - Otherwise the type of the initializing value is the same as
18071         //       the type of the initializing value of the preceding enumerator
18072         //       unless the incremented value is not representable in that type,
18073         //       in which case the type is an unspecified integral type
18074         //       sufficient to contain the incremented value. If no such type
18075         //       exists, the program is ill-formed.
18076         QualType T = getNextLargerIntegralType(Context, EltTy);
18077         if (T.isNull() || Enum->isFixed()) {
18078           // There is no integral type larger enough to represent this
18079           // value. Complain, then allow the value to wrap around.
18080           EnumVal = LastEnumConst->getInitVal();
18081           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18082           ++EnumVal;
18083           if (Enum->isFixed())
18084             // When the underlying type is fixed, this is ill-formed.
18085             Diag(IdLoc, diag::err_enumerator_wrapped)
18086               << toString(EnumVal, 10)
18087               << EltTy;
18088           else
18089             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18090               << toString(EnumVal, 10);
18091         } else {
18092           EltTy = T;
18093         }
18094 
18095         // Retrieve the last enumerator's value, extent that type to the
18096         // type that is supposed to be large enough to represent the incremented
18097         // value, then increment.
18098         EnumVal = LastEnumConst->getInitVal();
18099         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18100         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18101         ++EnumVal;
18102 
18103         // If we're not in C++, diagnose the overflow of enumerator values,
18104         // which in C99 means that the enumerator value is not representable in
18105         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18106         // permits enumerator values that are representable in some larger
18107         // integral type.
18108         if (!getLangOpts().CPlusPlus && !T.isNull())
18109           Diag(IdLoc, diag::warn_enum_value_overflow);
18110       } else if (!getLangOpts().CPlusPlus &&
18111                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18112         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18113         Diag(IdLoc, diag::ext_enum_value_not_int)
18114           << toString(EnumVal, 10) << 1;
18115       }
18116     }
18117   }
18118 
18119   if (!EltTy->isDependentType()) {
18120     // Make the enumerator value match the signedness and size of the
18121     // enumerator's type.
18122     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18123     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18124   }
18125 
18126   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18127                                   Val, EnumVal);
18128 }
18129 
18130 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18131                                                 SourceLocation IILoc) {
18132   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18133       !getLangOpts().CPlusPlus)
18134     return SkipBodyInfo();
18135 
18136   // We have an anonymous enum definition. Look up the first enumerator to
18137   // determine if we should merge the definition with an existing one and
18138   // skip the body.
18139   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18140                                          forRedeclarationInCurContext());
18141   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18142   if (!PrevECD)
18143     return SkipBodyInfo();
18144 
18145   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18146   NamedDecl *Hidden;
18147   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18148     SkipBodyInfo Skip;
18149     Skip.Previous = Hidden;
18150     return Skip;
18151   }
18152 
18153   return SkipBodyInfo();
18154 }
18155 
18156 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18157                               SourceLocation IdLoc, IdentifierInfo *Id,
18158                               const ParsedAttributesView &Attrs,
18159                               SourceLocation EqualLoc, Expr *Val) {
18160   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18161   EnumConstantDecl *LastEnumConst =
18162     cast_or_null<EnumConstantDecl>(lastEnumConst);
18163 
18164   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18165   // we find one that is.
18166   S = getNonFieldDeclScope(S);
18167 
18168   // Verify that there isn't already something declared with this name in this
18169   // scope.
18170   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18171   LookupName(R, S);
18172   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18173 
18174   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18175     // Maybe we will complain about the shadowed template parameter.
18176     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18177     // Just pretend that we didn't see the previous declaration.
18178     PrevDecl = nullptr;
18179   }
18180 
18181   // C++ [class.mem]p15:
18182   // If T is the name of a class, then each of the following shall have a name
18183   // different from T:
18184   // - every enumerator of every member of class T that is an unscoped
18185   // enumerated type
18186   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18187     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18188                             DeclarationNameInfo(Id, IdLoc));
18189 
18190   EnumConstantDecl *New =
18191     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18192   if (!New)
18193     return nullptr;
18194 
18195   if (PrevDecl) {
18196     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18197       // Check for other kinds of shadowing not already handled.
18198       CheckShadow(New, PrevDecl, R);
18199     }
18200 
18201     // When in C++, we may get a TagDecl with the same name; in this case the
18202     // enum constant will 'hide' the tag.
18203     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18204            "Received TagDecl when not in C++!");
18205     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18206       if (isa<EnumConstantDecl>(PrevDecl))
18207         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18208       else
18209         Diag(IdLoc, diag::err_redefinition) << Id;
18210       notePreviousDefinition(PrevDecl, IdLoc);
18211       return nullptr;
18212     }
18213   }
18214 
18215   // Process attributes.
18216   ProcessDeclAttributeList(S, New, Attrs);
18217   AddPragmaAttributes(S, New);
18218 
18219   // Register this decl in the current scope stack.
18220   New->setAccess(TheEnumDecl->getAccess());
18221   PushOnScopeChains(New, S);
18222 
18223   ActOnDocumentableDecl(New);
18224 
18225   return New;
18226 }
18227 
18228 // Returns true when the enum initial expression does not trigger the
18229 // duplicate enum warning.  A few common cases are exempted as follows:
18230 // Element2 = Element1
18231 // Element2 = Element1 + 1
18232 // Element2 = Element1 - 1
18233 // Where Element2 and Element1 are from the same enum.
18234 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18235   Expr *InitExpr = ECD->getInitExpr();
18236   if (!InitExpr)
18237     return true;
18238   InitExpr = InitExpr->IgnoreImpCasts();
18239 
18240   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18241     if (!BO->isAdditiveOp())
18242       return true;
18243     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18244     if (!IL)
18245       return true;
18246     if (IL->getValue() != 1)
18247       return true;
18248 
18249     InitExpr = BO->getLHS();
18250   }
18251 
18252   // This checks if the elements are from the same enum.
18253   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18254   if (!DRE)
18255     return true;
18256 
18257   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18258   if (!EnumConstant)
18259     return true;
18260 
18261   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18262       Enum)
18263     return true;
18264 
18265   return false;
18266 }
18267 
18268 // Emits a warning when an element is implicitly set a value that
18269 // a previous element has already been set to.
18270 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18271                                         EnumDecl *Enum, QualType EnumType) {
18272   // Avoid anonymous enums
18273   if (!Enum->getIdentifier())
18274     return;
18275 
18276   // Only check for small enums.
18277   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18278     return;
18279 
18280   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18281     return;
18282 
18283   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18284   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18285 
18286   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18287 
18288   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18289   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18290 
18291   // Use int64_t as a key to avoid needing special handling for map keys.
18292   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18293     llvm::APSInt Val = D->getInitVal();
18294     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18295   };
18296 
18297   DuplicatesVector DupVector;
18298   ValueToVectorMap EnumMap;
18299 
18300   // Populate the EnumMap with all values represented by enum constants without
18301   // an initializer.
18302   for (auto *Element : Elements) {
18303     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18304 
18305     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18306     // this constant.  Skip this enum since it may be ill-formed.
18307     if (!ECD) {
18308       return;
18309     }
18310 
18311     // Constants with initalizers are handled in the next loop.
18312     if (ECD->getInitExpr())
18313       continue;
18314 
18315     // Duplicate values are handled in the next loop.
18316     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18317   }
18318 
18319   if (EnumMap.size() == 0)
18320     return;
18321 
18322   // Create vectors for any values that has duplicates.
18323   for (auto *Element : Elements) {
18324     // The last loop returned if any constant was null.
18325     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18326     if (!ValidDuplicateEnum(ECD, Enum))
18327       continue;
18328 
18329     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18330     if (Iter == EnumMap.end())
18331       continue;
18332 
18333     DeclOrVector& Entry = Iter->second;
18334     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18335       // Ensure constants are different.
18336       if (D == ECD)
18337         continue;
18338 
18339       // Create new vector and push values onto it.
18340       auto Vec = std::make_unique<ECDVector>();
18341       Vec->push_back(D);
18342       Vec->push_back(ECD);
18343 
18344       // Update entry to point to the duplicates vector.
18345       Entry = Vec.get();
18346 
18347       // Store the vector somewhere we can consult later for quick emission of
18348       // diagnostics.
18349       DupVector.emplace_back(std::move(Vec));
18350       continue;
18351     }
18352 
18353     ECDVector *Vec = Entry.get<ECDVector*>();
18354     // Make sure constants are not added more than once.
18355     if (*Vec->begin() == ECD)
18356       continue;
18357 
18358     Vec->push_back(ECD);
18359   }
18360 
18361   // Emit diagnostics.
18362   for (const auto &Vec : DupVector) {
18363     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18364 
18365     // Emit warning for one enum constant.
18366     auto *FirstECD = Vec->front();
18367     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18368       << FirstECD << toString(FirstECD->getInitVal(), 10)
18369       << FirstECD->getSourceRange();
18370 
18371     // Emit one note for each of the remaining enum constants with
18372     // the same value.
18373     for (auto *ECD : llvm::drop_begin(*Vec))
18374       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18375         << ECD << toString(ECD->getInitVal(), 10)
18376         << ECD->getSourceRange();
18377   }
18378 }
18379 
18380 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18381                              bool AllowMask) const {
18382   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18383   assert(ED->isCompleteDefinition() && "expected enum definition");
18384 
18385   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18386   llvm::APInt &FlagBits = R.first->second;
18387 
18388   if (R.second) {
18389     for (auto *E : ED->enumerators()) {
18390       const auto &EVal = E->getInitVal();
18391       // Only single-bit enumerators introduce new flag values.
18392       if (EVal.isPowerOf2())
18393         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18394     }
18395   }
18396 
18397   // A value is in a flag enum if either its bits are a subset of the enum's
18398   // flag bits (the first condition) or we are allowing masks and the same is
18399   // true of its complement (the second condition). When masks are allowed, we
18400   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18401   //
18402   // While it's true that any value could be used as a mask, the assumption is
18403   // that a mask will have all of the insignificant bits set. Anything else is
18404   // likely a logic error.
18405   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18406   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18407 }
18408 
18409 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18410                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18411                          const ParsedAttributesView &Attrs) {
18412   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18413   QualType EnumType = Context.getTypeDeclType(Enum);
18414 
18415   ProcessDeclAttributeList(S, Enum, Attrs);
18416 
18417   if (Enum->isDependentType()) {
18418     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18419       EnumConstantDecl *ECD =
18420         cast_or_null<EnumConstantDecl>(Elements[i]);
18421       if (!ECD) continue;
18422 
18423       ECD->setType(EnumType);
18424     }
18425 
18426     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18427     return;
18428   }
18429 
18430   // TODO: If the result value doesn't fit in an int, it must be a long or long
18431   // long value.  ISO C does not support this, but GCC does as an extension,
18432   // emit a warning.
18433   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18434   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18435   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18436 
18437   // Verify that all the values are okay, compute the size of the values, and
18438   // reverse the list.
18439   unsigned NumNegativeBits = 0;
18440   unsigned NumPositiveBits = 0;
18441 
18442   // Keep track of whether all elements have type int.
18443   bool AllElementsInt = true;
18444 
18445   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18446     EnumConstantDecl *ECD =
18447       cast_or_null<EnumConstantDecl>(Elements[i]);
18448     if (!ECD) continue;  // Already issued a diagnostic.
18449 
18450     const llvm::APSInt &InitVal = ECD->getInitVal();
18451 
18452     // Keep track of the size of positive and negative values.
18453     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18454       NumPositiveBits = std::max(NumPositiveBits,
18455                                  (unsigned)InitVal.getActiveBits());
18456     else
18457       NumNegativeBits = std::max(NumNegativeBits,
18458                                  (unsigned)InitVal.getMinSignedBits());
18459 
18460     // Keep track of whether every enum element has type int (very common).
18461     if (AllElementsInt)
18462       AllElementsInt = ECD->getType() == Context.IntTy;
18463   }
18464 
18465   // Figure out the type that should be used for this enum.
18466   QualType BestType;
18467   unsigned BestWidth;
18468 
18469   // C++0x N3000 [conv.prom]p3:
18470   //   An rvalue of an unscoped enumeration type whose underlying
18471   //   type is not fixed can be converted to an rvalue of the first
18472   //   of the following types that can represent all the values of
18473   //   the enumeration: int, unsigned int, long int, unsigned long
18474   //   int, long long int, or unsigned long long int.
18475   // C99 6.4.4.3p2:
18476   //   An identifier declared as an enumeration constant has type int.
18477   // The C99 rule is modified by a gcc extension
18478   QualType BestPromotionType;
18479 
18480   bool Packed = Enum->hasAttr<PackedAttr>();
18481   // -fshort-enums is the equivalent to specifying the packed attribute on all
18482   // enum definitions.
18483   if (LangOpts.ShortEnums)
18484     Packed = true;
18485 
18486   // If the enum already has a type because it is fixed or dictated by the
18487   // target, promote that type instead of analyzing the enumerators.
18488   if (Enum->isComplete()) {
18489     BestType = Enum->getIntegerType();
18490     if (BestType->isPromotableIntegerType())
18491       BestPromotionType = Context.getPromotedIntegerType(BestType);
18492     else
18493       BestPromotionType = BestType;
18494 
18495     BestWidth = Context.getIntWidth(BestType);
18496   }
18497   else if (NumNegativeBits) {
18498     // If there is a negative value, figure out the smallest integer type (of
18499     // int/long/longlong) that fits.
18500     // If it's packed, check also if it fits a char or a short.
18501     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18502       BestType = Context.SignedCharTy;
18503       BestWidth = CharWidth;
18504     } else if (Packed && NumNegativeBits <= ShortWidth &&
18505                NumPositiveBits < ShortWidth) {
18506       BestType = Context.ShortTy;
18507       BestWidth = ShortWidth;
18508     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18509       BestType = Context.IntTy;
18510       BestWidth = IntWidth;
18511     } else {
18512       BestWidth = Context.getTargetInfo().getLongWidth();
18513 
18514       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18515         BestType = Context.LongTy;
18516       } else {
18517         BestWidth = Context.getTargetInfo().getLongLongWidth();
18518 
18519         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18520           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18521         BestType = Context.LongLongTy;
18522       }
18523     }
18524     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18525   } else {
18526     // If there is no negative value, figure out the smallest type that fits
18527     // all of the enumerator values.
18528     // If it's packed, check also if it fits a char or a short.
18529     if (Packed && NumPositiveBits <= CharWidth) {
18530       BestType = Context.UnsignedCharTy;
18531       BestPromotionType = Context.IntTy;
18532       BestWidth = CharWidth;
18533     } else if (Packed && NumPositiveBits <= ShortWidth) {
18534       BestType = Context.UnsignedShortTy;
18535       BestPromotionType = Context.IntTy;
18536       BestWidth = ShortWidth;
18537     } else if (NumPositiveBits <= IntWidth) {
18538       BestType = Context.UnsignedIntTy;
18539       BestWidth = IntWidth;
18540       BestPromotionType
18541         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18542                            ? Context.UnsignedIntTy : Context.IntTy;
18543     } else if (NumPositiveBits <=
18544                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18545       BestType = Context.UnsignedLongTy;
18546       BestPromotionType
18547         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18548                            ? Context.UnsignedLongTy : Context.LongTy;
18549     } else {
18550       BestWidth = Context.getTargetInfo().getLongLongWidth();
18551       assert(NumPositiveBits <= BestWidth &&
18552              "How could an initializer get larger than ULL?");
18553       BestType = Context.UnsignedLongLongTy;
18554       BestPromotionType
18555         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18556                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18557     }
18558   }
18559 
18560   // Loop over all of the enumerator constants, changing their types to match
18561   // the type of the enum if needed.
18562   for (auto *D : Elements) {
18563     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18564     if (!ECD) continue;  // Already issued a diagnostic.
18565 
18566     // Standard C says the enumerators have int type, but we allow, as an
18567     // extension, the enumerators to be larger than int size.  If each
18568     // enumerator value fits in an int, type it as an int, otherwise type it the
18569     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18570     // that X has type 'int', not 'unsigned'.
18571 
18572     // Determine whether the value fits into an int.
18573     llvm::APSInt InitVal = ECD->getInitVal();
18574 
18575     // If it fits into an integer type, force it.  Otherwise force it to match
18576     // the enum decl type.
18577     QualType NewTy;
18578     unsigned NewWidth;
18579     bool NewSign;
18580     if (!getLangOpts().CPlusPlus &&
18581         !Enum->isFixed() &&
18582         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18583       NewTy = Context.IntTy;
18584       NewWidth = IntWidth;
18585       NewSign = true;
18586     } else if (ECD->getType() == BestType) {
18587       // Already the right type!
18588       if (getLangOpts().CPlusPlus)
18589         // C++ [dcl.enum]p4: Following the closing brace of an
18590         // enum-specifier, each enumerator has the type of its
18591         // enumeration.
18592         ECD->setType(EnumType);
18593       continue;
18594     } else {
18595       NewTy = BestType;
18596       NewWidth = BestWidth;
18597       NewSign = BestType->isSignedIntegerOrEnumerationType();
18598     }
18599 
18600     // Adjust the APSInt value.
18601     InitVal = InitVal.extOrTrunc(NewWidth);
18602     InitVal.setIsSigned(NewSign);
18603     ECD->setInitVal(InitVal);
18604 
18605     // Adjust the Expr initializer and type.
18606     if (ECD->getInitExpr() &&
18607         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18608       ECD->setInitExpr(ImplicitCastExpr::Create(
18609           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18610           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18611     if (getLangOpts().CPlusPlus)
18612       // C++ [dcl.enum]p4: Following the closing brace of an
18613       // enum-specifier, each enumerator has the type of its
18614       // enumeration.
18615       ECD->setType(EnumType);
18616     else
18617       ECD->setType(NewTy);
18618   }
18619 
18620   Enum->completeDefinition(BestType, BestPromotionType,
18621                            NumPositiveBits, NumNegativeBits);
18622 
18623   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18624 
18625   if (Enum->isClosedFlag()) {
18626     for (Decl *D : Elements) {
18627       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18628       if (!ECD) continue;  // Already issued a diagnostic.
18629 
18630       llvm::APSInt InitVal = ECD->getInitVal();
18631       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18632           !IsValueInFlagEnum(Enum, InitVal, true))
18633         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18634           << ECD << Enum;
18635     }
18636   }
18637 
18638   // Now that the enum type is defined, ensure it's not been underaligned.
18639   if (Enum->hasAttrs())
18640     CheckAlignasUnderalignment(Enum);
18641 }
18642 
18643 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18644                                   SourceLocation StartLoc,
18645                                   SourceLocation EndLoc) {
18646   StringLiteral *AsmString = cast<StringLiteral>(expr);
18647 
18648   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18649                                                    AsmString, StartLoc,
18650                                                    EndLoc);
18651   CurContext->addDecl(New);
18652   return New;
18653 }
18654 
18655 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18656                                       IdentifierInfo* AliasName,
18657                                       SourceLocation PragmaLoc,
18658                                       SourceLocation NameLoc,
18659                                       SourceLocation AliasNameLoc) {
18660   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18661                                          LookupOrdinaryName);
18662   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18663                            AttributeCommonInfo::AS_Pragma);
18664   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18665       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18666 
18667   // If a declaration that:
18668   // 1) declares a function or a variable
18669   // 2) has external linkage
18670   // already exists, add a label attribute to it.
18671   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18672     if (isDeclExternC(PrevDecl))
18673       PrevDecl->addAttr(Attr);
18674     else
18675       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18676           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18677   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18678   } else
18679     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18680 }
18681 
18682 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18683                              SourceLocation PragmaLoc,
18684                              SourceLocation NameLoc) {
18685   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18686 
18687   if (PrevDecl) {
18688     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18689   } else {
18690     (void)WeakUndeclaredIdentifiers.insert(
18691       std::pair<IdentifierInfo*,WeakInfo>
18692         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18693   }
18694 }
18695 
18696 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18697                                 IdentifierInfo* AliasName,
18698                                 SourceLocation PragmaLoc,
18699                                 SourceLocation NameLoc,
18700                                 SourceLocation AliasNameLoc) {
18701   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18702                                     LookupOrdinaryName);
18703   WeakInfo W = WeakInfo(Name, NameLoc);
18704 
18705   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18706     if (!PrevDecl->hasAttr<AliasAttr>())
18707       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18708         DeclApplyPragmaWeak(TUScope, ND, W);
18709   } else {
18710     (void)WeakUndeclaredIdentifiers.insert(
18711       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18712   }
18713 }
18714 
18715 Decl *Sema::getObjCDeclContext() const {
18716   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18717 }
18718 
18719 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18720                                                      bool Final) {
18721   assert(FD && "Expected non-null FunctionDecl");
18722 
18723   // SYCL functions can be template, so we check if they have appropriate
18724   // attribute prior to checking if it is a template.
18725   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18726     return FunctionEmissionStatus::Emitted;
18727 
18728   // Templates are emitted when they're instantiated.
18729   if (FD->isDependentContext())
18730     return FunctionEmissionStatus::TemplateDiscarded;
18731 
18732   // Check whether this function is an externally visible definition.
18733   auto IsEmittedForExternalSymbol = [this, FD]() {
18734     // We have to check the GVA linkage of the function's *definition* -- if we
18735     // only have a declaration, we don't know whether or not the function will
18736     // be emitted, because (say) the definition could include "inline".
18737     FunctionDecl *Def = FD->getDefinition();
18738 
18739     return Def && !isDiscardableGVALinkage(
18740                       getASTContext().GetGVALinkageForFunction(Def));
18741   };
18742 
18743   if (LangOpts.OpenMPIsDevice) {
18744     // In OpenMP device mode we will not emit host only functions, or functions
18745     // we don't need due to their linkage.
18746     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18747         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18748     // DevTy may be changed later by
18749     //  #pragma omp declare target to(*) device_type(*).
18750     // Therefore DevTy having no value does not imply host. The emission status
18751     // will be checked again at the end of compilation unit with Final = true.
18752     if (DevTy.hasValue())
18753       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18754         return FunctionEmissionStatus::OMPDiscarded;
18755     // If we have an explicit value for the device type, or we are in a target
18756     // declare context, we need to emit all extern and used symbols.
18757     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18758       if (IsEmittedForExternalSymbol())
18759         return FunctionEmissionStatus::Emitted;
18760     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18761     // we'll omit it.
18762     if (Final)
18763       return FunctionEmissionStatus::OMPDiscarded;
18764   } else if (LangOpts.OpenMP > 45) {
18765     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18766     // function. In 5.0, no_host was introduced which might cause a function to
18767     // be ommitted.
18768     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18769         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18770     if (DevTy.hasValue())
18771       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18772         return FunctionEmissionStatus::OMPDiscarded;
18773   }
18774 
18775   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18776     return FunctionEmissionStatus::Emitted;
18777 
18778   if (LangOpts.CUDA) {
18779     // When compiling for device, host functions are never emitted.  Similarly,
18780     // when compiling for host, device and global functions are never emitted.
18781     // (Technically, we do emit a host-side stub for global functions, but this
18782     // doesn't count for our purposes here.)
18783     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18784     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18785       return FunctionEmissionStatus::CUDADiscarded;
18786     if (!LangOpts.CUDAIsDevice &&
18787         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18788       return FunctionEmissionStatus::CUDADiscarded;
18789 
18790     if (IsEmittedForExternalSymbol())
18791       return FunctionEmissionStatus::Emitted;
18792   }
18793 
18794   // Otherwise, the function is known-emitted if it's in our set of
18795   // known-emitted functions.
18796   return FunctionEmissionStatus::Unknown;
18797 }
18798 
18799 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18800   // Host-side references to a __global__ function refer to the stub, so the
18801   // function itself is never emitted and therefore should not be marked.
18802   // If we have host fn calls kernel fn calls host+device, the HD function
18803   // does not get instantiated on the host. We model this by omitting at the
18804   // call to the kernel from the callgraph. This ensures that, when compiling
18805   // for host, only HD functions actually called from the host get marked as
18806   // known-emitted.
18807   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18808          IdentifyCUDATarget(Callee) == CFT_Global;
18809 }
18810