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/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <functional>
52 #include <unordered_map>
53 
54 using namespace clang;
55 using namespace sema;
56 
57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58   if (OwnedType) {
59     Decl *Group[2] = { OwnedType, Ptr };
60     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61   }
62 
63   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 }
65 
66 namespace {
67 
68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69  public:
70    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71                         bool AllowTemplates = false,
72                         bool AllowNonTemplates = true)
73        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75      WantExpressionKeywords = false;
76      WantCXXNamedCasts = false;
77      WantRemainingKeywords = false;
78   }
79 
80   bool ValidateCandidate(const TypoCorrection &candidate) override {
81     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82       if (!AllowInvalidDecl && ND->isInvalidDecl())
83         return false;
84 
85       if (getAsTypeTemplateDecl(ND))
86         return AllowTemplates;
87 
88       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89       if (!IsType)
90         return false;
91 
92       if (AllowNonTemplates)
93         return true;
94 
95       // An injected-class-name of a class template (specialization) is valid
96       // as a template or as a non-template.
97       if (AllowTemplates) {
98         auto *RD = dyn_cast<CXXRecordDecl>(ND);
99         if (!RD || !RD->isInjectedClassName())
100           return false;
101         RD = cast<CXXRecordDecl>(RD->getDeclContext());
102         return RD->getDescribedClassTemplate() ||
103                isa<ClassTemplateSpecializationDecl>(RD);
104       }
105 
106       return false;
107     }
108 
109     return !WantClassName && candidate.isKeyword();
110   }
111 
112   std::unique_ptr<CorrectionCandidateCallback> clone() override {
113     return std::make_unique<TypeNameValidatorCCC>(*this);
114   }
115 
116  private:
117   bool AllowInvalidDecl;
118   bool WantClassName;
119   bool AllowTemplates;
120   bool AllowNonTemplates;
121 };
122 
123 } // end anonymous namespace
124 
125 /// Determine whether the token kind starts a simple-type-specifier.
126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127   switch (Kind) {
128   // FIXME: Take into account the current language when deciding whether a
129   // token kind is a valid type specifier
130   case tok::kw_short:
131   case tok::kw_long:
132   case tok::kw___int64:
133   case tok::kw___int128:
134   case tok::kw_signed:
135   case tok::kw_unsigned:
136   case tok::kw_void:
137   case tok::kw_char:
138   case tok::kw_int:
139   case tok::kw_half:
140   case tok::kw_float:
141   case tok::kw_double:
142   case tok::kw___bf16:
143   case tok::kw__Float16:
144   case tok::kw___float128:
145   case tok::kw___ibm128:
146   case tok::kw_wchar_t:
147   case tok::kw_bool:
148   case tok::kw___underlying_type:
149   case tok::kw___auto_type:
150     return true;
151 
152   case tok::annot_typename:
153   case tok::kw_char16_t:
154   case tok::kw_char32_t:
155   case tok::kw_typeof:
156   case tok::annot_decltype:
157   case tok::kw_decltype:
158     return getLangOpts().CPlusPlus;
159 
160   case tok::kw_char8_t:
161     return getLangOpts().Char8;
162 
163   default:
164     break;
165   }
166 
167   return false;
168 }
169 
170 namespace {
171 enum class UnqualifiedTypeNameLookupResult {
172   NotFound,
173   FoundNonType,
174   FoundType
175 };
176 } // end anonymous namespace
177 
178 /// Tries to perform unqualified lookup of the type decls in bases for
179 /// dependent class.
180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
181 /// type decl, \a FoundType if only type decls are found.
182 static UnqualifiedTypeNameLookupResult
183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
184                                 SourceLocation NameLoc,
185                                 const CXXRecordDecl *RD) {
186   if (!RD->hasDefinition())
187     return UnqualifiedTypeNameLookupResult::NotFound;
188   // Look for type decls in base classes.
189   UnqualifiedTypeNameLookupResult FoundTypeDecl =
190       UnqualifiedTypeNameLookupResult::NotFound;
191   for (const auto &Base : RD->bases()) {
192     const CXXRecordDecl *BaseRD = nullptr;
193     if (auto *BaseTT = Base.getType()->getAs<TagType>())
194       BaseRD = BaseTT->getAsCXXRecordDecl();
195     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
196       // Look for type decls in dependent base classes that have known primary
197       // templates.
198       if (!TST || !TST->isDependentType())
199         continue;
200       auto *TD = TST->getTemplateName().getAsTemplateDecl();
201       if (!TD)
202         continue;
203       if (auto *BasePrimaryTemplate =
204           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
205         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
206           BaseRD = BasePrimaryTemplate;
207         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208           if (const ClassTemplatePartialSpecializationDecl *PS =
209                   CTD->findPartialSpecialization(Base.getType()))
210             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
211               BaseRD = PS;
212         }
213       }
214     }
215     if (BaseRD) {
216       for (NamedDecl *ND : BaseRD->lookup(&II)) {
217         if (!isa<TypeDecl>(ND))
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220       }
221       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
223         case UnqualifiedTypeNameLookupResult::FoundNonType:
224           return UnqualifiedTypeNameLookupResult::FoundNonType;
225         case UnqualifiedTypeNameLookupResult::FoundType:
226           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227           break;
228         case UnqualifiedTypeNameLookupResult::NotFound:
229           break;
230         }
231       }
232     }
233   }
234 
235   return FoundTypeDecl;
236 }
237 
238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
239                                                       const IdentifierInfo &II,
240                                                       SourceLocation NameLoc) {
241   // Lookup in the parent class template context, if any.
242   const CXXRecordDecl *RD = nullptr;
243   UnqualifiedTypeNameLookupResult FoundTypeDecl =
244       UnqualifiedTypeNameLookupResult::NotFound;
245   for (DeclContext *DC = S.CurContext;
246        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
247        DC = DC->getParent()) {
248     // Look for type decls in dependent base classes that have known primary
249     // templates.
250     RD = dyn_cast<CXXRecordDecl>(DC);
251     if (RD && RD->getDescribedClassTemplate())
252       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
253   }
254   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
255     return nullptr;
256 
257   // We found some types in dependent base classes.  Recover as if the user
258   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
259   // lookup during template instantiation.
260   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
261 
262   ASTContext &Context = S.Context;
263   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
264                                           cast<Type>(Context.getRecordType(RD)));
265   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
266 
267   CXXScopeSpec SS;
268   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
269 
270   TypeLocBuilder Builder;
271   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
272   DepTL.setNameLoc(NameLoc);
273   DepTL.setElaboratedKeywordLoc(SourceLocation());
274   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
275   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
276 }
277 
278 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
279 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
280                                  SourceLocation NameLoc,
281                                  bool WantNontrivialTypeSourceInfo = true) {
282   switch (T->getTypeClass()) {
283   case Type::DeducedTemplateSpecialization:
284   case Type::Enum:
285   case Type::InjectedClassName:
286   case Type::Record:
287   case Type::Typedef:
288   case Type::UnresolvedUsing:
289   case Type::Using:
290     break;
291   // These can never be qualified so an ElaboratedType node
292   // would carry no additional meaning.
293   case Type::ObjCInterface:
294   case Type::ObjCTypeParam:
295   case Type::TemplateTypeParm:
296     return ParsedType::make(T);
297   default:
298     llvm_unreachable("Unexpected Type Class");
299   }
300 
301   if (!SS || SS->isEmpty())
302     return ParsedType::make(
303         S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
304 
305   QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
306   if (!WantNontrivialTypeSourceInfo)
307     return ParsedType::make(ElTy);
308 
309   TypeLocBuilder Builder;
310   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
311   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
312   ElabTL.setElaboratedKeywordLoc(SourceLocation());
313   ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
314   return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
315 }
316 
317 /// If the identifier refers to a type name within this scope,
318 /// return the declaration of that type.
319 ///
320 /// This routine performs ordinary name lookup of the identifier II
321 /// within the given scope, with optional C++ scope specifier SS, to
322 /// determine whether the name refers to a type. If so, returns an
323 /// opaque pointer (actually a QualType) corresponding to that
324 /// type. Otherwise, returns NULL.
325 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
326                              Scope *S, CXXScopeSpec *SS,
327                              bool isClassName, bool HasTrailingDot,
328                              ParsedType ObjectTypePtr,
329                              bool IsCtorOrDtorName,
330                              bool WantNontrivialTypeSourceInfo,
331                              bool IsClassTemplateDeductionContext,
332                              IdentifierInfo **CorrectedII) {
333   // FIXME: Consider allowing this outside C++1z mode as an extension.
334   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
335                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
336                               !isClassName && !HasTrailingDot;
337 
338   // Determine where we will perform name lookup.
339   DeclContext *LookupCtx = nullptr;
340   if (ObjectTypePtr) {
341     QualType ObjectType = ObjectTypePtr.get();
342     if (ObjectType->isRecordType())
343       LookupCtx = computeDeclContext(ObjectType);
344   } else if (SS && SS->isNotEmpty()) {
345     LookupCtx = computeDeclContext(*SS, false);
346 
347     if (!LookupCtx) {
348       if (isDependentScopeSpecifier(*SS)) {
349         // C++ [temp.res]p3:
350         //   A qualified-id that refers to a type and in which the
351         //   nested-name-specifier depends on a template-parameter (14.6.2)
352         //   shall be prefixed by the keyword typename to indicate that the
353         //   qualified-id denotes a type, forming an
354         //   elaborated-type-specifier (7.1.5.3).
355         //
356         // We therefore do not perform any name lookup if the result would
357         // refer to a member of an unknown specialization.
358         if (!isClassName && !IsCtorOrDtorName)
359           return nullptr;
360 
361         // We know from the grammar that this name refers to a type,
362         // so build a dependent node to describe the type.
363         if (WantNontrivialTypeSourceInfo)
364           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
365 
366         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
367         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
368                                        II, NameLoc);
369         return ParsedType::make(T);
370       }
371 
372       return nullptr;
373     }
374 
375     if (!LookupCtx->isDependentContext() &&
376         RequireCompleteDeclContext(*SS, LookupCtx))
377       return nullptr;
378   }
379 
380   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
381   // lookup for class-names.
382   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
383                                       LookupOrdinaryName;
384   LookupResult Result(*this, &II, NameLoc, Kind);
385   if (LookupCtx) {
386     // Perform "qualified" name lookup into the declaration context we
387     // computed, which is either the type of the base of a member access
388     // expression or the declaration context associated with a prior
389     // nested-name-specifier.
390     LookupQualifiedName(Result, LookupCtx);
391 
392     if (ObjectTypePtr && Result.empty()) {
393       // C++ [basic.lookup.classref]p3:
394       //   If the unqualified-id is ~type-name, the type-name is looked up
395       //   in the context of the entire postfix-expression. If the type T of
396       //   the object expression is of a class type C, the type-name is also
397       //   looked up in the scope of class C. At least one of the lookups shall
398       //   find a name that refers to (possibly cv-qualified) T.
399       LookupName(Result, S);
400     }
401   } else {
402     // Perform unqualified name lookup.
403     LookupName(Result, S);
404 
405     // For unqualified lookup in a class template in MSVC mode, look into
406     // dependent base classes where the primary class template is known.
407     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
408       if (ParsedType TypeInBase =
409               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
410         return TypeInBase;
411     }
412   }
413 
414   NamedDecl *IIDecl = nullptr;
415   UsingShadowDecl *FoundUsingShadow = nullptr;
416   switch (Result.getResultKind()) {
417   case LookupResult::NotFound:
418   case LookupResult::NotFoundInCurrentInstantiation:
419     if (CorrectedII) {
420       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
421                                AllowDeducedTemplate);
422       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
423                                               S, SS, CCC, CTK_ErrorRecovery);
424       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
425       TemplateTy Template;
426       bool MemberOfUnknownSpecialization;
427       UnqualifiedId TemplateName;
428       TemplateName.setIdentifier(NewII, NameLoc);
429       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
430       CXXScopeSpec NewSS, *NewSSPtr = SS;
431       if (SS && NNS) {
432         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
433         NewSSPtr = &NewSS;
434       }
435       if (Correction && (NNS || NewII != &II) &&
436           // Ignore a correction to a template type as the to-be-corrected
437           // identifier is not a template (typo correction for template names
438           // is handled elsewhere).
439           !(getLangOpts().CPlusPlus && NewSSPtr &&
440             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
441                            Template, MemberOfUnknownSpecialization))) {
442         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
443                                     isClassName, HasTrailingDot, ObjectTypePtr,
444                                     IsCtorOrDtorName,
445                                     WantNontrivialTypeSourceInfo,
446                                     IsClassTemplateDeductionContext);
447         if (Ty) {
448           diagnoseTypo(Correction,
449                        PDiag(diag::err_unknown_type_or_class_name_suggest)
450                          << Result.getLookupName() << isClassName);
451           if (SS && NNS)
452             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
453           *CorrectedII = NewII;
454           return Ty;
455         }
456       }
457     }
458     // If typo correction failed or was not performed, fall through
459     LLVM_FALLTHROUGH;
460   case LookupResult::FoundOverloaded:
461   case LookupResult::FoundUnresolvedValue:
462     Result.suppressDiagnostics();
463     return nullptr;
464 
465   case LookupResult::Ambiguous:
466     // Recover from type-hiding ambiguities by hiding the type.  We'll
467     // do the lookup again when looking for an object, and we can
468     // diagnose the error then.  If we don't do this, then the error
469     // about hiding the type will be immediately followed by an error
470     // that only makes sense if the identifier was treated like a type.
471     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
472       Result.suppressDiagnostics();
473       return nullptr;
474     }
475 
476     // Look to see if we have a type anywhere in the list of results.
477     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
478          Res != ResEnd; ++Res) {
479       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
480       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
481               RealRes) ||
482           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
483         if (!IIDecl ||
484             // Make the selection of the recovery decl deterministic.
485             RealRes->getLocation() < IIDecl->getLocation()) {
486           IIDecl = RealRes;
487           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
488         }
489       }
490     }
491 
492     if (!IIDecl) {
493       // None of the entities we found is a type, so there is no way
494       // to even assume that the result is a type. In this case, don't
495       // complain about the ambiguity. The parser will either try to
496       // perform this lookup again (e.g., as an object name), which
497       // will produce the ambiguity, or will complain that it expected
498       // a type name.
499       Result.suppressDiagnostics();
500       return nullptr;
501     }
502 
503     // We found a type within the ambiguous lookup; diagnose the
504     // ambiguity and then return that type. This might be the right
505     // answer, or it might not be, but it suppresses any attempt to
506     // perform the name lookup again.
507     break;
508 
509   case LookupResult::Found:
510     IIDecl = Result.getFoundDecl();
511     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
512     break;
513   }
514 
515   assert(IIDecl && "Didn't find decl");
516 
517   QualType T;
518   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
519     // C++ [class.qual]p2: A lookup that would find the injected-class-name
520     // instead names the constructors of the class, except when naming a class.
521     // This is ill-formed when we're not actually forming a ctor or dtor name.
522     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
523     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
524     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
525         FoundRD->isInjectedClassName() &&
526         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
527       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
528           << &II << /*Type*/1;
529 
530     DiagnoseUseOfDecl(IIDecl, NameLoc);
531 
532     T = Context.getTypeDeclType(TD);
533     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
534   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
535     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
536     if (!HasTrailingDot)
537       T = Context.getObjCInterfaceType(IDecl);
538     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
539   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
540     (void)DiagnoseUseOfDecl(UD, NameLoc);
541     // Recover with 'int'
542     return ParsedType::make(Context.IntTy);
543   } else if (AllowDeducedTemplate) {
544     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
545       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
546       TemplateName Template =
547           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
548       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
549                                                        false);
550       // Don't wrap in a further UsingType.
551       FoundUsingShadow = nullptr;
552     }
553   }
554 
555   if (T.isNull()) {
556     // If it's not plausibly a type, suppress diagnostics.
557     Result.suppressDiagnostics();
558     return nullptr;
559   }
560 
561   if (FoundUsingShadow)
562     T = Context.getUsingType(FoundUsingShadow, T);
563 
564   return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
565 }
566 
567 // Builds a fake NNS for the given decl context.
568 static NestedNameSpecifier *
569 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
570   for (;; DC = DC->getLookupParent()) {
571     DC = DC->getPrimaryContext();
572     auto *ND = dyn_cast<NamespaceDecl>(DC);
573     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
574       return NestedNameSpecifier::Create(Context, nullptr, ND);
575     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
576       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577                                          RD->getTypeForDecl());
578     else if (isa<TranslationUnitDecl>(DC))
579       return NestedNameSpecifier::GlobalSpecifier(Context);
580   }
581   llvm_unreachable("something isn't in TU scope?");
582 }
583 
584 /// Find the parent class with dependent bases of the innermost enclosing method
585 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
586 /// up allowing unqualified dependent type names at class-level, which MSVC
587 /// correctly rejects.
588 static const CXXRecordDecl *
589 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
590   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
591     DC = DC->getPrimaryContext();
592     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
593       if (MD->getParent()->hasAnyDependentBases())
594         return MD->getParent();
595   }
596   return nullptr;
597 }
598 
599 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
600                                           SourceLocation NameLoc,
601                                           bool IsTemplateTypeArg) {
602   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
603 
604   NestedNameSpecifier *NNS = nullptr;
605   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
606     // If we weren't able to parse a default template argument, delay lookup
607     // until instantiation time by making a non-dependent DependentTypeName. We
608     // pretend we saw a NestedNameSpecifier referring to the current scope, and
609     // lookup is retried.
610     // FIXME: This hurts our diagnostic quality, since we get errors like "no
611     // type named 'Foo' in 'current_namespace'" when the user didn't write any
612     // name specifiers.
613     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
614     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
615   } else if (const CXXRecordDecl *RD =
616                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
617     // Build a DependentNameType that will perform lookup into RD at
618     // instantiation time.
619     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
620                                       RD->getTypeForDecl());
621 
622     // Diagnose that this identifier was undeclared, and retry the lookup during
623     // template instantiation.
624     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
625                                                                       << RD;
626   } else {
627     // This is not a situation that we should recover from.
628     return ParsedType();
629   }
630 
631   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
632 
633   // Build type location information.  We synthesized the qualifier, so we have
634   // to build a fake NestedNameSpecifierLoc.
635   NestedNameSpecifierLocBuilder NNSLocBuilder;
636   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
637   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
638 
639   TypeLocBuilder Builder;
640   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
641   DepTL.setNameLoc(NameLoc);
642   DepTL.setElaboratedKeywordLoc(SourceLocation());
643   DepTL.setQualifierLoc(QualifierLoc);
644   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
645 }
646 
647 /// isTagName() - This method is called *for error recovery purposes only*
648 /// to determine if the specified name is a valid tag name ("struct foo").  If
649 /// so, this returns the TST for the tag corresponding to it (TST_enum,
650 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
651 /// cases in C where the user forgot to specify the tag.
652 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
653   // Do a tag name lookup in this scope.
654   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
655   LookupName(R, S, false);
656   R.suppressDiagnostics();
657   if (R.getResultKind() == LookupResult::Found)
658     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
659       switch (TD->getTagKind()) {
660       case TTK_Struct: return DeclSpec::TST_struct;
661       case TTK_Interface: return DeclSpec::TST_interface;
662       case TTK_Union:  return DeclSpec::TST_union;
663       case TTK_Class:  return DeclSpec::TST_class;
664       case TTK_Enum:   return DeclSpec::TST_enum;
665       }
666     }
667 
668   return DeclSpec::TST_unspecified;
669 }
670 
671 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
672 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
673 /// then downgrade the missing typename error to a warning.
674 /// This is needed for MSVC compatibility; Example:
675 /// @code
676 /// template<class T> class A {
677 /// public:
678 ///   typedef int TYPE;
679 /// };
680 /// template<class T> class B : public A<T> {
681 /// public:
682 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
683 /// };
684 /// @endcode
685 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
686   if (CurContext->isRecord()) {
687     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
688       return true;
689 
690     const Type *Ty = SS->getScopeRep()->getAsType();
691 
692     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
693     for (const auto &Base : RD->bases())
694       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
695         return true;
696     return S->isFunctionPrototypeScope();
697   }
698   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
699 }
700 
701 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
702                                    SourceLocation IILoc,
703                                    Scope *S,
704                                    CXXScopeSpec *SS,
705                                    ParsedType &SuggestedType,
706                                    bool IsTemplateName) {
707   // Don't report typename errors for editor placeholders.
708   if (II->isEditorPlaceholder())
709     return;
710   // We don't have anything to suggest (yet).
711   SuggestedType = nullptr;
712 
713   // There may have been a typo in the name of the type. Look up typo
714   // results, in case we have something that we can suggest.
715   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
716                            /*AllowTemplates=*/IsTemplateName,
717                            /*AllowNonTemplates=*/!IsTemplateName);
718   if (TypoCorrection Corrected =
719           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
720                       CCC, CTK_ErrorRecovery)) {
721     // FIXME: Support error recovery for the template-name case.
722     bool CanRecover = !IsTemplateName;
723     if (Corrected.isKeyword()) {
724       // We corrected to a keyword.
725       diagnoseTypo(Corrected,
726                    PDiag(IsTemplateName ? diag::err_no_template_suggest
727                                         : diag::err_unknown_typename_suggest)
728                        << II);
729       II = Corrected.getCorrectionAsIdentifierInfo();
730     } else {
731       // We found a similarly-named type or interface; suggest that.
732       if (!SS || !SS->isSet()) {
733         diagnoseTypo(Corrected,
734                      PDiag(IsTemplateName ? diag::err_no_template_suggest
735                                           : diag::err_unknown_typename_suggest)
736                          << II, CanRecover);
737       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
738         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
739         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
740                                 II->getName().equals(CorrectedStr);
741         diagnoseTypo(Corrected,
742                      PDiag(IsTemplateName
743                                ? diag::err_no_member_template_suggest
744                                : diag::err_unknown_nested_typename_suggest)
745                          << II << DC << DroppedSpecifier << SS->getRange(),
746                      CanRecover);
747       } else {
748         llvm_unreachable("could not have corrected a typo here");
749       }
750 
751       if (!CanRecover)
752         return;
753 
754       CXXScopeSpec tmpSS;
755       if (Corrected.getCorrectionSpecifier())
756         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
757                           SourceRange(IILoc));
758       // FIXME: Support class template argument deduction here.
759       SuggestedType =
760           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
761                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
762                       /*IsCtorOrDtorName=*/false,
763                       /*WantNontrivialTypeSourceInfo=*/true);
764     }
765     return;
766   }
767 
768   if (getLangOpts().CPlusPlus && !IsTemplateName) {
769     // See if II is a class template that the user forgot to pass arguments to.
770     UnqualifiedId Name;
771     Name.setIdentifier(II, IILoc);
772     CXXScopeSpec EmptySS;
773     TemplateTy TemplateResult;
774     bool MemberOfUnknownSpecialization;
775     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
776                        Name, nullptr, true, TemplateResult,
777                        MemberOfUnknownSpecialization) == TNK_Type_template) {
778       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
779       return;
780     }
781   }
782 
783   // FIXME: Should we move the logic that tries to recover from a missing tag
784   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
785 
786   if (!SS || (!SS->isSet() && !SS->isInvalid()))
787     Diag(IILoc, IsTemplateName ? diag::err_no_template
788                                : diag::err_unknown_typename)
789         << II;
790   else if (DeclContext *DC = computeDeclContext(*SS, false))
791     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
792                                : diag::err_typename_nested_not_found)
793         << II << DC << SS->getRange();
794   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
795     SuggestedType =
796         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
797   } else if (isDependentScopeSpecifier(*SS)) {
798     unsigned DiagID = diag::err_typename_missing;
799     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
800       DiagID = diag::ext_typename_missing;
801 
802     Diag(SS->getRange().getBegin(), DiagID)
803       << SS->getScopeRep() << II->getName()
804       << SourceRange(SS->getRange().getBegin(), IILoc)
805       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
806     SuggestedType = ActOnTypenameType(S, SourceLocation(),
807                                       *SS, *II, IILoc).get();
808   } else {
809     assert(SS && SS->isInvalid() &&
810            "Invalid scope specifier has already been diagnosed");
811   }
812 }
813 
814 /// Determine whether the given result set contains either a type name
815 /// or
816 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
817   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
818                        NextToken.is(tok::less);
819 
820   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
821     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
822       return true;
823 
824     if (CheckTemplate && isa<TemplateDecl>(*I))
825       return true;
826   }
827 
828   return false;
829 }
830 
831 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
832                                     Scope *S, CXXScopeSpec &SS,
833                                     IdentifierInfo *&Name,
834                                     SourceLocation NameLoc) {
835   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
836   SemaRef.LookupParsedName(R, S, &SS);
837   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
838     StringRef FixItTagName;
839     switch (Tag->getTagKind()) {
840       case TTK_Class:
841         FixItTagName = "class ";
842         break;
843 
844       case TTK_Enum:
845         FixItTagName = "enum ";
846         break;
847 
848       case TTK_Struct:
849         FixItTagName = "struct ";
850         break;
851 
852       case TTK_Interface:
853         FixItTagName = "__interface ";
854         break;
855 
856       case TTK_Union:
857         FixItTagName = "union ";
858         break;
859     }
860 
861     StringRef TagName = FixItTagName.drop_back();
862     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
863       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
864       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
865 
866     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
867          I != IEnd; ++I)
868       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
869         << Name << TagName;
870 
871     // Replace lookup results with just the tag decl.
872     Result.clear(Sema::LookupTagName);
873     SemaRef.LookupParsedName(Result, S, &SS);
874     return true;
875   }
876 
877   return false;
878 }
879 
880 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
881                                             IdentifierInfo *&Name,
882                                             SourceLocation NameLoc,
883                                             const Token &NextToken,
884                                             CorrectionCandidateCallback *CCC) {
885   DeclarationNameInfo NameInfo(Name, NameLoc);
886   ObjCMethodDecl *CurMethod = getCurMethodDecl();
887 
888   assert(NextToken.isNot(tok::coloncolon) &&
889          "parse nested name specifiers before calling ClassifyName");
890   if (getLangOpts().CPlusPlus && SS.isSet() &&
891       isCurrentClassName(*Name, S, &SS)) {
892     // Per [class.qual]p2, this names the constructors of SS, not the
893     // injected-class-name. We don't have a classification for that.
894     // There's not much point caching this result, since the parser
895     // will reject it later.
896     return NameClassification::Unknown();
897   }
898 
899   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
900   LookupParsedName(Result, S, &SS, !CurMethod);
901 
902   if (SS.isInvalid())
903     return NameClassification::Error();
904 
905   // For unqualified lookup in a class template in MSVC mode, look into
906   // dependent base classes where the primary class template is known.
907   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
908     if (ParsedType TypeInBase =
909             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
910       return TypeInBase;
911   }
912 
913   // Perform lookup for Objective-C instance variables (including automatically
914   // synthesized instance variables), if we're in an Objective-C method.
915   // FIXME: This lookup really, really needs to be folded in to the normal
916   // unqualified lookup mechanism.
917   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
918     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
919     if (Ivar.isInvalid())
920       return NameClassification::Error();
921     if (Ivar.isUsable())
922       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
923 
924     // We defer builtin creation until after ivar lookup inside ObjC methods.
925     if (Result.empty())
926       LookupBuiltin(Result);
927   }
928 
929   bool SecondTry = false;
930   bool IsFilteredTemplateName = false;
931 
932 Corrected:
933   switch (Result.getResultKind()) {
934   case LookupResult::NotFound:
935     // If an unqualified-id is followed by a '(', then we have a function
936     // call.
937     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
938       // In C++, this is an ADL-only call.
939       // FIXME: Reference?
940       if (getLangOpts().CPlusPlus)
941         return NameClassification::UndeclaredNonType();
942 
943       // C90 6.3.2.2:
944       //   If the expression that precedes the parenthesized argument list in a
945       //   function call consists solely of an identifier, and if no
946       //   declaration is visible for this identifier, the identifier is
947       //   implicitly declared exactly as if, in the innermost block containing
948       //   the function call, the declaration
949       //
950       //     extern int identifier ();
951       //
952       //   appeared.
953       //
954       // We also allow this in C99 as an extension. However, this is not
955       // allowed in all language modes as functions without prototypes may not
956       // be supported.
957       if (getLangOpts().implicitFunctionsAllowed()) {
958         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
959           return NameClassification::NonType(D);
960       }
961     }
962 
963     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
964       // In C++20 onwards, this could be an ADL-only call to a function
965       // template, and we're required to assume that this is a template name.
966       //
967       // FIXME: Find a way to still do typo correction in this case.
968       TemplateName Template =
969           Context.getAssumedTemplateName(NameInfo.getName());
970       return NameClassification::UndeclaredTemplate(Template);
971     }
972 
973     // In C, we first see whether there is a tag type by the same name, in
974     // which case it's likely that the user just forgot to write "enum",
975     // "struct", or "union".
976     if (!getLangOpts().CPlusPlus && !SecondTry &&
977         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
978       break;
979     }
980 
981     // Perform typo correction to determine if there is another name that is
982     // close to this name.
983     if (!SecondTry && CCC) {
984       SecondTry = true;
985       if (TypoCorrection Corrected =
986               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
987                           &SS, *CCC, CTK_ErrorRecovery)) {
988         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
989         unsigned QualifiedDiag = diag::err_no_member_suggest;
990 
991         NamedDecl *FirstDecl = Corrected.getFoundDecl();
992         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
993         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
994             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
995           UnqualifiedDiag = diag::err_no_template_suggest;
996           QualifiedDiag = diag::err_no_member_template_suggest;
997         } else if (UnderlyingFirstDecl &&
998                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
999                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1000                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1001           UnqualifiedDiag = diag::err_unknown_typename_suggest;
1002           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1003         }
1004 
1005         if (SS.isEmpty()) {
1006           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1007         } else {// FIXME: is this even reachable? Test it.
1008           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1009           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1010                                   Name->getName().equals(CorrectedStr);
1011           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1012                                     << Name << computeDeclContext(SS, false)
1013                                     << DroppedSpecifier << SS.getRange());
1014         }
1015 
1016         // Update the name, so that the caller has the new name.
1017         Name = Corrected.getCorrectionAsIdentifierInfo();
1018 
1019         // Typo correction corrected to a keyword.
1020         if (Corrected.isKeyword())
1021           return Name;
1022 
1023         // Also update the LookupResult...
1024         // FIXME: This should probably go away at some point
1025         Result.clear();
1026         Result.setLookupName(Corrected.getCorrection());
1027         if (FirstDecl)
1028           Result.addDecl(FirstDecl);
1029 
1030         // If we found an Objective-C instance variable, let
1031         // LookupInObjCMethod build the appropriate expression to
1032         // reference the ivar.
1033         // FIXME: This is a gross hack.
1034         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1035           DeclResult R =
1036               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1037           if (R.isInvalid())
1038             return NameClassification::Error();
1039           if (R.isUsable())
1040             return NameClassification::NonType(Ivar);
1041         }
1042 
1043         goto Corrected;
1044       }
1045     }
1046 
1047     // We failed to correct; just fall through and let the parser deal with it.
1048     Result.suppressDiagnostics();
1049     return NameClassification::Unknown();
1050 
1051   case LookupResult::NotFoundInCurrentInstantiation: {
1052     // We performed name lookup into the current instantiation, and there were
1053     // dependent bases, so we treat this result the same way as any other
1054     // dependent nested-name-specifier.
1055 
1056     // C++ [temp.res]p2:
1057     //   A name used in a template declaration or definition and that is
1058     //   dependent on a template-parameter is assumed not to name a type
1059     //   unless the applicable name lookup finds a type name or the name is
1060     //   qualified by the keyword typename.
1061     //
1062     // FIXME: If the next token is '<', we might want to ask the parser to
1063     // perform some heroics to see if we actually have a
1064     // template-argument-list, which would indicate a missing 'template'
1065     // keyword here.
1066     return NameClassification::DependentNonType();
1067   }
1068 
1069   case LookupResult::Found:
1070   case LookupResult::FoundOverloaded:
1071   case LookupResult::FoundUnresolvedValue:
1072     break;
1073 
1074   case LookupResult::Ambiguous:
1075     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1077                                       /*AllowDependent=*/false)) {
1078       // C++ [temp.local]p3:
1079       //   A lookup that finds an injected-class-name (10.2) can result in an
1080       //   ambiguity in certain cases (for example, if it is found in more than
1081       //   one base class). If all of the injected-class-names that are found
1082       //   refer to specializations of the same class template, and if the name
1083       //   is followed by a template-argument-list, the reference refers to the
1084       //   class template itself and not a specialization thereof, and is not
1085       //   ambiguous.
1086       //
1087       // This filtering can make an ambiguous result into an unambiguous one,
1088       // so try again after filtering out template names.
1089       FilterAcceptableTemplateNames(Result);
1090       if (!Result.isAmbiguous()) {
1091         IsFilteredTemplateName = true;
1092         break;
1093       }
1094     }
1095 
1096     // Diagnose the ambiguity and return an error.
1097     return NameClassification::Error();
1098   }
1099 
1100   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1101       (IsFilteredTemplateName ||
1102        hasAnyAcceptableTemplateNames(
1103            Result, /*AllowFunctionTemplates=*/true,
1104            /*AllowDependent=*/false,
1105            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1106                getLangOpts().CPlusPlus20))) {
1107     // C++ [temp.names]p3:
1108     //   After name lookup (3.4) finds that a name is a template-name or that
1109     //   an operator-function-id or a literal- operator-id refers to a set of
1110     //   overloaded functions any member of which is a function template if
1111     //   this is followed by a <, the < is always taken as the delimiter of a
1112     //   template-argument-list and never as the less-than operator.
1113     // C++2a [temp.names]p2:
1114     //   A name is also considered to refer to a template if it is an
1115     //   unqualified-id followed by a < and name lookup finds either one
1116     //   or more functions or finds nothing.
1117     if (!IsFilteredTemplateName)
1118       FilterAcceptableTemplateNames(Result);
1119 
1120     bool IsFunctionTemplate;
1121     bool IsVarTemplate;
1122     TemplateName Template;
1123     if (Result.end() - Result.begin() > 1) {
1124       IsFunctionTemplate = true;
1125       Template = Context.getOverloadedTemplateName(Result.begin(),
1126                                                    Result.end());
1127     } else if (!Result.empty()) {
1128       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1129           *Result.begin(), /*AllowFunctionTemplates=*/true,
1130           /*AllowDependent=*/false));
1131       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1132       IsVarTemplate = isa<VarTemplateDecl>(TD);
1133 
1134       UsingShadowDecl *FoundUsingShadow =
1135           dyn_cast<UsingShadowDecl>(*Result.begin());
1136       assert(!FoundUsingShadow ||
1137              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1138       Template =
1139           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1140       if (SS.isNotEmpty())
1141         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1142                                                     /*TemplateKeyword=*/false,
1143                                                     Template);
1144     } else {
1145       // All results were non-template functions. This is a function template
1146       // name.
1147       IsFunctionTemplate = true;
1148       Template = Context.getAssumedTemplateName(NameInfo.getName());
1149     }
1150 
1151     if (IsFunctionTemplate) {
1152       // Function templates always go through overload resolution, at which
1153       // point we'll perform the various checks (e.g., accessibility) we need
1154       // to based on which function we selected.
1155       Result.suppressDiagnostics();
1156 
1157       return NameClassification::FunctionTemplate(Template);
1158     }
1159 
1160     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1161                          : NameClassification::TypeTemplate(Template);
1162   }
1163 
1164   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1165     QualType T = Context.getTypeDeclType(Type);
1166     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1167       T = Context.getUsingType(USD, T);
1168     return buildNamedType(*this, &SS, T, NameLoc);
1169   };
1170 
1171   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1172   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1173     DiagnoseUseOfDecl(Type, NameLoc);
1174     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1175     return BuildTypeFor(Type, *Result.begin());
1176   }
1177 
1178   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1179   if (!Class) {
1180     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1181     if (ObjCCompatibleAliasDecl *Alias =
1182             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1183       Class = Alias->getClassInterface();
1184   }
1185 
1186   if (Class) {
1187     DiagnoseUseOfDecl(Class, NameLoc);
1188 
1189     if (NextToken.is(tok::period)) {
1190       // Interface. <something> is parsed as a property reference expression.
1191       // Just return "unknown" as a fall-through for now.
1192       Result.suppressDiagnostics();
1193       return NameClassification::Unknown();
1194     }
1195 
1196     QualType T = Context.getObjCInterfaceType(Class);
1197     return ParsedType::make(T);
1198   }
1199 
1200   if (isa<ConceptDecl>(FirstDecl))
1201     return NameClassification::Concept(
1202         TemplateName(cast<TemplateDecl>(FirstDecl)));
1203 
1204   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1205     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1206     return NameClassification::Error();
1207   }
1208 
1209   // We can have a type template here if we're classifying a template argument.
1210   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1211       !isa<VarTemplateDecl>(FirstDecl))
1212     return NameClassification::TypeTemplate(
1213         TemplateName(cast<TemplateDecl>(FirstDecl)));
1214 
1215   // Check for a tag type hidden by a non-type decl in a few cases where it
1216   // seems likely a type is wanted instead of the non-type that was found.
1217   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1218   if ((NextToken.is(tok::identifier) ||
1219        (NextIsOp &&
1220         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1221       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1222     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1223     DiagnoseUseOfDecl(Type, NameLoc);
1224     return BuildTypeFor(Type, *Result.begin());
1225   }
1226 
1227   // If we already know which single declaration is referenced, just annotate
1228   // that declaration directly. Defer resolving even non-overloaded class
1229   // member accesses, as we need to defer certain access checks until we know
1230   // the context.
1231   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1232   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1233     return NameClassification::NonType(Result.getRepresentativeDecl());
1234 
1235   // Otherwise, this is an overload set that we will need to resolve later.
1236   Result.suppressDiagnostics();
1237   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1238       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1239       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1240       Result.begin(), Result.end()));
1241 }
1242 
1243 ExprResult
1244 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1245                                              SourceLocation NameLoc) {
1246   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1247   CXXScopeSpec SS;
1248   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1249   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1250 }
1251 
1252 ExprResult
1253 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1254                                             IdentifierInfo *Name,
1255                                             SourceLocation NameLoc,
1256                                             bool IsAddressOfOperand) {
1257   DeclarationNameInfo NameInfo(Name, NameLoc);
1258   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1259                                     NameInfo, IsAddressOfOperand,
1260                                     /*TemplateArgs=*/nullptr);
1261 }
1262 
1263 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1264                                               NamedDecl *Found,
1265                                               SourceLocation NameLoc,
1266                                               const Token &NextToken) {
1267   if (getCurMethodDecl() && SS.isEmpty())
1268     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1269       return BuildIvarRefExpr(S, NameLoc, Ivar);
1270 
1271   // Reconstruct the lookup result.
1272   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1273   Result.addDecl(Found);
1274   Result.resolveKind();
1275 
1276   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1277   return BuildDeclarationNameExpr(SS, Result, ADL);
1278 }
1279 
1280 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1281   // For an implicit class member access, transform the result into a member
1282   // access expression if necessary.
1283   auto *ULE = cast<UnresolvedLookupExpr>(E);
1284   if ((*ULE->decls_begin())->isCXXClassMember()) {
1285     CXXScopeSpec SS;
1286     SS.Adopt(ULE->getQualifierLoc());
1287 
1288     // Reconstruct the lookup result.
1289     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1290                         LookupOrdinaryName);
1291     Result.setNamingClass(ULE->getNamingClass());
1292     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1293       Result.addDecl(*I, I.getAccess());
1294     Result.resolveKind();
1295     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1296                                            nullptr, S);
1297   }
1298 
1299   // Otherwise, this is already in the form we needed, and no further checks
1300   // are necessary.
1301   return ULE;
1302 }
1303 
1304 Sema::TemplateNameKindForDiagnostics
1305 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1306   auto *TD = Name.getAsTemplateDecl();
1307   if (!TD)
1308     return TemplateNameKindForDiagnostics::DependentTemplate;
1309   if (isa<ClassTemplateDecl>(TD))
1310     return TemplateNameKindForDiagnostics::ClassTemplate;
1311   if (isa<FunctionTemplateDecl>(TD))
1312     return TemplateNameKindForDiagnostics::FunctionTemplate;
1313   if (isa<VarTemplateDecl>(TD))
1314     return TemplateNameKindForDiagnostics::VarTemplate;
1315   if (isa<TypeAliasTemplateDecl>(TD))
1316     return TemplateNameKindForDiagnostics::AliasTemplate;
1317   if (isa<TemplateTemplateParmDecl>(TD))
1318     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1319   if (isa<ConceptDecl>(TD))
1320     return TemplateNameKindForDiagnostics::Concept;
1321   return TemplateNameKindForDiagnostics::DependentTemplate;
1322 }
1323 
1324 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1325   assert(DC->getLexicalParent() == CurContext &&
1326       "The next DeclContext should be lexically contained in the current one.");
1327   CurContext = DC;
1328   S->setEntity(DC);
1329 }
1330 
1331 void Sema::PopDeclContext() {
1332   assert(CurContext && "DeclContext imbalance!");
1333 
1334   CurContext = CurContext->getLexicalParent();
1335   assert(CurContext && "Popped translation unit!");
1336 }
1337 
1338 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1339                                                                     Decl *D) {
1340   // Unlike PushDeclContext, the context to which we return is not necessarily
1341   // the containing DC of TD, because the new context will be some pre-existing
1342   // TagDecl definition instead of a fresh one.
1343   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1344   CurContext = cast<TagDecl>(D)->getDefinition();
1345   assert(CurContext && "skipping definition of undefined tag");
1346   // Start lookups from the parent of the current context; we don't want to look
1347   // into the pre-existing complete definition.
1348   S->setEntity(CurContext->getLookupParent());
1349   return Result;
1350 }
1351 
1352 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1353   CurContext = static_cast<decltype(CurContext)>(Context);
1354 }
1355 
1356 /// EnterDeclaratorContext - Used when we must lookup names in the context
1357 /// of a declarator's nested name specifier.
1358 ///
1359 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1360   // C++0x [basic.lookup.unqual]p13:
1361   //   A name used in the definition of a static data member of class
1362   //   X (after the qualified-id of the static member) is looked up as
1363   //   if the name was used in a member function of X.
1364   // C++0x [basic.lookup.unqual]p14:
1365   //   If a variable member of a namespace is defined outside of the
1366   //   scope of its namespace then any name used in the definition of
1367   //   the variable member (after the declarator-id) is looked up as
1368   //   if the definition of the variable member occurred in its
1369   //   namespace.
1370   // Both of these imply that we should push a scope whose context
1371   // is the semantic context of the declaration.  We can't use
1372   // PushDeclContext here because that context is not necessarily
1373   // lexically contained in the current context.  Fortunately,
1374   // the containing scope should have the appropriate information.
1375 
1376   assert(!S->getEntity() && "scope already has entity");
1377 
1378 #ifndef NDEBUG
1379   Scope *Ancestor = S->getParent();
1380   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1381   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1382 #endif
1383 
1384   CurContext = DC;
1385   S->setEntity(DC);
1386 
1387   if (S->getParent()->isTemplateParamScope()) {
1388     // Also set the corresponding entities for all immediately-enclosing
1389     // template parameter scopes.
1390     EnterTemplatedContext(S->getParent(), DC);
1391   }
1392 }
1393 
1394 void Sema::ExitDeclaratorContext(Scope *S) {
1395   assert(S->getEntity() == CurContext && "Context imbalance!");
1396 
1397   // Switch back to the lexical context.  The safety of this is
1398   // enforced by an assert in EnterDeclaratorContext.
1399   Scope *Ancestor = S->getParent();
1400   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1401   CurContext = Ancestor->getEntity();
1402 
1403   // We don't need to do anything with the scope, which is going to
1404   // disappear.
1405 }
1406 
1407 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1408   assert(S->isTemplateParamScope() &&
1409          "expected to be initializing a template parameter scope");
1410 
1411   // C++20 [temp.local]p7:
1412   //   In the definition of a member of a class template that appears outside
1413   //   of the class template definition, the name of a member of the class
1414   //   template hides the name of a template-parameter of any enclosing class
1415   //   templates (but not a template-parameter of the member if the member is a
1416   //   class or function template).
1417   // C++20 [temp.local]p9:
1418   //   In the definition of a class template or in the definition of a member
1419   //   of such a template that appears outside of the template definition, for
1420   //   each non-dependent base class (13.8.2.1), if the name of the base class
1421   //   or the name of a member of the base class is the same as the name of a
1422   //   template-parameter, the base class name or member name hides the
1423   //   template-parameter name (6.4.10).
1424   //
1425   // This means that a template parameter scope should be searched immediately
1426   // after searching the DeclContext for which it is a template parameter
1427   // scope. For example, for
1428   //   template<typename T> template<typename U> template<typename V>
1429   //     void N::A<T>::B<U>::f(...)
1430   // we search V then B<U> (and base classes) then U then A<T> (and base
1431   // classes) then T then N then ::.
1432   unsigned ScopeDepth = getTemplateDepth(S);
1433   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1434     DeclContext *SearchDCAfterScope = DC;
1435     for (; DC; DC = DC->getLookupParent()) {
1436       if (const TemplateParameterList *TPL =
1437               cast<Decl>(DC)->getDescribedTemplateParams()) {
1438         unsigned DCDepth = TPL->getDepth() + 1;
1439         if (DCDepth > ScopeDepth)
1440           continue;
1441         if (ScopeDepth == DCDepth)
1442           SearchDCAfterScope = DC = DC->getLookupParent();
1443         break;
1444       }
1445     }
1446     S->setLookupEntity(SearchDCAfterScope);
1447   }
1448 }
1449 
1450 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1451   // We assume that the caller has already called
1452   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1453   FunctionDecl *FD = D->getAsFunction();
1454   if (!FD)
1455     return;
1456 
1457   // Same implementation as PushDeclContext, but enters the context
1458   // from the lexical parent, rather than the top-level class.
1459   assert(CurContext == FD->getLexicalParent() &&
1460     "The next DeclContext should be lexically contained in the current one.");
1461   CurContext = FD;
1462   S->setEntity(CurContext);
1463 
1464   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1465     ParmVarDecl *Param = FD->getParamDecl(P);
1466     // If the parameter has an identifier, then add it to the scope
1467     if (Param->getIdentifier()) {
1468       S->AddDecl(Param);
1469       IdResolver.AddDecl(Param);
1470     }
1471   }
1472 }
1473 
1474 void Sema::ActOnExitFunctionContext() {
1475   // Same implementation as PopDeclContext, but returns to the lexical parent,
1476   // rather than the top-level class.
1477   assert(CurContext && "DeclContext imbalance!");
1478   CurContext = CurContext->getLexicalParent();
1479   assert(CurContext && "Popped translation unit!");
1480 }
1481 
1482 /// Determine whether overloading is allowed for a new function
1483 /// declaration considering prior declarations of the same name.
1484 ///
1485 /// This routine determines whether overloading is possible, not
1486 /// whether a new declaration actually overloads a previous one.
1487 /// It will return true in C++ (where overloads are alway permitted)
1488 /// or, as a C extension, when either the new declaration or a
1489 /// previous one is declared with the 'overloadable' attribute.
1490 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1491                                        ASTContext &Context,
1492                                        const FunctionDecl *New) {
1493   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1494     return true;
1495 
1496   // Multiversion function declarations are not overloads in the
1497   // usual sense of that term, but lookup will report that an
1498   // overload set was found if more than one multiversion function
1499   // declaration is present for the same name. It is therefore
1500   // inadequate to assume that some prior declaration(s) had
1501   // the overloadable attribute; checking is required. Since one
1502   // declaration is permitted to omit the attribute, it is necessary
1503   // to check at least two; hence the 'any_of' check below. Note that
1504   // the overloadable attribute is implicitly added to declarations
1505   // that were required to have it but did not.
1506   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1507     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1508       return ND->hasAttr<OverloadableAttr>();
1509     });
1510   } else if (Previous.getResultKind() == LookupResult::Found)
1511     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1512 
1513   return false;
1514 }
1515 
1516 /// Add this decl to the scope shadowed decl chains.
1517 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1518   // Move up the scope chain until we find the nearest enclosing
1519   // non-transparent context. The declaration will be introduced into this
1520   // scope.
1521   while (S->getEntity() && S->getEntity()->isTransparentContext())
1522     S = S->getParent();
1523 
1524   // Add scoped declarations into their context, so that they can be
1525   // found later. Declarations without a context won't be inserted
1526   // into any context.
1527   if (AddToContext)
1528     CurContext->addDecl(D);
1529 
1530   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1531   // are function-local declarations.
1532   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1533     return;
1534 
1535   // Template instantiations should also not be pushed into scope.
1536   if (isa<FunctionDecl>(D) &&
1537       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1538     return;
1539 
1540   // If this replaces anything in the current scope,
1541   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1542                                IEnd = IdResolver.end();
1543   for (; I != IEnd; ++I) {
1544     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1545       S->RemoveDecl(*I);
1546       IdResolver.RemoveDecl(*I);
1547 
1548       // Should only need to replace one decl.
1549       break;
1550     }
1551   }
1552 
1553   S->AddDecl(D);
1554 
1555   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1556     // Implicitly-generated labels may end up getting generated in an order that
1557     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1558     // the label at the appropriate place in the identifier chain.
1559     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1560       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1561       if (IDC == CurContext) {
1562         if (!S->isDeclScope(*I))
1563           continue;
1564       } else if (IDC->Encloses(CurContext))
1565         break;
1566     }
1567 
1568     IdResolver.InsertDeclAfter(I, D);
1569   } else {
1570     IdResolver.AddDecl(D);
1571   }
1572   warnOnReservedIdentifier(D);
1573 }
1574 
1575 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1576                          bool AllowInlineNamespace) {
1577   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1578 }
1579 
1580 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1581   DeclContext *TargetDC = DC->getPrimaryContext();
1582   do {
1583     if (DeclContext *ScopeDC = S->getEntity())
1584       if (ScopeDC->getPrimaryContext() == TargetDC)
1585         return S;
1586   } while ((S = S->getParent()));
1587 
1588   return nullptr;
1589 }
1590 
1591 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1592                                             DeclContext*,
1593                                             ASTContext&);
1594 
1595 /// Filters out lookup results that don't fall within the given scope
1596 /// as determined by isDeclInScope.
1597 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1598                                 bool ConsiderLinkage,
1599                                 bool AllowInlineNamespace) {
1600   LookupResult::Filter F = R.makeFilter();
1601   while (F.hasNext()) {
1602     NamedDecl *D = F.next();
1603 
1604     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1605       continue;
1606 
1607     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1608       continue;
1609 
1610     F.erase();
1611   }
1612 
1613   F.done();
1614 }
1615 
1616 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1617 /// have compatible owning modules.
1618 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1619   // [module.interface]p7:
1620   // A declaration is attached to a module as follows:
1621   // - If the declaration is a non-dependent friend declaration that nominates a
1622   // function with a declarator-id that is a qualified-id or template-id or that
1623   // nominates a class other than with an elaborated-type-specifier with neither
1624   // a nested-name-specifier nor a simple-template-id, it is attached to the
1625   // module to which the friend is attached ([basic.link]).
1626   if (New->getFriendObjectKind() &&
1627       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1628     New->setLocalOwningModule(Old->getOwningModule());
1629     makeMergedDefinitionVisible(New);
1630     return false;
1631   }
1632 
1633   Module *NewM = New->getOwningModule();
1634   Module *OldM = Old->getOwningModule();
1635 
1636   if (NewM && NewM->isPrivateModule())
1637     NewM = NewM->Parent;
1638   if (OldM && OldM->isPrivateModule())
1639     OldM = OldM->Parent;
1640 
1641   if (NewM == OldM)
1642     return false;
1643 
1644   // Partitions are part of the module, but a partition could import another
1645   // module, so verify that the PMIs agree.
1646   if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition()))
1647     return NewM->getPrimaryModuleInterfaceName() ==
1648            OldM->getPrimaryModuleInterfaceName();
1649 
1650   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1651   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1652   if (NewIsModuleInterface || OldIsModuleInterface) {
1653     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1654     //   if a declaration of D [...] appears in the purview of a module, all
1655     //   other such declarations shall appear in the purview of the same module
1656     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1657       << New
1658       << NewIsModuleInterface
1659       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1660       << OldIsModuleInterface
1661       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1662     Diag(Old->getLocation(), diag::note_previous_declaration);
1663     New->setInvalidDecl();
1664     return true;
1665   }
1666 
1667   return false;
1668 }
1669 
1670 // [module.interface]p6:
1671 // A redeclaration of an entity X is implicitly exported if X was introduced by
1672 // an exported declaration; otherwise it shall not be exported.
1673 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1674   // [module.interface]p1:
1675   // An export-declaration shall inhabit a namespace scope.
1676   //
1677   // So it is meaningless to talk about redeclaration which is not at namespace
1678   // scope.
1679   if (!New->getLexicalDeclContext()
1680            ->getNonTransparentContext()
1681            ->isFileContext() ||
1682       !Old->getLexicalDeclContext()
1683            ->getNonTransparentContext()
1684            ->isFileContext())
1685     return false;
1686 
1687   bool IsNewExported = New->isInExportDeclContext();
1688   bool IsOldExported = Old->isInExportDeclContext();
1689 
1690   // It should be irrevelant if both of them are not exported.
1691   if (!IsNewExported && !IsOldExported)
1692     return false;
1693 
1694   if (IsOldExported)
1695     return false;
1696 
1697   assert(IsNewExported);
1698 
1699   auto Lk = Old->getFormalLinkage();
1700   int S = 0;
1701   if (Lk == Linkage::InternalLinkage)
1702     S = 1;
1703   else if (Lk == Linkage::ModuleLinkage)
1704     S = 2;
1705   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1706   Diag(Old->getLocation(), diag::note_previous_declaration);
1707   return true;
1708 }
1709 
1710 // A wrapper function for checking the semantic restrictions of
1711 // a redeclaration within a module.
1712 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1713   if (CheckRedeclarationModuleOwnership(New, Old))
1714     return true;
1715 
1716   if (CheckRedeclarationExported(New, Old))
1717     return true;
1718 
1719   return false;
1720 }
1721 
1722 static bool isUsingDecl(NamedDecl *D) {
1723   return isa<UsingShadowDecl>(D) ||
1724          isa<UnresolvedUsingTypenameDecl>(D) ||
1725          isa<UnresolvedUsingValueDecl>(D);
1726 }
1727 
1728 /// Removes using shadow declarations from the lookup results.
1729 static void RemoveUsingDecls(LookupResult &R) {
1730   LookupResult::Filter F = R.makeFilter();
1731   while (F.hasNext())
1732     if (isUsingDecl(F.next()))
1733       F.erase();
1734 
1735   F.done();
1736 }
1737 
1738 /// Check for this common pattern:
1739 /// @code
1740 /// class S {
1741 ///   S(const S&); // DO NOT IMPLEMENT
1742 ///   void operator=(const S&); // DO NOT IMPLEMENT
1743 /// };
1744 /// @endcode
1745 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1746   // FIXME: Should check for private access too but access is set after we get
1747   // the decl here.
1748   if (D->doesThisDeclarationHaveABody())
1749     return false;
1750 
1751   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1752     return CD->isCopyConstructor();
1753   return D->isCopyAssignmentOperator();
1754 }
1755 
1756 // We need this to handle
1757 //
1758 // typedef struct {
1759 //   void *foo() { return 0; }
1760 // } A;
1761 //
1762 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1763 // for example. If 'A', foo will have external linkage. If we have '*A',
1764 // foo will have no linkage. Since we can't know until we get to the end
1765 // of the typedef, this function finds out if D might have non-external linkage.
1766 // Callers should verify at the end of the TU if it D has external linkage or
1767 // not.
1768 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1769   const DeclContext *DC = D->getDeclContext();
1770   while (!DC->isTranslationUnit()) {
1771     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1772       if (!RD->hasNameForLinkage())
1773         return true;
1774     }
1775     DC = DC->getParent();
1776   }
1777 
1778   return !D->isExternallyVisible();
1779 }
1780 
1781 // FIXME: This needs to be refactored; some other isInMainFile users want
1782 // these semantics.
1783 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1784   if (S.TUKind != TU_Complete)
1785     return false;
1786   return S.SourceMgr.isInMainFile(Loc);
1787 }
1788 
1789 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1790   assert(D);
1791 
1792   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1793     return false;
1794 
1795   // Ignore all entities declared within templates, and out-of-line definitions
1796   // of members of class templates.
1797   if (D->getDeclContext()->isDependentContext() ||
1798       D->getLexicalDeclContext()->isDependentContext())
1799     return false;
1800 
1801   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1802     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1803       return false;
1804     // A non-out-of-line declaration of a member specialization was implicitly
1805     // instantiated; it's the out-of-line declaration that we're interested in.
1806     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1807         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1808       return false;
1809 
1810     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1811       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1812         return false;
1813     } else {
1814       // 'static inline' functions are defined in headers; don't warn.
1815       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1816         return false;
1817     }
1818 
1819     if (FD->doesThisDeclarationHaveABody() &&
1820         Context.DeclMustBeEmitted(FD))
1821       return false;
1822   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1823     // Constants and utility variables are defined in headers with internal
1824     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1825     // like "inline".)
1826     if (!isMainFileLoc(*this, VD->getLocation()))
1827       return false;
1828 
1829     if (Context.DeclMustBeEmitted(VD))
1830       return false;
1831 
1832     if (VD->isStaticDataMember() &&
1833         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1834       return false;
1835     if (VD->isStaticDataMember() &&
1836         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1837         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1838       return false;
1839 
1840     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1841       return false;
1842   } else {
1843     return false;
1844   }
1845 
1846   // Only warn for unused decls internal to the translation unit.
1847   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1848   // for inline functions defined in the main source file, for instance.
1849   return mightHaveNonExternalLinkage(D);
1850 }
1851 
1852 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1853   if (!D)
1854     return;
1855 
1856   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1857     const FunctionDecl *First = FD->getFirstDecl();
1858     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1859       return; // First should already be in the vector.
1860   }
1861 
1862   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1863     const VarDecl *First = VD->getFirstDecl();
1864     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1865       return; // First should already be in the vector.
1866   }
1867 
1868   if (ShouldWarnIfUnusedFileScopedDecl(D))
1869     UnusedFileScopedDecls.push_back(D);
1870 }
1871 
1872 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1873   if (D->isInvalidDecl())
1874     return false;
1875 
1876   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1877     // For a decomposition declaration, warn if none of the bindings are
1878     // referenced, instead of if the variable itself is referenced (which
1879     // it is, by the bindings' expressions).
1880     for (auto *BD : DD->bindings())
1881       if (BD->isReferenced())
1882         return false;
1883   } else if (!D->getDeclName()) {
1884     return false;
1885   } else if (D->isReferenced() || D->isUsed()) {
1886     return false;
1887   }
1888 
1889   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1890     return false;
1891 
1892   if (isa<LabelDecl>(D))
1893     return true;
1894 
1895   // Except for labels, we only care about unused decls that are local to
1896   // functions.
1897   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1898   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1899     // For dependent types, the diagnostic is deferred.
1900     WithinFunction =
1901         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1902   if (!WithinFunction)
1903     return false;
1904 
1905   if (isa<TypedefNameDecl>(D))
1906     return true;
1907 
1908   // White-list anything that isn't a local variable.
1909   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1910     return false;
1911 
1912   // Types of valid local variables should be complete, so this should succeed.
1913   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1914 
1915     const Expr *Init = VD->getInit();
1916     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1917       Init = Cleanups->getSubExpr();
1918 
1919     const auto *Ty = VD->getType().getTypePtr();
1920 
1921     // Only look at the outermost level of typedef.
1922     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1923       // Allow anything marked with __attribute__((unused)).
1924       if (TT->getDecl()->hasAttr<UnusedAttr>())
1925         return false;
1926     }
1927 
1928     // Warn for reference variables whose initializtion performs lifetime
1929     // extension.
1930     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1931       if (MTE->getExtendingDecl()) {
1932         Ty = VD->getType().getNonReferenceType().getTypePtr();
1933         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1934       }
1935     }
1936 
1937     // If we failed to complete the type for some reason, or if the type is
1938     // dependent, don't diagnose the variable.
1939     if (Ty->isIncompleteType() || Ty->isDependentType())
1940       return false;
1941 
1942     // Look at the element type to ensure that the warning behaviour is
1943     // consistent for both scalars and arrays.
1944     Ty = Ty->getBaseElementTypeUnsafe();
1945 
1946     if (const TagType *TT = Ty->getAs<TagType>()) {
1947       const TagDecl *Tag = TT->getDecl();
1948       if (Tag->hasAttr<UnusedAttr>())
1949         return false;
1950 
1951       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1952         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1953           return false;
1954 
1955         if (Init) {
1956           const CXXConstructExpr *Construct =
1957             dyn_cast<CXXConstructExpr>(Init);
1958           if (Construct && !Construct->isElidable()) {
1959             CXXConstructorDecl *CD = Construct->getConstructor();
1960             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1961                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1962               return false;
1963           }
1964 
1965           // Suppress the warning if we don't know how this is constructed, and
1966           // it could possibly be non-trivial constructor.
1967           if (Init->isTypeDependent()) {
1968             for (const CXXConstructorDecl *Ctor : RD->ctors())
1969               if (!Ctor->isTrivial())
1970                 return false;
1971           }
1972 
1973           // Suppress the warning if the constructor is unresolved because
1974           // its arguments are dependent.
1975           if (isa<CXXUnresolvedConstructExpr>(Init))
1976             return false;
1977         }
1978       }
1979     }
1980 
1981     // TODO: __attribute__((unused)) templates?
1982   }
1983 
1984   return true;
1985 }
1986 
1987 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1988                                      FixItHint &Hint) {
1989   if (isa<LabelDecl>(D)) {
1990     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1991         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1992         true);
1993     if (AfterColon.isInvalid())
1994       return;
1995     Hint = FixItHint::CreateRemoval(
1996         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1997   }
1998 }
1999 
2000 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2001   if (D->getTypeForDecl()->isDependentType())
2002     return;
2003 
2004   for (auto *TmpD : D->decls()) {
2005     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2006       DiagnoseUnusedDecl(T);
2007     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2008       DiagnoseUnusedNestedTypedefs(R);
2009   }
2010 }
2011 
2012 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2013 /// unless they are marked attr(unused).
2014 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2015   if (!ShouldDiagnoseUnusedDecl(D))
2016     return;
2017 
2018   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2019     // typedefs can be referenced later on, so the diagnostics are emitted
2020     // at end-of-translation-unit.
2021     UnusedLocalTypedefNameCandidates.insert(TD);
2022     return;
2023   }
2024 
2025   FixItHint Hint;
2026   GenerateFixForUnusedDecl(D, Context, Hint);
2027 
2028   unsigned DiagID;
2029   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2030     DiagID = diag::warn_unused_exception_param;
2031   else if (isa<LabelDecl>(D))
2032     DiagID = diag::warn_unused_label;
2033   else
2034     DiagID = diag::warn_unused_variable;
2035 
2036   Diag(D->getLocation(), DiagID) << D << Hint;
2037 }
2038 
2039 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2040   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2041   // it's not really unused.
2042   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2043       VD->hasAttr<CleanupAttr>())
2044     return;
2045 
2046   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2047 
2048   if (Ty->isReferenceType() || Ty->isDependentType())
2049     return;
2050 
2051   if (const TagType *TT = Ty->getAs<TagType>()) {
2052     const TagDecl *Tag = TT->getDecl();
2053     if (Tag->hasAttr<UnusedAttr>())
2054       return;
2055     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2056     // mimic gcc's behavior.
2057     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2058       if (!RD->hasAttr<WarnUnusedAttr>())
2059         return;
2060     }
2061   }
2062 
2063   // Don't warn about __block Objective-C pointer variables, as they might
2064   // be assigned in the block but not used elsewhere for the purpose of lifetime
2065   // extension.
2066   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2067     return;
2068 
2069   // Don't warn about Objective-C pointer variables with precise lifetime
2070   // semantics; they can be used to ensure ARC releases the object at a known
2071   // time, which may mean assignment but no other references.
2072   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2073     return;
2074 
2075   auto iter = RefsMinusAssignments.find(VD);
2076   if (iter == RefsMinusAssignments.end())
2077     return;
2078 
2079   assert(iter->getSecond() >= 0 &&
2080          "Found a negative number of references to a VarDecl");
2081   if (iter->getSecond() != 0)
2082     return;
2083   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2084                                          : diag::warn_unused_but_set_variable;
2085   Diag(VD->getLocation(), DiagID) << VD;
2086 }
2087 
2088 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2089   // Verify that we have no forward references left.  If so, there was a goto
2090   // or address of a label taken, but no definition of it.  Label fwd
2091   // definitions are indicated with a null substmt which is also not a resolved
2092   // MS inline assembly label name.
2093   bool Diagnose = false;
2094   if (L->isMSAsmLabel())
2095     Diagnose = !L->isResolvedMSAsmLabel();
2096   else
2097     Diagnose = L->getStmt() == nullptr;
2098   if (Diagnose)
2099     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2100 }
2101 
2102 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2103   S->mergeNRVOIntoParent();
2104 
2105   if (S->decl_empty()) return;
2106   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2107          "Scope shouldn't contain decls!");
2108 
2109   for (auto *TmpD : S->decls()) {
2110     assert(TmpD && "This decl didn't get pushed??");
2111 
2112     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2113     NamedDecl *D = cast<NamedDecl>(TmpD);
2114 
2115     // Diagnose unused variables in this scope.
2116     if (!S->hasUnrecoverableErrorOccurred()) {
2117       DiagnoseUnusedDecl(D);
2118       if (const auto *RD = dyn_cast<RecordDecl>(D))
2119         DiagnoseUnusedNestedTypedefs(RD);
2120       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2121         DiagnoseUnusedButSetDecl(VD);
2122         RefsMinusAssignments.erase(VD);
2123       }
2124     }
2125 
2126     if (!D->getDeclName()) continue;
2127 
2128     // If this was a forward reference to a label, verify it was defined.
2129     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2130       CheckPoppedLabel(LD, *this);
2131 
2132     // Remove this name from our lexical scope, and warn on it if we haven't
2133     // already.
2134     IdResolver.RemoveDecl(D);
2135     auto ShadowI = ShadowingDecls.find(D);
2136     if (ShadowI != ShadowingDecls.end()) {
2137       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2138         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2139             << D << FD << FD->getParent();
2140         Diag(FD->getLocation(), diag::note_previous_declaration);
2141       }
2142       ShadowingDecls.erase(ShadowI);
2143     }
2144   }
2145 }
2146 
2147 /// Look for an Objective-C class in the translation unit.
2148 ///
2149 /// \param Id The name of the Objective-C class we're looking for. If
2150 /// typo-correction fixes this name, the Id will be updated
2151 /// to the fixed name.
2152 ///
2153 /// \param IdLoc The location of the name in the translation unit.
2154 ///
2155 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2156 /// if there is no class with the given name.
2157 ///
2158 /// \returns The declaration of the named Objective-C class, or NULL if the
2159 /// class could not be found.
2160 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2161                                               SourceLocation IdLoc,
2162                                               bool DoTypoCorrection) {
2163   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2164   // creation from this context.
2165   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2166 
2167   if (!IDecl && DoTypoCorrection) {
2168     // Perform typo correction at the given location, but only if we
2169     // find an Objective-C class name.
2170     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2171     if (TypoCorrection C =
2172             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2173                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2174       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2175       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2176       Id = IDecl->getIdentifier();
2177     }
2178   }
2179   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2180   // This routine must always return a class definition, if any.
2181   if (Def && Def->getDefinition())
2182       Def = Def->getDefinition();
2183   return Def;
2184 }
2185 
2186 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2187 /// from S, where a non-field would be declared. This routine copes
2188 /// with the difference between C and C++ scoping rules in structs and
2189 /// unions. For example, the following code is well-formed in C but
2190 /// ill-formed in C++:
2191 /// @code
2192 /// struct S6 {
2193 ///   enum { BAR } e;
2194 /// };
2195 ///
2196 /// void test_S6() {
2197 ///   struct S6 a;
2198 ///   a.e = BAR;
2199 /// }
2200 /// @endcode
2201 /// For the declaration of BAR, this routine will return a different
2202 /// scope. The scope S will be the scope of the unnamed enumeration
2203 /// within S6. In C++, this routine will return the scope associated
2204 /// with S6, because the enumeration's scope is a transparent
2205 /// context but structures can contain non-field names. In C, this
2206 /// routine will return the translation unit scope, since the
2207 /// enumeration's scope is a transparent context and structures cannot
2208 /// contain non-field names.
2209 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2210   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2211          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2212          (S->isClassScope() && !getLangOpts().CPlusPlus))
2213     S = S->getParent();
2214   return S;
2215 }
2216 
2217 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2218                                ASTContext::GetBuiltinTypeError Error) {
2219   switch (Error) {
2220   case ASTContext::GE_None:
2221     return "";
2222   case ASTContext::GE_Missing_type:
2223     return BuiltinInfo.getHeaderName(ID);
2224   case ASTContext::GE_Missing_stdio:
2225     return "stdio.h";
2226   case ASTContext::GE_Missing_setjmp:
2227     return "setjmp.h";
2228   case ASTContext::GE_Missing_ucontext:
2229     return "ucontext.h";
2230   }
2231   llvm_unreachable("unhandled error kind");
2232 }
2233 
2234 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2235                                   unsigned ID, SourceLocation Loc) {
2236   DeclContext *Parent = Context.getTranslationUnitDecl();
2237 
2238   if (getLangOpts().CPlusPlus) {
2239     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2240         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2241     CLinkageDecl->setImplicit();
2242     Parent->addDecl(CLinkageDecl);
2243     Parent = CLinkageDecl;
2244   }
2245 
2246   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2247                                            /*TInfo=*/nullptr, SC_Extern,
2248                                            getCurFPFeatures().isFPConstrained(),
2249                                            false, Type->isFunctionProtoType());
2250   New->setImplicit();
2251   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2252 
2253   // Create Decl objects for each parameter, adding them to the
2254   // FunctionDecl.
2255   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2256     SmallVector<ParmVarDecl *, 16> Params;
2257     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2258       ParmVarDecl *parm = ParmVarDecl::Create(
2259           Context, New, SourceLocation(), SourceLocation(), nullptr,
2260           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2261       parm->setScopeInfo(0, i);
2262       Params.push_back(parm);
2263     }
2264     New->setParams(Params);
2265   }
2266 
2267   AddKnownFunctionAttributes(New);
2268   return New;
2269 }
2270 
2271 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2272 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2273 /// if we're creating this built-in in anticipation of redeclaring the
2274 /// built-in.
2275 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2276                                      Scope *S, bool ForRedeclaration,
2277                                      SourceLocation Loc) {
2278   LookupNecessaryTypesForBuiltin(S, ID);
2279 
2280   ASTContext::GetBuiltinTypeError Error;
2281   QualType R = Context.GetBuiltinType(ID, Error);
2282   if (Error) {
2283     if (!ForRedeclaration)
2284       return nullptr;
2285 
2286     // If we have a builtin without an associated type we should not emit a
2287     // warning when we were not able to find a type for it.
2288     if (Error == ASTContext::GE_Missing_type ||
2289         Context.BuiltinInfo.allowTypeMismatch(ID))
2290       return nullptr;
2291 
2292     // If we could not find a type for setjmp it is because the jmp_buf type was
2293     // not defined prior to the setjmp declaration.
2294     if (Error == ASTContext::GE_Missing_setjmp) {
2295       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2296           << Context.BuiltinInfo.getName(ID);
2297       return nullptr;
2298     }
2299 
2300     // Generally, we emit a warning that the declaration requires the
2301     // appropriate header.
2302     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2303         << getHeaderName(Context.BuiltinInfo, ID, Error)
2304         << Context.BuiltinInfo.getName(ID);
2305     return nullptr;
2306   }
2307 
2308   if (!ForRedeclaration &&
2309       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2310        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2311     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2312                            : diag::ext_implicit_lib_function_decl)
2313         << Context.BuiltinInfo.getName(ID) << R;
2314     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2315       Diag(Loc, diag::note_include_header_or_declare)
2316           << Header << Context.BuiltinInfo.getName(ID);
2317   }
2318 
2319   if (R.isNull())
2320     return nullptr;
2321 
2322   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2323   RegisterLocallyScopedExternCDecl(New, S);
2324 
2325   // TUScope is the translation-unit scope to insert this function into.
2326   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2327   // relate Scopes to DeclContexts, and probably eliminate CurContext
2328   // entirely, but we're not there yet.
2329   DeclContext *SavedContext = CurContext;
2330   CurContext = New->getDeclContext();
2331   PushOnScopeChains(New, TUScope);
2332   CurContext = SavedContext;
2333   return New;
2334 }
2335 
2336 /// Typedef declarations don't have linkage, but they still denote the same
2337 /// entity if their types are the same.
2338 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2339 /// isSameEntity.
2340 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2341                                                      TypedefNameDecl *Decl,
2342                                                      LookupResult &Previous) {
2343   // This is only interesting when modules are enabled.
2344   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2345     return;
2346 
2347   // Empty sets are uninteresting.
2348   if (Previous.empty())
2349     return;
2350 
2351   LookupResult::Filter Filter = Previous.makeFilter();
2352   while (Filter.hasNext()) {
2353     NamedDecl *Old = Filter.next();
2354 
2355     // Non-hidden declarations are never ignored.
2356     if (S.isVisible(Old))
2357       continue;
2358 
2359     // Declarations of the same entity are not ignored, even if they have
2360     // different linkages.
2361     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2362       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2363                                 Decl->getUnderlyingType()))
2364         continue;
2365 
2366       // If both declarations give a tag declaration a typedef name for linkage
2367       // purposes, then they declare the same entity.
2368       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2369           Decl->getAnonDeclWithTypedefName())
2370         continue;
2371     }
2372 
2373     Filter.erase();
2374   }
2375 
2376   Filter.done();
2377 }
2378 
2379 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2380   QualType OldType;
2381   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2382     OldType = OldTypedef->getUnderlyingType();
2383   else
2384     OldType = Context.getTypeDeclType(Old);
2385   QualType NewType = New->getUnderlyingType();
2386 
2387   if (NewType->isVariablyModifiedType()) {
2388     // Must not redefine a typedef with a variably-modified type.
2389     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2390     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2391       << Kind << NewType;
2392     if (Old->getLocation().isValid())
2393       notePreviousDefinition(Old, New->getLocation());
2394     New->setInvalidDecl();
2395     return true;
2396   }
2397 
2398   if (OldType != NewType &&
2399       !OldType->isDependentType() &&
2400       !NewType->isDependentType() &&
2401       !Context.hasSameType(OldType, NewType)) {
2402     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2403     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2404       << Kind << NewType << OldType;
2405     if (Old->getLocation().isValid())
2406       notePreviousDefinition(Old, New->getLocation());
2407     New->setInvalidDecl();
2408     return true;
2409   }
2410   return false;
2411 }
2412 
2413 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2414 /// same name and scope as a previous declaration 'Old'.  Figure out
2415 /// how to resolve this situation, merging decls or emitting
2416 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2417 ///
2418 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2419                                 LookupResult &OldDecls) {
2420   // If the new decl is known invalid already, don't bother doing any
2421   // merging checks.
2422   if (New->isInvalidDecl()) return;
2423 
2424   // Allow multiple definitions for ObjC built-in typedefs.
2425   // FIXME: Verify the underlying types are equivalent!
2426   if (getLangOpts().ObjC) {
2427     const IdentifierInfo *TypeID = New->getIdentifier();
2428     switch (TypeID->getLength()) {
2429     default: break;
2430     case 2:
2431       {
2432         if (!TypeID->isStr("id"))
2433           break;
2434         QualType T = New->getUnderlyingType();
2435         if (!T->isPointerType())
2436           break;
2437         if (!T->isVoidPointerType()) {
2438           QualType PT = T->castAs<PointerType>()->getPointeeType();
2439           if (!PT->isStructureType())
2440             break;
2441         }
2442         Context.setObjCIdRedefinitionType(T);
2443         // Install the built-in type for 'id', ignoring the current definition.
2444         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2445         return;
2446       }
2447     case 5:
2448       if (!TypeID->isStr("Class"))
2449         break;
2450       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2451       // Install the built-in type for 'Class', ignoring the current definition.
2452       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2453       return;
2454     case 3:
2455       if (!TypeID->isStr("SEL"))
2456         break;
2457       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2458       // Install the built-in type for 'SEL', ignoring the current definition.
2459       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2460       return;
2461     }
2462     // Fall through - the typedef name was not a builtin type.
2463   }
2464 
2465   // Verify the old decl was also a type.
2466   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2467   if (!Old) {
2468     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2469       << New->getDeclName();
2470 
2471     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2472     if (OldD->getLocation().isValid())
2473       notePreviousDefinition(OldD, New->getLocation());
2474 
2475     return New->setInvalidDecl();
2476   }
2477 
2478   // If the old declaration is invalid, just give up here.
2479   if (Old->isInvalidDecl())
2480     return New->setInvalidDecl();
2481 
2482   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2483     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2484     auto *NewTag = New->getAnonDeclWithTypedefName();
2485     NamedDecl *Hidden = nullptr;
2486     if (OldTag && NewTag &&
2487         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2488         !hasVisibleDefinition(OldTag, &Hidden)) {
2489       // There is a definition of this tag, but it is not visible. Use it
2490       // instead of our tag.
2491       New->setTypeForDecl(OldTD->getTypeForDecl());
2492       if (OldTD->isModed())
2493         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2494                                     OldTD->getUnderlyingType());
2495       else
2496         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2497 
2498       // Make the old tag definition visible.
2499       makeMergedDefinitionVisible(Hidden);
2500 
2501       // If this was an unscoped enumeration, yank all of its enumerators
2502       // out of the scope.
2503       if (isa<EnumDecl>(NewTag)) {
2504         Scope *EnumScope = getNonFieldDeclScope(S);
2505         for (auto *D : NewTag->decls()) {
2506           auto *ED = cast<EnumConstantDecl>(D);
2507           assert(EnumScope->isDeclScope(ED));
2508           EnumScope->RemoveDecl(ED);
2509           IdResolver.RemoveDecl(ED);
2510           ED->getLexicalDeclContext()->removeDecl(ED);
2511         }
2512       }
2513     }
2514   }
2515 
2516   // If the typedef types are not identical, reject them in all languages and
2517   // with any extensions enabled.
2518   if (isIncompatibleTypedef(Old, New))
2519     return;
2520 
2521   // The types match.  Link up the redeclaration chain and merge attributes if
2522   // the old declaration was a typedef.
2523   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2524     New->setPreviousDecl(Typedef);
2525     mergeDeclAttributes(New, Old);
2526   }
2527 
2528   if (getLangOpts().MicrosoftExt)
2529     return;
2530 
2531   if (getLangOpts().CPlusPlus) {
2532     // C++ [dcl.typedef]p2:
2533     //   In a given non-class scope, a typedef specifier can be used to
2534     //   redefine the name of any type declared in that scope to refer
2535     //   to the type to which it already refers.
2536     if (!isa<CXXRecordDecl>(CurContext))
2537       return;
2538 
2539     // C++0x [dcl.typedef]p4:
2540     //   In a given class scope, a typedef specifier can be used to redefine
2541     //   any class-name declared in that scope that is not also a typedef-name
2542     //   to refer to the type to which it already refers.
2543     //
2544     // This wording came in via DR424, which was a correction to the
2545     // wording in DR56, which accidentally banned code like:
2546     //
2547     //   struct S {
2548     //     typedef struct A { } A;
2549     //   };
2550     //
2551     // in the C++03 standard. We implement the C++0x semantics, which
2552     // allow the above but disallow
2553     //
2554     //   struct S {
2555     //     typedef int I;
2556     //     typedef int I;
2557     //   };
2558     //
2559     // since that was the intent of DR56.
2560     if (!isa<TypedefNameDecl>(Old))
2561       return;
2562 
2563     Diag(New->getLocation(), diag::err_redefinition)
2564       << New->getDeclName();
2565     notePreviousDefinition(Old, New->getLocation());
2566     return New->setInvalidDecl();
2567   }
2568 
2569   // Modules always permit redefinition of typedefs, as does C11.
2570   if (getLangOpts().Modules || getLangOpts().C11)
2571     return;
2572 
2573   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2574   // is normally mapped to an error, but can be controlled with
2575   // -Wtypedef-redefinition.  If either the original or the redefinition is
2576   // in a system header, don't emit this for compatibility with GCC.
2577   if (getDiagnostics().getSuppressSystemWarnings() &&
2578       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2579       (Old->isImplicit() ||
2580        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2581        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2582     return;
2583 
2584   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2585     << New->getDeclName();
2586   notePreviousDefinition(Old, New->getLocation());
2587 }
2588 
2589 /// DeclhasAttr - returns true if decl Declaration already has the target
2590 /// attribute.
2591 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2592   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2593   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2594   for (const auto *i : D->attrs())
2595     if (i->getKind() == A->getKind()) {
2596       if (Ann) {
2597         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2598           return true;
2599         continue;
2600       }
2601       // FIXME: Don't hardcode this check
2602       if (OA && isa<OwnershipAttr>(i))
2603         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2604       return true;
2605     }
2606 
2607   return false;
2608 }
2609 
2610 static bool isAttributeTargetADefinition(Decl *D) {
2611   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2612     return VD->isThisDeclarationADefinition();
2613   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2614     return TD->isCompleteDefinition() || TD->isBeingDefined();
2615   return true;
2616 }
2617 
2618 /// Merge alignment attributes from \p Old to \p New, taking into account the
2619 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2620 ///
2621 /// \return \c true if any attributes were added to \p New.
2622 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2623   // Look for alignas attributes on Old, and pick out whichever attribute
2624   // specifies the strictest alignment requirement.
2625   AlignedAttr *OldAlignasAttr = nullptr;
2626   AlignedAttr *OldStrictestAlignAttr = nullptr;
2627   unsigned OldAlign = 0;
2628   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2629     // FIXME: We have no way of representing inherited dependent alignments
2630     // in a case like:
2631     //   template<int A, int B> struct alignas(A) X;
2632     //   template<int A, int B> struct alignas(B) X {};
2633     // For now, we just ignore any alignas attributes which are not on the
2634     // definition in such a case.
2635     if (I->isAlignmentDependent())
2636       return false;
2637 
2638     if (I->isAlignas())
2639       OldAlignasAttr = I;
2640 
2641     unsigned Align = I->getAlignment(S.Context);
2642     if (Align > OldAlign) {
2643       OldAlign = Align;
2644       OldStrictestAlignAttr = I;
2645     }
2646   }
2647 
2648   // Look for alignas attributes on New.
2649   AlignedAttr *NewAlignasAttr = nullptr;
2650   unsigned NewAlign = 0;
2651   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2652     if (I->isAlignmentDependent())
2653       return false;
2654 
2655     if (I->isAlignas())
2656       NewAlignasAttr = I;
2657 
2658     unsigned Align = I->getAlignment(S.Context);
2659     if (Align > NewAlign)
2660       NewAlign = Align;
2661   }
2662 
2663   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2664     // Both declarations have 'alignas' attributes. We require them to match.
2665     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2666     // fall short. (If two declarations both have alignas, they must both match
2667     // every definition, and so must match each other if there is a definition.)
2668 
2669     // If either declaration only contains 'alignas(0)' specifiers, then it
2670     // specifies the natural alignment for the type.
2671     if (OldAlign == 0 || NewAlign == 0) {
2672       QualType Ty;
2673       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2674         Ty = VD->getType();
2675       else
2676         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2677 
2678       if (OldAlign == 0)
2679         OldAlign = S.Context.getTypeAlign(Ty);
2680       if (NewAlign == 0)
2681         NewAlign = S.Context.getTypeAlign(Ty);
2682     }
2683 
2684     if (OldAlign != NewAlign) {
2685       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2686         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2687         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2688       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2689     }
2690   }
2691 
2692   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2693     // C++11 [dcl.align]p6:
2694     //   if any declaration of an entity has an alignment-specifier,
2695     //   every defining declaration of that entity shall specify an
2696     //   equivalent alignment.
2697     // C11 6.7.5/7:
2698     //   If the definition of an object does not have an alignment
2699     //   specifier, any other declaration of that object shall also
2700     //   have no alignment specifier.
2701     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2702       << OldAlignasAttr;
2703     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2704       << OldAlignasAttr;
2705   }
2706 
2707   bool AnyAdded = false;
2708 
2709   // Ensure we have an attribute representing the strictest alignment.
2710   if (OldAlign > NewAlign) {
2711     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2712     Clone->setInherited(true);
2713     New->addAttr(Clone);
2714     AnyAdded = true;
2715   }
2716 
2717   // Ensure we have an alignas attribute if the old declaration had one.
2718   if (OldAlignasAttr && !NewAlignasAttr &&
2719       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2720     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2721     Clone->setInherited(true);
2722     New->addAttr(Clone);
2723     AnyAdded = true;
2724   }
2725 
2726   return AnyAdded;
2727 }
2728 
2729 #define WANT_DECL_MERGE_LOGIC
2730 #include "clang/Sema/AttrParsedAttrImpl.inc"
2731 #undef WANT_DECL_MERGE_LOGIC
2732 
2733 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2734                                const InheritableAttr *Attr,
2735                                Sema::AvailabilityMergeKind AMK) {
2736   // Diagnose any mutual exclusions between the attribute that we want to add
2737   // and attributes that already exist on the declaration.
2738   if (!DiagnoseMutualExclusions(S, D, Attr))
2739     return false;
2740 
2741   // This function copies an attribute Attr from a previous declaration to the
2742   // new declaration D if the new declaration doesn't itself have that attribute
2743   // yet or if that attribute allows duplicates.
2744   // If you're adding a new attribute that requires logic different from
2745   // "use explicit attribute on decl if present, else use attribute from
2746   // previous decl", for example if the attribute needs to be consistent
2747   // between redeclarations, you need to call a custom merge function here.
2748   InheritableAttr *NewAttr = nullptr;
2749   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2750     NewAttr = S.mergeAvailabilityAttr(
2751         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2752         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2753         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2754         AA->getPriority());
2755   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2756     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2757   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2758     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2759   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2760     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2761   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2762     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2763   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2764     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2765   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2766     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2767                                 FA->getFirstArg());
2768   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2769     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2770   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2771     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2772   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2773     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2774                                        IA->getInheritanceModel());
2775   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2776     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2777                                       &S.Context.Idents.get(AA->getSpelling()));
2778   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2779            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2780             isa<CUDAGlobalAttr>(Attr))) {
2781     // CUDA target attributes are part of function signature for
2782     // overloading purposes and must not be merged.
2783     return false;
2784   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2785     NewAttr = S.mergeMinSizeAttr(D, *MA);
2786   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2787     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2788   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2789     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2790   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2791     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2792   else if (isa<AlignedAttr>(Attr))
2793     // AlignedAttrs are handled separately, because we need to handle all
2794     // such attributes on a declaration at the same time.
2795     NewAttr = nullptr;
2796   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2797            (AMK == Sema::AMK_Override ||
2798             AMK == Sema::AMK_ProtocolImplementation ||
2799             AMK == Sema::AMK_OptionalProtocolImplementation))
2800     NewAttr = nullptr;
2801   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2802     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2803   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2804     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2805   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2806     NewAttr = S.mergeImportNameAttr(D, *INA);
2807   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2808     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2809   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2810     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2811   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2812     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2813   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2814     NewAttr =
2815         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2816   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2817     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2818   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2819     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2820 
2821   if (NewAttr) {
2822     NewAttr->setInherited(true);
2823     D->addAttr(NewAttr);
2824     if (isa<MSInheritanceAttr>(NewAttr))
2825       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2826     return true;
2827   }
2828 
2829   return false;
2830 }
2831 
2832 static const NamedDecl *getDefinition(const Decl *D) {
2833   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2834     return TD->getDefinition();
2835   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2836     const VarDecl *Def = VD->getDefinition();
2837     if (Def)
2838       return Def;
2839     return VD->getActingDefinition();
2840   }
2841   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2842     const FunctionDecl *Def = nullptr;
2843     if (FD->isDefined(Def, true))
2844       return Def;
2845   }
2846   return nullptr;
2847 }
2848 
2849 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2850   for (const auto *Attribute : D->attrs())
2851     if (Attribute->getKind() == Kind)
2852       return true;
2853   return false;
2854 }
2855 
2856 /// checkNewAttributesAfterDef - If we already have a definition, check that
2857 /// there are no new attributes in this declaration.
2858 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2859   if (!New->hasAttrs())
2860     return;
2861 
2862   const NamedDecl *Def = getDefinition(Old);
2863   if (!Def || Def == New)
2864     return;
2865 
2866   AttrVec &NewAttributes = New->getAttrs();
2867   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2868     const Attr *NewAttribute = NewAttributes[I];
2869 
2870     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2871       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2872         Sema::SkipBodyInfo SkipBody;
2873         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2874 
2875         // If we're skipping this definition, drop the "alias" attribute.
2876         if (SkipBody.ShouldSkip) {
2877           NewAttributes.erase(NewAttributes.begin() + I);
2878           --E;
2879           continue;
2880         }
2881       } else {
2882         VarDecl *VD = cast<VarDecl>(New);
2883         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2884                                 VarDecl::TentativeDefinition
2885                             ? diag::err_alias_after_tentative
2886                             : diag::err_redefinition;
2887         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2888         if (Diag == diag::err_redefinition)
2889           S.notePreviousDefinition(Def, VD->getLocation());
2890         else
2891           S.Diag(Def->getLocation(), diag::note_previous_definition);
2892         VD->setInvalidDecl();
2893       }
2894       ++I;
2895       continue;
2896     }
2897 
2898     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2899       // Tentative definitions are only interesting for the alias check above.
2900       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2901         ++I;
2902         continue;
2903       }
2904     }
2905 
2906     if (hasAttribute(Def, NewAttribute->getKind())) {
2907       ++I;
2908       continue; // regular attr merging will take care of validating this.
2909     }
2910 
2911     if (isa<C11NoReturnAttr>(NewAttribute)) {
2912       // C's _Noreturn is allowed to be added to a function after it is defined.
2913       ++I;
2914       continue;
2915     } else if (isa<UuidAttr>(NewAttribute)) {
2916       // msvc will allow a subsequent definition to add an uuid to a class
2917       ++I;
2918       continue;
2919     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2920       if (AA->isAlignas()) {
2921         // C++11 [dcl.align]p6:
2922         //   if any declaration of an entity has an alignment-specifier,
2923         //   every defining declaration of that entity shall specify an
2924         //   equivalent alignment.
2925         // C11 6.7.5/7:
2926         //   If the definition of an object does not have an alignment
2927         //   specifier, any other declaration of that object shall also
2928         //   have no alignment specifier.
2929         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2930           << AA;
2931         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2932           << AA;
2933         NewAttributes.erase(NewAttributes.begin() + I);
2934         --E;
2935         continue;
2936       }
2937     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2938       // If there is a C definition followed by a redeclaration with this
2939       // attribute then there are two different definitions. In C++, prefer the
2940       // standard diagnostics.
2941       if (!S.getLangOpts().CPlusPlus) {
2942         S.Diag(NewAttribute->getLocation(),
2943                diag::err_loader_uninitialized_redeclaration);
2944         S.Diag(Def->getLocation(), diag::note_previous_definition);
2945         NewAttributes.erase(NewAttributes.begin() + I);
2946         --E;
2947         continue;
2948       }
2949     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2950                cast<VarDecl>(New)->isInline() &&
2951                !cast<VarDecl>(New)->isInlineSpecified()) {
2952       // Don't warn about applying selectany to implicitly inline variables.
2953       // Older compilers and language modes would require the use of selectany
2954       // to make such variables inline, and it would have no effect if we
2955       // honored it.
2956       ++I;
2957       continue;
2958     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2959       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2960       // declarations after defintions.
2961       ++I;
2962       continue;
2963     }
2964 
2965     S.Diag(NewAttribute->getLocation(),
2966            diag::warn_attribute_precede_definition);
2967     S.Diag(Def->getLocation(), diag::note_previous_definition);
2968     NewAttributes.erase(NewAttributes.begin() + I);
2969     --E;
2970   }
2971 }
2972 
2973 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2974                                      const ConstInitAttr *CIAttr,
2975                                      bool AttrBeforeInit) {
2976   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2977 
2978   // Figure out a good way to write this specifier on the old declaration.
2979   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2980   // enough of the attribute list spelling information to extract that without
2981   // heroics.
2982   std::string SuitableSpelling;
2983   if (S.getLangOpts().CPlusPlus20)
2984     SuitableSpelling = std::string(
2985         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2986   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2987     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2988         InsertLoc, {tok::l_square, tok::l_square,
2989                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2990                     S.PP.getIdentifierInfo("require_constant_initialization"),
2991                     tok::r_square, tok::r_square}));
2992   if (SuitableSpelling.empty())
2993     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2994         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2995                     S.PP.getIdentifierInfo("require_constant_initialization"),
2996                     tok::r_paren, tok::r_paren}));
2997   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2998     SuitableSpelling = "constinit";
2999   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3000     SuitableSpelling = "[[clang::require_constant_initialization]]";
3001   if (SuitableSpelling.empty())
3002     SuitableSpelling = "__attribute__((require_constant_initialization))";
3003   SuitableSpelling += " ";
3004 
3005   if (AttrBeforeInit) {
3006     // extern constinit int a;
3007     // int a = 0; // error (missing 'constinit'), accepted as extension
3008     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3009     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3010         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3011     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3012   } else {
3013     // int a = 0;
3014     // constinit extern int a; // error (missing 'constinit')
3015     S.Diag(CIAttr->getLocation(),
3016            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3017                                  : diag::warn_require_const_init_added_too_late)
3018         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3019     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3020         << CIAttr->isConstinit()
3021         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3022   }
3023 }
3024 
3025 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3026 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3027                                AvailabilityMergeKind AMK) {
3028   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3029     UsedAttr *NewAttr = OldAttr->clone(Context);
3030     NewAttr->setInherited(true);
3031     New->addAttr(NewAttr);
3032   }
3033   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3034     RetainAttr *NewAttr = OldAttr->clone(Context);
3035     NewAttr->setInherited(true);
3036     New->addAttr(NewAttr);
3037   }
3038 
3039   if (!Old->hasAttrs() && !New->hasAttrs())
3040     return;
3041 
3042   // [dcl.constinit]p1:
3043   //   If the [constinit] specifier is applied to any declaration of a
3044   //   variable, it shall be applied to the initializing declaration.
3045   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3046   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3047   if (bool(OldConstInit) != bool(NewConstInit)) {
3048     const auto *OldVD = cast<VarDecl>(Old);
3049     auto *NewVD = cast<VarDecl>(New);
3050 
3051     // Find the initializing declaration. Note that we might not have linked
3052     // the new declaration into the redeclaration chain yet.
3053     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3054     if (!InitDecl &&
3055         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3056       InitDecl = NewVD;
3057 
3058     if (InitDecl == NewVD) {
3059       // This is the initializing declaration. If it would inherit 'constinit',
3060       // that's ill-formed. (Note that we do not apply this to the attribute
3061       // form).
3062       if (OldConstInit && OldConstInit->isConstinit())
3063         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3064                                  /*AttrBeforeInit=*/true);
3065     } else if (NewConstInit) {
3066       // This is the first time we've been told that this declaration should
3067       // have a constant initializer. If we already saw the initializing
3068       // declaration, this is too late.
3069       if (InitDecl && InitDecl != NewVD) {
3070         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3071                                  /*AttrBeforeInit=*/false);
3072         NewVD->dropAttr<ConstInitAttr>();
3073       }
3074     }
3075   }
3076 
3077   // Attributes declared post-definition are currently ignored.
3078   checkNewAttributesAfterDef(*this, New, Old);
3079 
3080   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3081     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3082       if (!OldA->isEquivalent(NewA)) {
3083         // This redeclaration changes __asm__ label.
3084         Diag(New->getLocation(), diag::err_different_asm_label);
3085         Diag(OldA->getLocation(), diag::note_previous_declaration);
3086       }
3087     } else if (Old->isUsed()) {
3088       // This redeclaration adds an __asm__ label to a declaration that has
3089       // already been ODR-used.
3090       Diag(New->getLocation(), diag::err_late_asm_label_name)
3091         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3092     }
3093   }
3094 
3095   // Re-declaration cannot add abi_tag's.
3096   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3097     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3098       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3099         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3100           Diag(NewAbiTagAttr->getLocation(),
3101                diag::err_new_abi_tag_on_redeclaration)
3102               << NewTag;
3103           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3104         }
3105       }
3106     } else {
3107       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3108       Diag(Old->getLocation(), diag::note_previous_declaration);
3109     }
3110   }
3111 
3112   // This redeclaration adds a section attribute.
3113   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3114     if (auto *VD = dyn_cast<VarDecl>(New)) {
3115       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3116         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3117         Diag(Old->getLocation(), diag::note_previous_declaration);
3118       }
3119     }
3120   }
3121 
3122   // Redeclaration adds code-seg attribute.
3123   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3124   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3125       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3126     Diag(New->getLocation(), diag::warn_mismatched_section)
3127          << 0 /*codeseg*/;
3128     Diag(Old->getLocation(), diag::note_previous_declaration);
3129   }
3130 
3131   if (!Old->hasAttrs())
3132     return;
3133 
3134   bool foundAny = New->hasAttrs();
3135 
3136   // Ensure that any moving of objects within the allocated map is done before
3137   // we process them.
3138   if (!foundAny) New->setAttrs(AttrVec());
3139 
3140   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3141     // Ignore deprecated/unavailable/availability attributes if requested.
3142     AvailabilityMergeKind LocalAMK = AMK_None;
3143     if (isa<DeprecatedAttr>(I) ||
3144         isa<UnavailableAttr>(I) ||
3145         isa<AvailabilityAttr>(I)) {
3146       switch (AMK) {
3147       case AMK_None:
3148         continue;
3149 
3150       case AMK_Redeclaration:
3151       case AMK_Override:
3152       case AMK_ProtocolImplementation:
3153       case AMK_OptionalProtocolImplementation:
3154         LocalAMK = AMK;
3155         break;
3156       }
3157     }
3158 
3159     // Already handled.
3160     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3161       continue;
3162 
3163     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3164       foundAny = true;
3165   }
3166 
3167   if (mergeAlignedAttrs(*this, New, Old))
3168     foundAny = true;
3169 
3170   if (!foundAny) New->dropAttrs();
3171 }
3172 
3173 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3174 /// to the new one.
3175 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3176                                      const ParmVarDecl *oldDecl,
3177                                      Sema &S) {
3178   // C++11 [dcl.attr.depend]p2:
3179   //   The first declaration of a function shall specify the
3180   //   carries_dependency attribute for its declarator-id if any declaration
3181   //   of the function specifies the carries_dependency attribute.
3182   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3183   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3184     S.Diag(CDA->getLocation(),
3185            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3186     // Find the first declaration of the parameter.
3187     // FIXME: Should we build redeclaration chains for function parameters?
3188     const FunctionDecl *FirstFD =
3189       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3190     const ParmVarDecl *FirstVD =
3191       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3192     S.Diag(FirstVD->getLocation(),
3193            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3194   }
3195 
3196   if (!oldDecl->hasAttrs())
3197     return;
3198 
3199   bool foundAny = newDecl->hasAttrs();
3200 
3201   // Ensure that any moving of objects within the allocated map is
3202   // done before we process them.
3203   if (!foundAny) newDecl->setAttrs(AttrVec());
3204 
3205   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3206     if (!DeclHasAttr(newDecl, I)) {
3207       InheritableAttr *newAttr =
3208         cast<InheritableParamAttr>(I->clone(S.Context));
3209       newAttr->setInherited(true);
3210       newDecl->addAttr(newAttr);
3211       foundAny = true;
3212     }
3213   }
3214 
3215   if (!foundAny) newDecl->dropAttrs();
3216 }
3217 
3218 static bool EquivalentArrayTypes(QualType Old, QualType New,
3219                                  const ASTContext &Ctx) {
3220 
3221   auto NoSizeInfo = [&Ctx](QualType Ty) {
3222     if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3223       return true;
3224     if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3225       return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3226     return false;
3227   };
3228 
3229   // `type[]` is equivalent to `type *` and `type[*]`.
3230   if (NoSizeInfo(Old) && NoSizeInfo(New))
3231     return true;
3232 
3233   // Don't try to compare VLA sizes, unless one of them has the star modifier.
3234   if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3235     const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3236     const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3237     if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3238         (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3239       return false;
3240     return true;
3241   }
3242 
3243   // Only compare size, ignore Size modifiers and CVR.
3244   if (Old->isConstantArrayType() && New->isConstantArrayType())
3245     return Ctx.getAsConstantArrayType(Old)->getSize() ==
3246            Ctx.getAsConstantArrayType(New)->getSize();
3247 
3248   return Old == New;
3249 }
3250 
3251 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3252                                 const ParmVarDecl *OldParam,
3253                                 Sema &S) {
3254   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3255     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3256       if (*Oldnullability != *Newnullability) {
3257         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3258           << DiagNullabilityKind(
3259                *Newnullability,
3260                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3261                 != 0))
3262           << DiagNullabilityKind(
3263                *Oldnullability,
3264                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3265                 != 0));
3266         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3267       }
3268     } else {
3269       QualType NewT = NewParam->getType();
3270       NewT = S.Context.getAttributedType(
3271                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3272                          NewT, NewT);
3273       NewParam->setType(NewT);
3274     }
3275   }
3276   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3277   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3278   if (OldParamDT && NewParamDT &&
3279       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3280     QualType OldParamOT = OldParamDT->getOriginalType();
3281     QualType NewParamOT = NewParamDT->getOriginalType();
3282     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3283       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3284           << NewParam << NewParamOT;
3285       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3286           << OldParamOT;
3287     }
3288   }
3289 }
3290 
3291 namespace {
3292 
3293 /// Used in MergeFunctionDecl to keep track of function parameters in
3294 /// C.
3295 struct GNUCompatibleParamWarning {
3296   ParmVarDecl *OldParm;
3297   ParmVarDecl *NewParm;
3298   QualType PromotedType;
3299 };
3300 
3301 } // end anonymous namespace
3302 
3303 // Determine whether the previous declaration was a definition, implicit
3304 // declaration, or a declaration.
3305 template <typename T>
3306 static std::pair<diag::kind, SourceLocation>
3307 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3308   diag::kind PrevDiag;
3309   SourceLocation OldLocation = Old->getLocation();
3310   if (Old->isThisDeclarationADefinition())
3311     PrevDiag = diag::note_previous_definition;
3312   else if (Old->isImplicit()) {
3313     PrevDiag = diag::note_previous_implicit_declaration;
3314     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3315       if (FD->getBuiltinID())
3316         PrevDiag = diag::note_previous_builtin_declaration;
3317     }
3318     if (OldLocation.isInvalid())
3319       OldLocation = New->getLocation();
3320   } else
3321     PrevDiag = diag::note_previous_declaration;
3322   return std::make_pair(PrevDiag, OldLocation);
3323 }
3324 
3325 /// canRedefineFunction - checks if a function can be redefined. Currently,
3326 /// only extern inline functions can be redefined, and even then only in
3327 /// GNU89 mode.
3328 static bool canRedefineFunction(const FunctionDecl *FD,
3329                                 const LangOptions& LangOpts) {
3330   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3331           !LangOpts.CPlusPlus &&
3332           FD->isInlineSpecified() &&
3333           FD->getStorageClass() == SC_Extern);
3334 }
3335 
3336 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3337   const AttributedType *AT = T->getAs<AttributedType>();
3338   while (AT && !AT->isCallingConv())
3339     AT = AT->getModifiedType()->getAs<AttributedType>();
3340   return AT;
3341 }
3342 
3343 template <typename T>
3344 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3345   const DeclContext *DC = Old->getDeclContext();
3346   if (DC->isRecord())
3347     return false;
3348 
3349   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3350   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3351     return true;
3352   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3353     return true;
3354   return false;
3355 }
3356 
3357 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3358 static bool isExternC(VarTemplateDecl *) { return false; }
3359 static bool isExternC(FunctionTemplateDecl *) { return false; }
3360 
3361 /// Check whether a redeclaration of an entity introduced by a
3362 /// using-declaration is valid, given that we know it's not an overload
3363 /// (nor a hidden tag declaration).
3364 template<typename ExpectedDecl>
3365 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3366                                    ExpectedDecl *New) {
3367   // C++11 [basic.scope.declarative]p4:
3368   //   Given a set of declarations in a single declarative region, each of
3369   //   which specifies the same unqualified name,
3370   //   -- they shall all refer to the same entity, or all refer to functions
3371   //      and function templates; or
3372   //   -- exactly one declaration shall declare a class name or enumeration
3373   //      name that is not a typedef name and the other declarations shall all
3374   //      refer to the same variable or enumerator, or all refer to functions
3375   //      and function templates; in this case the class name or enumeration
3376   //      name is hidden (3.3.10).
3377 
3378   // C++11 [namespace.udecl]p14:
3379   //   If a function declaration in namespace scope or block scope has the
3380   //   same name and the same parameter-type-list as a function introduced
3381   //   by a using-declaration, and the declarations do not declare the same
3382   //   function, the program is ill-formed.
3383 
3384   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3385   if (Old &&
3386       !Old->getDeclContext()->getRedeclContext()->Equals(
3387           New->getDeclContext()->getRedeclContext()) &&
3388       !(isExternC(Old) && isExternC(New)))
3389     Old = nullptr;
3390 
3391   if (!Old) {
3392     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3393     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3394     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3395     return true;
3396   }
3397   return false;
3398 }
3399 
3400 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3401                                             const FunctionDecl *B) {
3402   assert(A->getNumParams() == B->getNumParams());
3403 
3404   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3405     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3406     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3407     if (AttrA == AttrB)
3408       return true;
3409     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3410            AttrA->isDynamic() == AttrB->isDynamic();
3411   };
3412 
3413   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3414 }
3415 
3416 /// If necessary, adjust the semantic declaration context for a qualified
3417 /// declaration to name the correct inline namespace within the qualifier.
3418 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3419                                                DeclaratorDecl *OldD) {
3420   // The only case where we need to update the DeclContext is when
3421   // redeclaration lookup for a qualified name finds a declaration
3422   // in an inline namespace within the context named by the qualifier:
3423   //
3424   //   inline namespace N { int f(); }
3425   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3426   //
3427   // For unqualified declarations, the semantic context *can* change
3428   // along the redeclaration chain (for local extern declarations,
3429   // extern "C" declarations, and friend declarations in particular).
3430   if (!NewD->getQualifier())
3431     return;
3432 
3433   // NewD is probably already in the right context.
3434   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3435   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3436   if (NamedDC->Equals(SemaDC))
3437     return;
3438 
3439   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3440           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3441          "unexpected context for redeclaration");
3442 
3443   auto *LexDC = NewD->getLexicalDeclContext();
3444   auto FixSemaDC = [=](NamedDecl *D) {
3445     if (!D)
3446       return;
3447     D->setDeclContext(SemaDC);
3448     D->setLexicalDeclContext(LexDC);
3449   };
3450 
3451   FixSemaDC(NewD);
3452   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3453     FixSemaDC(FD->getDescribedFunctionTemplate());
3454   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3455     FixSemaDC(VD->getDescribedVarTemplate());
3456 }
3457 
3458 /// MergeFunctionDecl - We just parsed a function 'New' from
3459 /// declarator D which has the same name and scope as a previous
3460 /// declaration 'Old'.  Figure out how to resolve this situation,
3461 /// merging decls or emitting diagnostics as appropriate.
3462 ///
3463 /// In C++, New and Old must be declarations that are not
3464 /// overloaded. Use IsOverload to determine whether New and Old are
3465 /// overloaded, and to select the Old declaration that New should be
3466 /// merged with.
3467 ///
3468 /// Returns true if there was an error, false otherwise.
3469 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3470                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3471   // Verify the old decl was also a function.
3472   FunctionDecl *Old = OldD->getAsFunction();
3473   if (!Old) {
3474     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3475       if (New->getFriendObjectKind()) {
3476         Diag(New->getLocation(), diag::err_using_decl_friend);
3477         Diag(Shadow->getTargetDecl()->getLocation(),
3478              diag::note_using_decl_target);
3479         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3480             << 0;
3481         return true;
3482       }
3483 
3484       // Check whether the two declarations might declare the same function or
3485       // function template.
3486       if (FunctionTemplateDecl *NewTemplate =
3487               New->getDescribedFunctionTemplate()) {
3488         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3489                                                          NewTemplate))
3490           return true;
3491         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3492                          ->getAsFunction();
3493       } else {
3494         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3495           return true;
3496         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3497       }
3498     } else {
3499       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3500         << New->getDeclName();
3501       notePreviousDefinition(OldD, New->getLocation());
3502       return true;
3503     }
3504   }
3505 
3506   // If the old declaration was found in an inline namespace and the new
3507   // declaration was qualified, update the DeclContext to match.
3508   adjustDeclContextForDeclaratorDecl(New, Old);
3509 
3510   // If the old declaration is invalid, just give up here.
3511   if (Old->isInvalidDecl())
3512     return true;
3513 
3514   // Disallow redeclaration of some builtins.
3515   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3516     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3517     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3518         << Old << Old->getType();
3519     return true;
3520   }
3521 
3522   diag::kind PrevDiag;
3523   SourceLocation OldLocation;
3524   std::tie(PrevDiag, OldLocation) =
3525       getNoteDiagForInvalidRedeclaration(Old, New);
3526 
3527   // Don't complain about this if we're in GNU89 mode and the old function
3528   // is an extern inline function.
3529   // Don't complain about specializations. They are not supposed to have
3530   // storage classes.
3531   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3532       New->getStorageClass() == SC_Static &&
3533       Old->hasExternalFormalLinkage() &&
3534       !New->getTemplateSpecializationInfo() &&
3535       !canRedefineFunction(Old, getLangOpts())) {
3536     if (getLangOpts().MicrosoftExt) {
3537       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3538       Diag(OldLocation, PrevDiag);
3539     } else {
3540       Diag(New->getLocation(), diag::err_static_non_static) << New;
3541       Diag(OldLocation, PrevDiag);
3542       return true;
3543     }
3544   }
3545 
3546   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3547     if (!Old->hasAttr<InternalLinkageAttr>()) {
3548       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3549           << ILA;
3550       Diag(Old->getLocation(), diag::note_previous_declaration);
3551       New->dropAttr<InternalLinkageAttr>();
3552     }
3553 
3554   if (auto *EA = New->getAttr<ErrorAttr>()) {
3555     if (!Old->hasAttr<ErrorAttr>()) {
3556       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3557       Diag(Old->getLocation(), diag::note_previous_declaration);
3558       New->dropAttr<ErrorAttr>();
3559     }
3560   }
3561 
3562   if (CheckRedeclarationInModule(New, Old))
3563     return true;
3564 
3565   if (!getLangOpts().CPlusPlus) {
3566     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3567     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3568       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3569         << New << OldOvl;
3570 
3571       // Try our best to find a decl that actually has the overloadable
3572       // attribute for the note. In most cases (e.g. programs with only one
3573       // broken declaration/definition), this won't matter.
3574       //
3575       // FIXME: We could do this if we juggled some extra state in
3576       // OverloadableAttr, rather than just removing it.
3577       const Decl *DiagOld = Old;
3578       if (OldOvl) {
3579         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3580           const auto *A = D->getAttr<OverloadableAttr>();
3581           return A && !A->isImplicit();
3582         });
3583         // If we've implicitly added *all* of the overloadable attrs to this
3584         // chain, emitting a "previous redecl" note is pointless.
3585         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3586       }
3587 
3588       if (DiagOld)
3589         Diag(DiagOld->getLocation(),
3590              diag::note_attribute_overloadable_prev_overload)
3591           << OldOvl;
3592 
3593       if (OldOvl)
3594         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3595       else
3596         New->dropAttr<OverloadableAttr>();
3597     }
3598   }
3599 
3600   // If a function is first declared with a calling convention, but is later
3601   // declared or defined without one, all following decls assume the calling
3602   // convention of the first.
3603   //
3604   // It's OK if a function is first declared without a calling convention,
3605   // but is later declared or defined with the default calling convention.
3606   //
3607   // To test if either decl has an explicit calling convention, we look for
3608   // AttributedType sugar nodes on the type as written.  If they are missing or
3609   // were canonicalized away, we assume the calling convention was implicit.
3610   //
3611   // Note also that we DO NOT return at this point, because we still have
3612   // other tests to run.
3613   QualType OldQType = Context.getCanonicalType(Old->getType());
3614   QualType NewQType = Context.getCanonicalType(New->getType());
3615   const FunctionType *OldType = cast<FunctionType>(OldQType);
3616   const FunctionType *NewType = cast<FunctionType>(NewQType);
3617   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3618   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3619   bool RequiresAdjustment = false;
3620 
3621   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3622     FunctionDecl *First = Old->getFirstDecl();
3623     const FunctionType *FT =
3624         First->getType().getCanonicalType()->castAs<FunctionType>();
3625     FunctionType::ExtInfo FI = FT->getExtInfo();
3626     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3627     if (!NewCCExplicit) {
3628       // Inherit the CC from the previous declaration if it was specified
3629       // there but not here.
3630       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3631       RequiresAdjustment = true;
3632     } else if (Old->getBuiltinID()) {
3633       // Builtin attribute isn't propagated to the new one yet at this point,
3634       // so we check if the old one is a builtin.
3635 
3636       // Calling Conventions on a Builtin aren't really useful and setting a
3637       // default calling convention and cdecl'ing some builtin redeclarations is
3638       // common, so warn and ignore the calling convention on the redeclaration.
3639       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3640           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3641           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3642       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3643       RequiresAdjustment = true;
3644     } else {
3645       // Calling conventions aren't compatible, so complain.
3646       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3647       Diag(New->getLocation(), diag::err_cconv_change)
3648         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3649         << !FirstCCExplicit
3650         << (!FirstCCExplicit ? "" :
3651             FunctionType::getNameForCallConv(FI.getCC()));
3652 
3653       // Put the note on the first decl, since it is the one that matters.
3654       Diag(First->getLocation(), diag::note_previous_declaration);
3655       return true;
3656     }
3657   }
3658 
3659   // FIXME: diagnose the other way around?
3660   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3661     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3662     RequiresAdjustment = true;
3663   }
3664 
3665   // Merge regparm attribute.
3666   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3667       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3668     if (NewTypeInfo.getHasRegParm()) {
3669       Diag(New->getLocation(), diag::err_regparm_mismatch)
3670         << NewType->getRegParmType()
3671         << OldType->getRegParmType();
3672       Diag(OldLocation, diag::note_previous_declaration);
3673       return true;
3674     }
3675 
3676     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3677     RequiresAdjustment = true;
3678   }
3679 
3680   // Merge ns_returns_retained attribute.
3681   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3682     if (NewTypeInfo.getProducesResult()) {
3683       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3684           << "'ns_returns_retained'";
3685       Diag(OldLocation, diag::note_previous_declaration);
3686       return true;
3687     }
3688 
3689     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3690     RequiresAdjustment = true;
3691   }
3692 
3693   if (OldTypeInfo.getNoCallerSavedRegs() !=
3694       NewTypeInfo.getNoCallerSavedRegs()) {
3695     if (NewTypeInfo.getNoCallerSavedRegs()) {
3696       AnyX86NoCallerSavedRegistersAttr *Attr =
3697         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3698       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3699       Diag(OldLocation, diag::note_previous_declaration);
3700       return true;
3701     }
3702 
3703     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3704     RequiresAdjustment = true;
3705   }
3706 
3707   if (RequiresAdjustment) {
3708     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3709     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3710     New->setType(QualType(AdjustedType, 0));
3711     NewQType = Context.getCanonicalType(New->getType());
3712   }
3713 
3714   // If this redeclaration makes the function inline, we may need to add it to
3715   // UndefinedButUsed.
3716   if (!Old->isInlined() && New->isInlined() &&
3717       !New->hasAttr<GNUInlineAttr>() &&
3718       !getLangOpts().GNUInline &&
3719       Old->isUsed(false) &&
3720       !Old->isDefined() && !New->isThisDeclarationADefinition())
3721     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3722                                            SourceLocation()));
3723 
3724   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3725   // about it.
3726   if (New->hasAttr<GNUInlineAttr>() &&
3727       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3728     UndefinedButUsed.erase(Old->getCanonicalDecl());
3729   }
3730 
3731   // If pass_object_size params don't match up perfectly, this isn't a valid
3732   // redeclaration.
3733   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3734       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3735     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3736         << New->getDeclName();
3737     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3738     return true;
3739   }
3740 
3741   if (getLangOpts().CPlusPlus) {
3742     // C++1z [over.load]p2
3743     //   Certain function declarations cannot be overloaded:
3744     //     -- Function declarations that differ only in the return type,
3745     //        the exception specification, or both cannot be overloaded.
3746 
3747     // Check the exception specifications match. This may recompute the type of
3748     // both Old and New if it resolved exception specifications, so grab the
3749     // types again after this. Because this updates the type, we do this before
3750     // any of the other checks below, which may update the "de facto" NewQType
3751     // but do not necessarily update the type of New.
3752     if (CheckEquivalentExceptionSpec(Old, New))
3753       return true;
3754     OldQType = Context.getCanonicalType(Old->getType());
3755     NewQType = Context.getCanonicalType(New->getType());
3756 
3757     // Go back to the type source info to compare the declared return types,
3758     // per C++1y [dcl.type.auto]p13:
3759     //   Redeclarations or specializations of a function or function template
3760     //   with a declared return type that uses a placeholder type shall also
3761     //   use that placeholder, not a deduced type.
3762     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3763     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3764     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3765         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3766                                        OldDeclaredReturnType)) {
3767       QualType ResQT;
3768       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3769           OldDeclaredReturnType->isObjCObjectPointerType())
3770         // FIXME: This does the wrong thing for a deduced return type.
3771         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3772       if (ResQT.isNull()) {
3773         if (New->isCXXClassMember() && New->isOutOfLine())
3774           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3775               << New << New->getReturnTypeSourceRange();
3776         else
3777           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3778               << New->getReturnTypeSourceRange();
3779         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3780                                     << Old->getReturnTypeSourceRange();
3781         return true;
3782       }
3783       else
3784         NewQType = ResQT;
3785     }
3786 
3787     QualType OldReturnType = OldType->getReturnType();
3788     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3789     if (OldReturnType != NewReturnType) {
3790       // If this function has a deduced return type and has already been
3791       // defined, copy the deduced value from the old declaration.
3792       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3793       if (OldAT && OldAT->isDeduced()) {
3794         QualType DT = OldAT->getDeducedType();
3795         if (DT.isNull()) {
3796           New->setType(SubstAutoTypeDependent(New->getType()));
3797           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3798         } else {
3799           New->setType(SubstAutoType(New->getType(), DT));
3800           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3801         }
3802       }
3803     }
3804 
3805     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3806     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3807     if (OldMethod && NewMethod) {
3808       // Preserve triviality.
3809       NewMethod->setTrivial(OldMethod->isTrivial());
3810 
3811       // MSVC allows explicit template specialization at class scope:
3812       // 2 CXXMethodDecls referring to the same function will be injected.
3813       // We don't want a redeclaration error.
3814       bool IsClassScopeExplicitSpecialization =
3815                               OldMethod->isFunctionTemplateSpecialization() &&
3816                               NewMethod->isFunctionTemplateSpecialization();
3817       bool isFriend = NewMethod->getFriendObjectKind();
3818 
3819       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3820           !IsClassScopeExplicitSpecialization) {
3821         //    -- Member function declarations with the same name and the
3822         //       same parameter types cannot be overloaded if any of them
3823         //       is a static member function declaration.
3824         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3825           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3826           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3827           return true;
3828         }
3829 
3830         // C++ [class.mem]p1:
3831         //   [...] A member shall not be declared twice in the
3832         //   member-specification, except that a nested class or member
3833         //   class template can be declared and then later defined.
3834         if (!inTemplateInstantiation()) {
3835           unsigned NewDiag;
3836           if (isa<CXXConstructorDecl>(OldMethod))
3837             NewDiag = diag::err_constructor_redeclared;
3838           else if (isa<CXXDestructorDecl>(NewMethod))
3839             NewDiag = diag::err_destructor_redeclared;
3840           else if (isa<CXXConversionDecl>(NewMethod))
3841             NewDiag = diag::err_conv_function_redeclared;
3842           else
3843             NewDiag = diag::err_member_redeclared;
3844 
3845           Diag(New->getLocation(), NewDiag);
3846         } else {
3847           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3848             << New << New->getType();
3849         }
3850         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3851         return true;
3852 
3853       // Complain if this is an explicit declaration of a special
3854       // member that was initially declared implicitly.
3855       //
3856       // As an exception, it's okay to befriend such methods in order
3857       // to permit the implicit constructor/destructor/operator calls.
3858       } else if (OldMethod->isImplicit()) {
3859         if (isFriend) {
3860           NewMethod->setImplicit();
3861         } else {
3862           Diag(NewMethod->getLocation(),
3863                diag::err_definition_of_implicitly_declared_member)
3864             << New << getSpecialMember(OldMethod);
3865           return true;
3866         }
3867       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3868         Diag(NewMethod->getLocation(),
3869              diag::err_definition_of_explicitly_defaulted_member)
3870           << getSpecialMember(OldMethod);
3871         return true;
3872       }
3873     }
3874 
3875     // C++11 [dcl.attr.noreturn]p1:
3876     //   The first declaration of a function shall specify the noreturn
3877     //   attribute if any declaration of that function specifies the noreturn
3878     //   attribute.
3879     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3880       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3881         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3882             << NRA;
3883         Diag(Old->getLocation(), diag::note_previous_declaration);
3884       }
3885 
3886     // C++11 [dcl.attr.depend]p2:
3887     //   The first declaration of a function shall specify the
3888     //   carries_dependency attribute for its declarator-id if any declaration
3889     //   of the function specifies the carries_dependency attribute.
3890     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3891     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3892       Diag(CDA->getLocation(),
3893            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3894       Diag(Old->getFirstDecl()->getLocation(),
3895            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3896     }
3897 
3898     // (C++98 8.3.5p3):
3899     //   All declarations for a function shall agree exactly in both the
3900     //   return type and the parameter-type-list.
3901     // We also want to respect all the extended bits except noreturn.
3902 
3903     // noreturn should now match unless the old type info didn't have it.
3904     QualType OldQTypeForComparison = OldQType;
3905     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3906       auto *OldType = OldQType->castAs<FunctionProtoType>();
3907       const FunctionType *OldTypeForComparison
3908         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3909       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3910       assert(OldQTypeForComparison.isCanonical());
3911     }
3912 
3913     if (haveIncompatibleLanguageLinkages(Old, New)) {
3914       // As a special case, retain the language linkage from previous
3915       // declarations of a friend function as an extension.
3916       //
3917       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3918       // and is useful because there's otherwise no way to specify language
3919       // linkage within class scope.
3920       //
3921       // Check cautiously as the friend object kind isn't yet complete.
3922       if (New->getFriendObjectKind() != Decl::FOK_None) {
3923         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3924         Diag(OldLocation, PrevDiag);
3925       } else {
3926         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3927         Diag(OldLocation, PrevDiag);
3928         return true;
3929       }
3930     }
3931 
3932     // If the function types are compatible, merge the declarations. Ignore the
3933     // exception specifier because it was already checked above in
3934     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3935     // about incompatible types under -fms-compatibility.
3936     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3937                                                          NewQType))
3938       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3939 
3940     // If the types are imprecise (due to dependent constructs in friends or
3941     // local extern declarations), it's OK if they differ. We'll check again
3942     // during instantiation.
3943     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3944       return false;
3945 
3946     // Fall through for conflicting redeclarations and redefinitions.
3947   }
3948 
3949   // C: Function types need to be compatible, not identical. This handles
3950   // duplicate function decls like "void f(int); void f(enum X);" properly.
3951   if (!getLangOpts().CPlusPlus) {
3952     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3953     // type is specified by a function definition that contains a (possibly
3954     // empty) identifier list, both shall agree in the number of parameters
3955     // and the type of each parameter shall be compatible with the type that
3956     // results from the application of default argument promotions to the
3957     // type of the corresponding identifier. ...
3958     // This cannot be handled by ASTContext::typesAreCompatible() because that
3959     // doesn't know whether the function type is for a definition or not when
3960     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3961     // we need to cover here is that the number of arguments agree as the
3962     // default argument promotion rules were already checked by
3963     // ASTContext::typesAreCompatible().
3964     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3965         Old->getNumParams() != New->getNumParams()) {
3966       if (Old->hasInheritedPrototype())
3967         Old = Old->getCanonicalDecl();
3968       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3969       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3970       return true;
3971     }
3972 
3973     // If we are merging two functions where only one of them has a prototype,
3974     // we may have enough information to decide to issue a diagnostic that the
3975     // function without a protoype will change behavior in C2x. This handles
3976     // cases like:
3977     //   void i(); void i(int j);
3978     //   void i(int j); void i();
3979     //   void i(); void i(int j) {}
3980     // See ActOnFinishFunctionBody() for other cases of the behavior change
3981     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3982     // type without a prototype.
3983     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3984         !New->isImplicit() && !Old->isImplicit()) {
3985       const FunctionDecl *WithProto, *WithoutProto;
3986       if (New->hasWrittenPrototype()) {
3987         WithProto = New;
3988         WithoutProto = Old;
3989       } else {
3990         WithProto = Old;
3991         WithoutProto = New;
3992       }
3993 
3994       if (WithProto->getNumParams() != 0) {
3995         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3996           // The one without the prototype will be changing behavior in C2x, so
3997           // warn about that one so long as it's a user-visible declaration.
3998           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3999           if (WithoutProto == New)
4000             IsWithoutProtoADef = NewDeclIsDefn;
4001           else
4002             IsWithProtoADef = NewDeclIsDefn;
4003           Diag(WithoutProto->getLocation(),
4004                diag::warn_non_prototype_changes_behavior)
4005               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4006               << (WithoutProto == Old) << IsWithProtoADef;
4007 
4008           // The reason the one without the prototype will be changing behavior
4009           // is because of the one with the prototype, so note that so long as
4010           // it's a user-visible declaration. There is one exception to this:
4011           // when the new declaration is a definition without a prototype, the
4012           // old declaration with a prototype is not the cause of the issue,
4013           // and that does not need to be noted because the one with a
4014           // prototype will not change behavior in C2x.
4015           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4016               !IsWithoutProtoADef)
4017             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4018         }
4019       }
4020     }
4021 
4022     if (Context.typesAreCompatible(OldQType, NewQType)) {
4023       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4024       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4025       const FunctionProtoType *OldProto = nullptr;
4026       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4027           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4028         // The old declaration provided a function prototype, but the
4029         // new declaration does not. Merge in the prototype.
4030         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4031         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4032         NewQType =
4033             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4034                                     OldProto->getExtProtoInfo());
4035         New->setType(NewQType);
4036         New->setHasInheritedPrototype();
4037 
4038         // Synthesize parameters with the same types.
4039         SmallVector<ParmVarDecl *, 16> Params;
4040         for (const auto &ParamType : OldProto->param_types()) {
4041           ParmVarDecl *Param = ParmVarDecl::Create(
4042               Context, New, SourceLocation(), SourceLocation(), nullptr,
4043               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4044           Param->setScopeInfo(0, Params.size());
4045           Param->setImplicit();
4046           Params.push_back(Param);
4047         }
4048 
4049         New->setParams(Params);
4050       }
4051 
4052       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4053     }
4054   }
4055 
4056   // Check if the function types are compatible when pointer size address
4057   // spaces are ignored.
4058   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4059     return false;
4060 
4061   // GNU C permits a K&R definition to follow a prototype declaration
4062   // if the declared types of the parameters in the K&R definition
4063   // match the types in the prototype declaration, even when the
4064   // promoted types of the parameters from the K&R definition differ
4065   // from the types in the prototype. GCC then keeps the types from
4066   // the prototype.
4067   //
4068   // If a variadic prototype is followed by a non-variadic K&R definition,
4069   // the K&R definition becomes variadic.  This is sort of an edge case, but
4070   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4071   // C99 6.9.1p8.
4072   if (!getLangOpts().CPlusPlus &&
4073       Old->hasPrototype() && !New->hasPrototype() &&
4074       New->getType()->getAs<FunctionProtoType>() &&
4075       Old->getNumParams() == New->getNumParams()) {
4076     SmallVector<QualType, 16> ArgTypes;
4077     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4078     const FunctionProtoType *OldProto
4079       = Old->getType()->getAs<FunctionProtoType>();
4080     const FunctionProtoType *NewProto
4081       = New->getType()->getAs<FunctionProtoType>();
4082 
4083     // Determine whether this is the GNU C extension.
4084     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4085                                                NewProto->getReturnType());
4086     bool LooseCompatible = !MergedReturn.isNull();
4087     for (unsigned Idx = 0, End = Old->getNumParams();
4088          LooseCompatible && Idx != End; ++Idx) {
4089       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4090       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4091       if (Context.typesAreCompatible(OldParm->getType(),
4092                                      NewProto->getParamType(Idx))) {
4093         ArgTypes.push_back(NewParm->getType());
4094       } else if (Context.typesAreCompatible(OldParm->getType(),
4095                                             NewParm->getType(),
4096                                             /*CompareUnqualified=*/true)) {
4097         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4098                                            NewProto->getParamType(Idx) };
4099         Warnings.push_back(Warn);
4100         ArgTypes.push_back(NewParm->getType());
4101       } else
4102         LooseCompatible = false;
4103     }
4104 
4105     if (LooseCompatible) {
4106       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4107         Diag(Warnings[Warn].NewParm->getLocation(),
4108              diag::ext_param_promoted_not_compatible_with_prototype)
4109           << Warnings[Warn].PromotedType
4110           << Warnings[Warn].OldParm->getType();
4111         if (Warnings[Warn].OldParm->getLocation().isValid())
4112           Diag(Warnings[Warn].OldParm->getLocation(),
4113                diag::note_previous_declaration);
4114       }
4115 
4116       if (MergeTypeWithOld)
4117         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4118                                              OldProto->getExtProtoInfo()));
4119       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4120     }
4121 
4122     // Fall through to diagnose conflicting types.
4123   }
4124 
4125   // A function that has already been declared has been redeclared or
4126   // defined with a different type; show an appropriate diagnostic.
4127 
4128   // If the previous declaration was an implicitly-generated builtin
4129   // declaration, then at the very least we should use a specialized note.
4130   unsigned BuiltinID;
4131   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4132     // If it's actually a library-defined builtin function like 'malloc'
4133     // or 'printf', just warn about the incompatible redeclaration.
4134     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4135       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4136       Diag(OldLocation, diag::note_previous_builtin_declaration)
4137         << Old << Old->getType();
4138       return false;
4139     }
4140 
4141     PrevDiag = diag::note_previous_builtin_declaration;
4142   }
4143 
4144   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4145   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4146   return true;
4147 }
4148 
4149 /// Completes the merge of two function declarations that are
4150 /// known to be compatible.
4151 ///
4152 /// This routine handles the merging of attributes and other
4153 /// properties of function declarations from the old declaration to
4154 /// the new declaration, once we know that New is in fact a
4155 /// redeclaration of Old.
4156 ///
4157 /// \returns false
4158 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4159                                         Scope *S, bool MergeTypeWithOld) {
4160   // Merge the attributes
4161   mergeDeclAttributes(New, Old);
4162 
4163   // Merge "pure" flag.
4164   if (Old->isPure())
4165     New->setPure();
4166 
4167   // Merge "used" flag.
4168   if (Old->getMostRecentDecl()->isUsed(false))
4169     New->setIsUsed();
4170 
4171   // Merge attributes from the parameters.  These can mismatch with K&R
4172   // declarations.
4173   if (New->getNumParams() == Old->getNumParams())
4174       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4175         ParmVarDecl *NewParam = New->getParamDecl(i);
4176         ParmVarDecl *OldParam = Old->getParamDecl(i);
4177         mergeParamDeclAttributes(NewParam, OldParam, *this);
4178         mergeParamDeclTypes(NewParam, OldParam, *this);
4179       }
4180 
4181   if (getLangOpts().CPlusPlus)
4182     return MergeCXXFunctionDecl(New, Old, S);
4183 
4184   // Merge the function types so the we get the composite types for the return
4185   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4186   // was visible.
4187   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4188   if (!Merged.isNull() && MergeTypeWithOld)
4189     New->setType(Merged);
4190 
4191   return false;
4192 }
4193 
4194 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4195                                 ObjCMethodDecl *oldMethod) {
4196   // Merge the attributes, including deprecated/unavailable
4197   AvailabilityMergeKind MergeKind =
4198       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4199           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4200                                      : AMK_ProtocolImplementation)
4201           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4202                                                            : AMK_Override;
4203 
4204   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4205 
4206   // Merge attributes from the parameters.
4207   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4208                                        oe = oldMethod->param_end();
4209   for (ObjCMethodDecl::param_iterator
4210          ni = newMethod->param_begin(), ne = newMethod->param_end();
4211        ni != ne && oi != oe; ++ni, ++oi)
4212     mergeParamDeclAttributes(*ni, *oi, *this);
4213 
4214   CheckObjCMethodOverride(newMethod, oldMethod);
4215 }
4216 
4217 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4218   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4219 
4220   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4221          ? diag::err_redefinition_different_type
4222          : diag::err_redeclaration_different_type)
4223     << New->getDeclName() << New->getType() << Old->getType();
4224 
4225   diag::kind PrevDiag;
4226   SourceLocation OldLocation;
4227   std::tie(PrevDiag, OldLocation)
4228     = getNoteDiagForInvalidRedeclaration(Old, New);
4229   S.Diag(OldLocation, PrevDiag);
4230   New->setInvalidDecl();
4231 }
4232 
4233 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4234 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4235 /// emitting diagnostics as appropriate.
4236 ///
4237 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4238 /// to here in AddInitializerToDecl. We can't check them before the initializer
4239 /// is attached.
4240 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4241                              bool MergeTypeWithOld) {
4242   if (New->isInvalidDecl() || Old->isInvalidDecl())
4243     return;
4244 
4245   QualType MergedT;
4246   if (getLangOpts().CPlusPlus) {
4247     if (New->getType()->isUndeducedType()) {
4248       // We don't know what the new type is until the initializer is attached.
4249       return;
4250     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4251       // These could still be something that needs exception specs checked.
4252       return MergeVarDeclExceptionSpecs(New, Old);
4253     }
4254     // C++ [basic.link]p10:
4255     //   [...] the types specified by all declarations referring to a given
4256     //   object or function shall be identical, except that declarations for an
4257     //   array object can specify array types that differ by the presence or
4258     //   absence of a major array bound (8.3.4).
4259     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4260       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4261       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4262 
4263       // We are merging a variable declaration New into Old. If it has an array
4264       // bound, and that bound differs from Old's bound, we should diagnose the
4265       // mismatch.
4266       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4267         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4268              PrevVD = PrevVD->getPreviousDecl()) {
4269           QualType PrevVDTy = PrevVD->getType();
4270           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4271             continue;
4272 
4273           if (!Context.hasSameType(New->getType(), PrevVDTy))
4274             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4275         }
4276       }
4277 
4278       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4279         if (Context.hasSameType(OldArray->getElementType(),
4280                                 NewArray->getElementType()))
4281           MergedT = New->getType();
4282       }
4283       // FIXME: Check visibility. New is hidden but has a complete type. If New
4284       // has no array bound, it should not inherit one from Old, if Old is not
4285       // visible.
4286       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4287         if (Context.hasSameType(OldArray->getElementType(),
4288                                 NewArray->getElementType()))
4289           MergedT = Old->getType();
4290       }
4291     }
4292     else if (New->getType()->isObjCObjectPointerType() &&
4293                Old->getType()->isObjCObjectPointerType()) {
4294       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4295                                               Old->getType());
4296     }
4297   } else {
4298     // C 6.2.7p2:
4299     //   All declarations that refer to the same object or function shall have
4300     //   compatible type.
4301     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4302   }
4303   if (MergedT.isNull()) {
4304     // It's OK if we couldn't merge types if either type is dependent, for a
4305     // block-scope variable. In other cases (static data members of class
4306     // templates, variable templates, ...), we require the types to be
4307     // equivalent.
4308     // FIXME: The C++ standard doesn't say anything about this.
4309     if ((New->getType()->isDependentType() ||
4310          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4311       // If the old type was dependent, we can't merge with it, so the new type
4312       // becomes dependent for now. We'll reproduce the original type when we
4313       // instantiate the TypeSourceInfo for the variable.
4314       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4315         New->setType(Context.DependentTy);
4316       return;
4317     }
4318     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4319   }
4320 
4321   // Don't actually update the type on the new declaration if the old
4322   // declaration was an extern declaration in a different scope.
4323   if (MergeTypeWithOld)
4324     New->setType(MergedT);
4325 }
4326 
4327 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4328                                   LookupResult &Previous) {
4329   // C11 6.2.7p4:
4330   //   For an identifier with internal or external linkage declared
4331   //   in a scope in which a prior declaration of that identifier is
4332   //   visible, if the prior declaration specifies internal or
4333   //   external linkage, the type of the identifier at the later
4334   //   declaration becomes the composite type.
4335   //
4336   // If the variable isn't visible, we do not merge with its type.
4337   if (Previous.isShadowed())
4338     return false;
4339 
4340   if (S.getLangOpts().CPlusPlus) {
4341     // C++11 [dcl.array]p3:
4342     //   If there is a preceding declaration of the entity in the same
4343     //   scope in which the bound was specified, an omitted array bound
4344     //   is taken to be the same as in that earlier declaration.
4345     return NewVD->isPreviousDeclInSameBlockScope() ||
4346            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4347             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4348   } else {
4349     // If the old declaration was function-local, don't merge with its
4350     // type unless we're in the same function.
4351     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4352            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4353   }
4354 }
4355 
4356 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4357 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4358 /// situation, merging decls or emitting diagnostics as appropriate.
4359 ///
4360 /// Tentative definition rules (C99 6.9.2p2) are checked by
4361 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4362 /// definitions here, since the initializer hasn't been attached.
4363 ///
4364 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4365   // If the new decl is already invalid, don't do any other checking.
4366   if (New->isInvalidDecl())
4367     return;
4368 
4369   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4370     return;
4371 
4372   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4373 
4374   // Verify the old decl was also a variable or variable template.
4375   VarDecl *Old = nullptr;
4376   VarTemplateDecl *OldTemplate = nullptr;
4377   if (Previous.isSingleResult()) {
4378     if (NewTemplate) {
4379       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4380       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4381 
4382       if (auto *Shadow =
4383               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4384         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4385           return New->setInvalidDecl();
4386     } else {
4387       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4388 
4389       if (auto *Shadow =
4390               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4391         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4392           return New->setInvalidDecl();
4393     }
4394   }
4395   if (!Old) {
4396     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4397         << New->getDeclName();
4398     notePreviousDefinition(Previous.getRepresentativeDecl(),
4399                            New->getLocation());
4400     return New->setInvalidDecl();
4401   }
4402 
4403   // If the old declaration was found in an inline namespace and the new
4404   // declaration was qualified, update the DeclContext to match.
4405   adjustDeclContextForDeclaratorDecl(New, Old);
4406 
4407   // Ensure the template parameters are compatible.
4408   if (NewTemplate &&
4409       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4410                                       OldTemplate->getTemplateParameters(),
4411                                       /*Complain=*/true, TPL_TemplateMatch))
4412     return New->setInvalidDecl();
4413 
4414   // C++ [class.mem]p1:
4415   //   A member shall not be declared twice in the member-specification [...]
4416   //
4417   // Here, we need only consider static data members.
4418   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4419     Diag(New->getLocation(), diag::err_duplicate_member)
4420       << New->getIdentifier();
4421     Diag(Old->getLocation(), diag::note_previous_declaration);
4422     New->setInvalidDecl();
4423   }
4424 
4425   mergeDeclAttributes(New, Old);
4426   // Warn if an already-declared variable is made a weak_import in a subsequent
4427   // declaration
4428   if (New->hasAttr<WeakImportAttr>() &&
4429       Old->getStorageClass() == SC_None &&
4430       !Old->hasAttr<WeakImportAttr>()) {
4431     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4432     Diag(Old->getLocation(), diag::note_previous_declaration);
4433     // Remove weak_import attribute on new declaration.
4434     New->dropAttr<WeakImportAttr>();
4435   }
4436 
4437   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4438     if (!Old->hasAttr<InternalLinkageAttr>()) {
4439       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4440           << ILA;
4441       Diag(Old->getLocation(), diag::note_previous_declaration);
4442       New->dropAttr<InternalLinkageAttr>();
4443     }
4444 
4445   // Merge the types.
4446   VarDecl *MostRecent = Old->getMostRecentDecl();
4447   if (MostRecent != Old) {
4448     MergeVarDeclTypes(New, MostRecent,
4449                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4450     if (New->isInvalidDecl())
4451       return;
4452   }
4453 
4454   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4455   if (New->isInvalidDecl())
4456     return;
4457 
4458   diag::kind PrevDiag;
4459   SourceLocation OldLocation;
4460   std::tie(PrevDiag, OldLocation) =
4461       getNoteDiagForInvalidRedeclaration(Old, New);
4462 
4463   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4464   if (New->getStorageClass() == SC_Static &&
4465       !New->isStaticDataMember() &&
4466       Old->hasExternalFormalLinkage()) {
4467     if (getLangOpts().MicrosoftExt) {
4468       Diag(New->getLocation(), diag::ext_static_non_static)
4469           << New->getDeclName();
4470       Diag(OldLocation, PrevDiag);
4471     } else {
4472       Diag(New->getLocation(), diag::err_static_non_static)
4473           << New->getDeclName();
4474       Diag(OldLocation, PrevDiag);
4475       return New->setInvalidDecl();
4476     }
4477   }
4478   // C99 6.2.2p4:
4479   //   For an identifier declared with the storage-class specifier
4480   //   extern in a scope in which a prior declaration of that
4481   //   identifier is visible,23) if the prior declaration specifies
4482   //   internal or external linkage, the linkage of the identifier at
4483   //   the later declaration is the same as the linkage specified at
4484   //   the prior declaration. If no prior declaration is visible, or
4485   //   if the prior declaration specifies no linkage, then the
4486   //   identifier has external linkage.
4487   if (New->hasExternalStorage() && Old->hasLinkage())
4488     /* Okay */;
4489   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4490            !New->isStaticDataMember() &&
4491            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4492     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4493     Diag(OldLocation, PrevDiag);
4494     return New->setInvalidDecl();
4495   }
4496 
4497   // Check if extern is followed by non-extern and vice-versa.
4498   if (New->hasExternalStorage() &&
4499       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4500     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4501     Diag(OldLocation, PrevDiag);
4502     return New->setInvalidDecl();
4503   }
4504   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4505       !New->hasExternalStorage()) {
4506     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4507     Diag(OldLocation, PrevDiag);
4508     return New->setInvalidDecl();
4509   }
4510 
4511   if (CheckRedeclarationInModule(New, Old))
4512     return;
4513 
4514   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4515 
4516   // FIXME: The test for external storage here seems wrong? We still
4517   // need to check for mismatches.
4518   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4519       // Don't complain about out-of-line definitions of static members.
4520       !(Old->getLexicalDeclContext()->isRecord() &&
4521         !New->getLexicalDeclContext()->isRecord())) {
4522     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4523     Diag(OldLocation, PrevDiag);
4524     return New->setInvalidDecl();
4525   }
4526 
4527   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4528     if (VarDecl *Def = Old->getDefinition()) {
4529       // C++1z [dcl.fcn.spec]p4:
4530       //   If the definition of a variable appears in a translation unit before
4531       //   its first declaration as inline, the program is ill-formed.
4532       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4533       Diag(Def->getLocation(), diag::note_previous_definition);
4534     }
4535   }
4536 
4537   // If this redeclaration makes the variable inline, we may need to add it to
4538   // UndefinedButUsed.
4539   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4540       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4541     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4542                                            SourceLocation()));
4543 
4544   if (New->getTLSKind() != Old->getTLSKind()) {
4545     if (!Old->getTLSKind()) {
4546       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4547       Diag(OldLocation, PrevDiag);
4548     } else if (!New->getTLSKind()) {
4549       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4550       Diag(OldLocation, PrevDiag);
4551     } else {
4552       // Do not allow redeclaration to change the variable between requiring
4553       // static and dynamic initialization.
4554       // FIXME: GCC allows this, but uses the TLS keyword on the first
4555       // declaration to determine the kind. Do we need to be compatible here?
4556       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4557         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4558       Diag(OldLocation, PrevDiag);
4559     }
4560   }
4561 
4562   // C++ doesn't have tentative definitions, so go right ahead and check here.
4563   if (getLangOpts().CPlusPlus) {
4564     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4565         Old->getCanonicalDecl()->isConstexpr()) {
4566       // This definition won't be a definition any more once it's been merged.
4567       Diag(New->getLocation(),
4568            diag::warn_deprecated_redundant_constexpr_static_def);
4569     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4570       VarDecl *Def = Old->getDefinition();
4571       if (Def && checkVarDeclRedefinition(Def, New))
4572         return;
4573     }
4574   }
4575 
4576   if (haveIncompatibleLanguageLinkages(Old, New)) {
4577     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4578     Diag(OldLocation, PrevDiag);
4579     New->setInvalidDecl();
4580     return;
4581   }
4582 
4583   // Merge "used" flag.
4584   if (Old->getMostRecentDecl()->isUsed(false))
4585     New->setIsUsed();
4586 
4587   // Keep a chain of previous declarations.
4588   New->setPreviousDecl(Old);
4589   if (NewTemplate)
4590     NewTemplate->setPreviousDecl(OldTemplate);
4591 
4592   // Inherit access appropriately.
4593   New->setAccess(Old->getAccess());
4594   if (NewTemplate)
4595     NewTemplate->setAccess(New->getAccess());
4596 
4597   if (Old->isInline())
4598     New->setImplicitlyInline();
4599 }
4600 
4601 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4602   SourceManager &SrcMgr = getSourceManager();
4603   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4604   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4605   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4606   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4607   auto &HSI = PP.getHeaderSearchInfo();
4608   StringRef HdrFilename =
4609       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4610 
4611   auto noteFromModuleOrInclude = [&](Module *Mod,
4612                                      SourceLocation IncLoc) -> bool {
4613     // Redefinition errors with modules are common with non modular mapped
4614     // headers, example: a non-modular header H in module A that also gets
4615     // included directly in a TU. Pointing twice to the same header/definition
4616     // is confusing, try to get better diagnostics when modules is on.
4617     if (IncLoc.isValid()) {
4618       if (Mod) {
4619         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4620             << HdrFilename.str() << Mod->getFullModuleName();
4621         if (!Mod->DefinitionLoc.isInvalid())
4622           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4623               << Mod->getFullModuleName();
4624       } else {
4625         Diag(IncLoc, diag::note_redefinition_include_same_file)
4626             << HdrFilename.str();
4627       }
4628       return true;
4629     }
4630 
4631     return false;
4632   };
4633 
4634   // Is it the same file and same offset? Provide more information on why
4635   // this leads to a redefinition error.
4636   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4637     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4638     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4639     bool EmittedDiag =
4640         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4641     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4642 
4643     // If the header has no guards, emit a note suggesting one.
4644     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4645       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4646 
4647     if (EmittedDiag)
4648       return;
4649   }
4650 
4651   // Redefinition coming from different files or couldn't do better above.
4652   if (Old->getLocation().isValid())
4653     Diag(Old->getLocation(), diag::note_previous_definition);
4654 }
4655 
4656 /// We've just determined that \p Old and \p New both appear to be definitions
4657 /// of the same variable. Either diagnose or fix the problem.
4658 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4659   if (!hasVisibleDefinition(Old) &&
4660       (New->getFormalLinkage() == InternalLinkage ||
4661        New->isInline() ||
4662        New->getDescribedVarTemplate() ||
4663        New->getNumTemplateParameterLists() ||
4664        New->getDeclContext()->isDependentContext())) {
4665     // The previous definition is hidden, and multiple definitions are
4666     // permitted (in separate TUs). Demote this to a declaration.
4667     New->demoteThisDefinitionToDeclaration();
4668 
4669     // Make the canonical definition visible.
4670     if (auto *OldTD = Old->getDescribedVarTemplate())
4671       makeMergedDefinitionVisible(OldTD);
4672     makeMergedDefinitionVisible(Old);
4673     return false;
4674   } else {
4675     Diag(New->getLocation(), diag::err_redefinition) << New;
4676     notePreviousDefinition(Old, New->getLocation());
4677     New->setInvalidDecl();
4678     return true;
4679   }
4680 }
4681 
4682 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4683 /// no declarator (e.g. "struct foo;") is parsed.
4684 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4685                                        DeclSpec &DS,
4686                                        const ParsedAttributesView &DeclAttrs,
4687                                        RecordDecl *&AnonRecord) {
4688   return ParsedFreeStandingDeclSpec(
4689       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4690 }
4691 
4692 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4693 // disambiguate entities defined in different scopes.
4694 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4695 // compatibility.
4696 // We will pick our mangling number depending on which version of MSVC is being
4697 // targeted.
4698 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4699   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4700              ? S->getMSCurManglingNumber()
4701              : S->getMSLastManglingNumber();
4702 }
4703 
4704 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4705   if (!Context.getLangOpts().CPlusPlus)
4706     return;
4707 
4708   if (isa<CXXRecordDecl>(Tag->getParent())) {
4709     // If this tag is the direct child of a class, number it if
4710     // it is anonymous.
4711     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4712       return;
4713     MangleNumberingContext &MCtx =
4714         Context.getManglingNumberContext(Tag->getParent());
4715     Context.setManglingNumber(
4716         Tag, MCtx.getManglingNumber(
4717                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4718     return;
4719   }
4720 
4721   // If this tag isn't a direct child of a class, number it if it is local.
4722   MangleNumberingContext *MCtx;
4723   Decl *ManglingContextDecl;
4724   std::tie(MCtx, ManglingContextDecl) =
4725       getCurrentMangleNumberContext(Tag->getDeclContext());
4726   if (MCtx) {
4727     Context.setManglingNumber(
4728         Tag, MCtx->getManglingNumber(
4729                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4730   }
4731 }
4732 
4733 namespace {
4734 struct NonCLikeKind {
4735   enum {
4736     None,
4737     BaseClass,
4738     DefaultMemberInit,
4739     Lambda,
4740     Friend,
4741     OtherMember,
4742     Invalid,
4743   } Kind = None;
4744   SourceRange Range;
4745 
4746   explicit operator bool() { return Kind != None; }
4747 };
4748 }
4749 
4750 /// Determine whether a class is C-like, according to the rules of C++
4751 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4752 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4753   if (RD->isInvalidDecl())
4754     return {NonCLikeKind::Invalid, {}};
4755 
4756   // C++ [dcl.typedef]p9: [P1766R1]
4757   //   An unnamed class with a typedef name for linkage purposes shall not
4758   //
4759   //    -- have any base classes
4760   if (RD->getNumBases())
4761     return {NonCLikeKind::BaseClass,
4762             SourceRange(RD->bases_begin()->getBeginLoc(),
4763                         RD->bases_end()[-1].getEndLoc())};
4764   bool Invalid = false;
4765   for (Decl *D : RD->decls()) {
4766     // Don't complain about things we already diagnosed.
4767     if (D->isInvalidDecl()) {
4768       Invalid = true;
4769       continue;
4770     }
4771 
4772     //  -- have any [...] default member initializers
4773     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4774       if (FD->hasInClassInitializer()) {
4775         auto *Init = FD->getInClassInitializer();
4776         return {NonCLikeKind::DefaultMemberInit,
4777                 Init ? Init->getSourceRange() : D->getSourceRange()};
4778       }
4779       continue;
4780     }
4781 
4782     // FIXME: We don't allow friend declarations. This violates the wording of
4783     // P1766, but not the intent.
4784     if (isa<FriendDecl>(D))
4785       return {NonCLikeKind::Friend, D->getSourceRange()};
4786 
4787     //  -- declare any members other than non-static data members, member
4788     //     enumerations, or member classes,
4789     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4790         isa<EnumDecl>(D))
4791       continue;
4792     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4793     if (!MemberRD) {
4794       if (D->isImplicit())
4795         continue;
4796       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4797     }
4798 
4799     //  -- contain a lambda-expression,
4800     if (MemberRD->isLambda())
4801       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4802 
4803     //  and all member classes shall also satisfy these requirements
4804     //  (recursively).
4805     if (MemberRD->isThisDeclarationADefinition()) {
4806       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4807         return Kind;
4808     }
4809   }
4810 
4811   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4812 }
4813 
4814 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4815                                         TypedefNameDecl *NewTD) {
4816   if (TagFromDeclSpec->isInvalidDecl())
4817     return;
4818 
4819   // Do nothing if the tag already has a name for linkage purposes.
4820   if (TagFromDeclSpec->hasNameForLinkage())
4821     return;
4822 
4823   // A well-formed anonymous tag must always be a TUK_Definition.
4824   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4825 
4826   // The type must match the tag exactly;  no qualifiers allowed.
4827   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4828                            Context.getTagDeclType(TagFromDeclSpec))) {
4829     if (getLangOpts().CPlusPlus)
4830       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4831     return;
4832   }
4833 
4834   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4835   //   An unnamed class with a typedef name for linkage purposes shall [be
4836   //   C-like].
4837   //
4838   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4839   // shouldn't happen, but there are constructs that the language rule doesn't
4840   // disallow for which we can't reasonably avoid computing linkage early.
4841   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4842   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4843                              : NonCLikeKind();
4844   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4845   if (NonCLike || ChangesLinkage) {
4846     if (NonCLike.Kind == NonCLikeKind::Invalid)
4847       return;
4848 
4849     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4850     if (ChangesLinkage) {
4851       // If the linkage changes, we can't accept this as an extension.
4852       if (NonCLike.Kind == NonCLikeKind::None)
4853         DiagID = diag::err_typedef_changes_linkage;
4854       else
4855         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4856     }
4857 
4858     SourceLocation FixitLoc =
4859         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4860     llvm::SmallString<40> TextToInsert;
4861     TextToInsert += ' ';
4862     TextToInsert += NewTD->getIdentifier()->getName();
4863 
4864     Diag(FixitLoc, DiagID)
4865       << isa<TypeAliasDecl>(NewTD)
4866       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4867     if (NonCLike.Kind != NonCLikeKind::None) {
4868       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4869         << NonCLike.Kind - 1 << NonCLike.Range;
4870     }
4871     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4872       << NewTD << isa<TypeAliasDecl>(NewTD);
4873 
4874     if (ChangesLinkage)
4875       return;
4876   }
4877 
4878   // Otherwise, set this as the anon-decl typedef for the tag.
4879   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4880 }
4881 
4882 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4883   switch (T) {
4884   case DeclSpec::TST_class:
4885     return 0;
4886   case DeclSpec::TST_struct:
4887     return 1;
4888   case DeclSpec::TST_interface:
4889     return 2;
4890   case DeclSpec::TST_union:
4891     return 3;
4892   case DeclSpec::TST_enum:
4893     return 4;
4894   default:
4895     llvm_unreachable("unexpected type specifier");
4896   }
4897 }
4898 
4899 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4900 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4901 /// parameters to cope with template friend declarations.
4902 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4903                                        DeclSpec &DS,
4904                                        const ParsedAttributesView &DeclAttrs,
4905                                        MultiTemplateParamsArg TemplateParams,
4906                                        bool IsExplicitInstantiation,
4907                                        RecordDecl *&AnonRecord) {
4908   Decl *TagD = nullptr;
4909   TagDecl *Tag = nullptr;
4910   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4911       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4912       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4913       DS.getTypeSpecType() == DeclSpec::TST_union ||
4914       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4915     TagD = DS.getRepAsDecl();
4916 
4917     if (!TagD) // We probably had an error
4918       return nullptr;
4919 
4920     // Note that the above type specs guarantee that the
4921     // type rep is a Decl, whereas in many of the others
4922     // it's a Type.
4923     if (isa<TagDecl>(TagD))
4924       Tag = cast<TagDecl>(TagD);
4925     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4926       Tag = CTD->getTemplatedDecl();
4927   }
4928 
4929   if (Tag) {
4930     handleTagNumbering(Tag, S);
4931     Tag->setFreeStanding();
4932     if (Tag->isInvalidDecl())
4933       return Tag;
4934   }
4935 
4936   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4937     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4938     // or incomplete types shall not be restrict-qualified."
4939     if (TypeQuals & DeclSpec::TQ_restrict)
4940       Diag(DS.getRestrictSpecLoc(),
4941            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4942            << DS.getSourceRange();
4943   }
4944 
4945   if (DS.isInlineSpecified())
4946     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4947         << getLangOpts().CPlusPlus17;
4948 
4949   if (DS.hasConstexprSpecifier()) {
4950     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4951     // and definitions of functions and variables.
4952     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4953     // the declaration of a function or function template
4954     if (Tag)
4955       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4956           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4957           << static_cast<int>(DS.getConstexprSpecifier());
4958     else
4959       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4960           << static_cast<int>(DS.getConstexprSpecifier());
4961     // Don't emit warnings after this error.
4962     return TagD;
4963   }
4964 
4965   DiagnoseFunctionSpecifiers(DS);
4966 
4967   if (DS.isFriendSpecified()) {
4968     // If we're dealing with a decl but not a TagDecl, assume that
4969     // whatever routines created it handled the friendship aspect.
4970     if (TagD && !Tag)
4971       return nullptr;
4972     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4973   }
4974 
4975   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4976   bool IsExplicitSpecialization =
4977     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4978   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4979       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4980       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4981     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4982     // nested-name-specifier unless it is an explicit instantiation
4983     // or an explicit specialization.
4984     //
4985     // FIXME: We allow class template partial specializations here too, per the
4986     // obvious intent of DR1819.
4987     //
4988     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4989     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4990         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4991     return nullptr;
4992   }
4993 
4994   // Track whether this decl-specifier declares anything.
4995   bool DeclaresAnything = true;
4996 
4997   // Handle anonymous struct definitions.
4998   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4999     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5000         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5001       if (getLangOpts().CPlusPlus ||
5002           Record->getDeclContext()->isRecord()) {
5003         // If CurContext is a DeclContext that can contain statements,
5004         // RecursiveASTVisitor won't visit the decls that
5005         // BuildAnonymousStructOrUnion() will put into CurContext.
5006         // Also store them here so that they can be part of the
5007         // DeclStmt that gets created in this case.
5008         // FIXME: Also return the IndirectFieldDecls created by
5009         // BuildAnonymousStructOr union, for the same reason?
5010         if (CurContext->isFunctionOrMethod())
5011           AnonRecord = Record;
5012         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5013                                            Context.getPrintingPolicy());
5014       }
5015 
5016       DeclaresAnything = false;
5017     }
5018   }
5019 
5020   // C11 6.7.2.1p2:
5021   //   A struct-declaration that does not declare an anonymous structure or
5022   //   anonymous union shall contain a struct-declarator-list.
5023   //
5024   // This rule also existed in C89 and C99; the grammar for struct-declaration
5025   // did not permit a struct-declaration without a struct-declarator-list.
5026   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5027       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5028     // Check for Microsoft C extension: anonymous struct/union member.
5029     // Handle 2 kinds of anonymous struct/union:
5030     //   struct STRUCT;
5031     //   union UNION;
5032     // and
5033     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5034     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5035     if ((Tag && Tag->getDeclName()) ||
5036         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5037       RecordDecl *Record = nullptr;
5038       if (Tag)
5039         Record = dyn_cast<RecordDecl>(Tag);
5040       else if (const RecordType *RT =
5041                    DS.getRepAsType().get()->getAsStructureType())
5042         Record = RT->getDecl();
5043       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5044         Record = UT->getDecl();
5045 
5046       if (Record && getLangOpts().MicrosoftExt) {
5047         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5048             << Record->isUnion() << DS.getSourceRange();
5049         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5050       }
5051 
5052       DeclaresAnything = false;
5053     }
5054   }
5055 
5056   // Skip all the checks below if we have a type error.
5057   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5058       (TagD && TagD->isInvalidDecl()))
5059     return TagD;
5060 
5061   if (getLangOpts().CPlusPlus &&
5062       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5063     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5064       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5065           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5066         DeclaresAnything = false;
5067 
5068   if (!DS.isMissingDeclaratorOk()) {
5069     // Customize diagnostic for a typedef missing a name.
5070     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5071       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5072           << DS.getSourceRange();
5073     else
5074       DeclaresAnything = false;
5075   }
5076 
5077   if (DS.isModulePrivateSpecified() &&
5078       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5079     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5080       << Tag->getTagKind()
5081       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5082 
5083   ActOnDocumentableDecl(TagD);
5084 
5085   // C 6.7/2:
5086   //   A declaration [...] shall declare at least a declarator [...], a tag,
5087   //   or the members of an enumeration.
5088   // C++ [dcl.dcl]p3:
5089   //   [If there are no declarators], and except for the declaration of an
5090   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5091   //   names into the program, or shall redeclare a name introduced by a
5092   //   previous declaration.
5093   if (!DeclaresAnything) {
5094     // In C, we allow this as a (popular) extension / bug. Don't bother
5095     // producing further diagnostics for redundant qualifiers after this.
5096     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5097                                ? diag::err_no_declarators
5098                                : diag::ext_no_declarators)
5099         << DS.getSourceRange();
5100     return TagD;
5101   }
5102 
5103   // C++ [dcl.stc]p1:
5104   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5105   //   init-declarator-list of the declaration shall not be empty.
5106   // C++ [dcl.fct.spec]p1:
5107   //   If a cv-qualifier appears in a decl-specifier-seq, the
5108   //   init-declarator-list of the declaration shall not be empty.
5109   //
5110   // Spurious qualifiers here appear to be valid in C.
5111   unsigned DiagID = diag::warn_standalone_specifier;
5112   if (getLangOpts().CPlusPlus)
5113     DiagID = diag::ext_standalone_specifier;
5114 
5115   // Note that a linkage-specification sets a storage class, but
5116   // 'extern "C" struct foo;' is actually valid and not theoretically
5117   // useless.
5118   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5119     if (SCS == DeclSpec::SCS_mutable)
5120       // Since mutable is not a viable storage class specifier in C, there is
5121       // no reason to treat it as an extension. Instead, diagnose as an error.
5122       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5123     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5124       Diag(DS.getStorageClassSpecLoc(), DiagID)
5125         << DeclSpec::getSpecifierName(SCS);
5126   }
5127 
5128   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5129     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5130       << DeclSpec::getSpecifierName(TSCS);
5131   if (DS.getTypeQualifiers()) {
5132     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5133       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5134     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5135       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5136     // Restrict is covered above.
5137     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5138       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5139     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5140       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5141   }
5142 
5143   // Warn about ignored type attributes, for example:
5144   // __attribute__((aligned)) struct A;
5145   // Attributes should be placed after tag to apply to type declaration.
5146   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5147     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5148     if (TypeSpecType == DeclSpec::TST_class ||
5149         TypeSpecType == DeclSpec::TST_struct ||
5150         TypeSpecType == DeclSpec::TST_interface ||
5151         TypeSpecType == DeclSpec::TST_union ||
5152         TypeSpecType == DeclSpec::TST_enum) {
5153       for (const ParsedAttr &AL : DS.getAttributes())
5154         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5155             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5156       for (const ParsedAttr &AL : DeclAttrs)
5157         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5158             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5159     }
5160   }
5161 
5162   return TagD;
5163 }
5164 
5165 /// We are trying to inject an anonymous member into the given scope;
5166 /// check if there's an existing declaration that can't be overloaded.
5167 ///
5168 /// \return true if this is a forbidden redeclaration
5169 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5170                                          Scope *S,
5171                                          DeclContext *Owner,
5172                                          DeclarationName Name,
5173                                          SourceLocation NameLoc,
5174                                          bool IsUnion) {
5175   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5176                  Sema::ForVisibleRedeclaration);
5177   if (!SemaRef.LookupName(R, S)) return false;
5178 
5179   // Pick a representative declaration.
5180   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5181   assert(PrevDecl && "Expected a non-null Decl");
5182 
5183   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5184     return false;
5185 
5186   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5187     << IsUnion << Name;
5188   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5189 
5190   return true;
5191 }
5192 
5193 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5194 /// anonymous struct or union AnonRecord into the owning context Owner
5195 /// and scope S. This routine will be invoked just after we realize
5196 /// that an unnamed union or struct is actually an anonymous union or
5197 /// struct, e.g.,
5198 ///
5199 /// @code
5200 /// union {
5201 ///   int i;
5202 ///   float f;
5203 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5204 ///    // f into the surrounding scope.x
5205 /// @endcode
5206 ///
5207 /// This routine is recursive, injecting the names of nested anonymous
5208 /// structs/unions into the owning context and scope as well.
5209 static bool
5210 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5211                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5212                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5213   bool Invalid = false;
5214 
5215   // Look every FieldDecl and IndirectFieldDecl with a name.
5216   for (auto *D : AnonRecord->decls()) {
5217     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5218         cast<NamedDecl>(D)->getDeclName()) {
5219       ValueDecl *VD = cast<ValueDecl>(D);
5220       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5221                                        VD->getLocation(),
5222                                        AnonRecord->isUnion())) {
5223         // C++ [class.union]p2:
5224         //   The names of the members of an anonymous union shall be
5225         //   distinct from the names of any other entity in the
5226         //   scope in which the anonymous union is declared.
5227         Invalid = true;
5228       } else {
5229         // C++ [class.union]p2:
5230         //   For the purpose of name lookup, after the anonymous union
5231         //   definition, the members of the anonymous union are
5232         //   considered to have been defined in the scope in which the
5233         //   anonymous union is declared.
5234         unsigned OldChainingSize = Chaining.size();
5235         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5236           Chaining.append(IF->chain_begin(), IF->chain_end());
5237         else
5238           Chaining.push_back(VD);
5239 
5240         assert(Chaining.size() >= 2);
5241         NamedDecl **NamedChain =
5242           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5243         for (unsigned i = 0; i < Chaining.size(); i++)
5244           NamedChain[i] = Chaining[i];
5245 
5246         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5247             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5248             VD->getType(), {NamedChain, Chaining.size()});
5249 
5250         for (const auto *Attr : VD->attrs())
5251           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5252 
5253         IndirectField->setAccess(AS);
5254         IndirectField->setImplicit();
5255         SemaRef.PushOnScopeChains(IndirectField, S);
5256 
5257         // That includes picking up the appropriate access specifier.
5258         if (AS != AS_none) IndirectField->setAccess(AS);
5259 
5260         Chaining.resize(OldChainingSize);
5261       }
5262     }
5263   }
5264 
5265   return Invalid;
5266 }
5267 
5268 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5269 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5270 /// illegal input values are mapped to SC_None.
5271 static StorageClass
5272 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5273   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5274   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5275          "Parser allowed 'typedef' as storage class VarDecl.");
5276   switch (StorageClassSpec) {
5277   case DeclSpec::SCS_unspecified:    return SC_None;
5278   case DeclSpec::SCS_extern:
5279     if (DS.isExternInLinkageSpec())
5280       return SC_None;
5281     return SC_Extern;
5282   case DeclSpec::SCS_static:         return SC_Static;
5283   case DeclSpec::SCS_auto:           return SC_Auto;
5284   case DeclSpec::SCS_register:       return SC_Register;
5285   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5286     // Illegal SCSs map to None: error reporting is up to the caller.
5287   case DeclSpec::SCS_mutable:        // Fall through.
5288   case DeclSpec::SCS_typedef:        return SC_None;
5289   }
5290   llvm_unreachable("unknown storage class specifier");
5291 }
5292 
5293 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5294   assert(Record->hasInClassInitializer());
5295 
5296   for (const auto *I : Record->decls()) {
5297     const auto *FD = dyn_cast<FieldDecl>(I);
5298     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5299       FD = IFD->getAnonField();
5300     if (FD && FD->hasInClassInitializer())
5301       return FD->getLocation();
5302   }
5303 
5304   llvm_unreachable("couldn't find in-class initializer");
5305 }
5306 
5307 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5308                                       SourceLocation DefaultInitLoc) {
5309   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5310     return;
5311 
5312   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5313   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5314 }
5315 
5316 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5317                                       CXXRecordDecl *AnonUnion) {
5318   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5319     return;
5320 
5321   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5322 }
5323 
5324 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5325 /// anonymous structure or union. Anonymous unions are a C++ feature
5326 /// (C++ [class.union]) and a C11 feature; anonymous structures
5327 /// are a C11 feature and GNU C++ extension.
5328 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5329                                         AccessSpecifier AS,
5330                                         RecordDecl *Record,
5331                                         const PrintingPolicy &Policy) {
5332   DeclContext *Owner = Record->getDeclContext();
5333 
5334   // Diagnose whether this anonymous struct/union is an extension.
5335   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5336     Diag(Record->getLocation(), diag::ext_anonymous_union);
5337   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5338     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5339   else if (!Record->isUnion() && !getLangOpts().C11)
5340     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5341 
5342   // C and C++ require different kinds of checks for anonymous
5343   // structs/unions.
5344   bool Invalid = false;
5345   if (getLangOpts().CPlusPlus) {
5346     const char *PrevSpec = nullptr;
5347     if (Record->isUnion()) {
5348       // C++ [class.union]p6:
5349       // C++17 [class.union.anon]p2:
5350       //   Anonymous unions declared in a named namespace or in the
5351       //   global namespace shall be declared static.
5352       unsigned DiagID;
5353       DeclContext *OwnerScope = Owner->getRedeclContext();
5354       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5355           (OwnerScope->isTranslationUnit() ||
5356            (OwnerScope->isNamespace() &&
5357             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5358         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5359           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5360 
5361         // Recover by adding 'static'.
5362         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5363                                PrevSpec, DiagID, Policy);
5364       }
5365       // C++ [class.union]p6:
5366       //   A storage class is not allowed in a declaration of an
5367       //   anonymous union in a class scope.
5368       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5369                isa<RecordDecl>(Owner)) {
5370         Diag(DS.getStorageClassSpecLoc(),
5371              diag::err_anonymous_union_with_storage_spec)
5372           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5373 
5374         // Recover by removing the storage specifier.
5375         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5376                                SourceLocation(),
5377                                PrevSpec, DiagID, Context.getPrintingPolicy());
5378       }
5379     }
5380 
5381     // Ignore const/volatile/restrict qualifiers.
5382     if (DS.getTypeQualifiers()) {
5383       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5384         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5385           << Record->isUnion() << "const"
5386           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5387       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5388         Diag(DS.getVolatileSpecLoc(),
5389              diag::ext_anonymous_struct_union_qualified)
5390           << Record->isUnion() << "volatile"
5391           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5392       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5393         Diag(DS.getRestrictSpecLoc(),
5394              diag::ext_anonymous_struct_union_qualified)
5395           << Record->isUnion() << "restrict"
5396           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5397       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5398         Diag(DS.getAtomicSpecLoc(),
5399              diag::ext_anonymous_struct_union_qualified)
5400           << Record->isUnion() << "_Atomic"
5401           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5402       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5403         Diag(DS.getUnalignedSpecLoc(),
5404              diag::ext_anonymous_struct_union_qualified)
5405           << Record->isUnion() << "__unaligned"
5406           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5407 
5408       DS.ClearTypeQualifiers();
5409     }
5410 
5411     // C++ [class.union]p2:
5412     //   The member-specification of an anonymous union shall only
5413     //   define non-static data members. [Note: nested types and
5414     //   functions cannot be declared within an anonymous union. ]
5415     for (auto *Mem : Record->decls()) {
5416       // Ignore invalid declarations; we already diagnosed them.
5417       if (Mem->isInvalidDecl())
5418         continue;
5419 
5420       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5421         // C++ [class.union]p3:
5422         //   An anonymous union shall not have private or protected
5423         //   members (clause 11).
5424         assert(FD->getAccess() != AS_none);
5425         if (FD->getAccess() != AS_public) {
5426           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5427             << Record->isUnion() << (FD->getAccess() == AS_protected);
5428           Invalid = true;
5429         }
5430 
5431         // C++ [class.union]p1
5432         //   An object of a class with a non-trivial constructor, a non-trivial
5433         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5434         //   assignment operator cannot be a member of a union, nor can an
5435         //   array of such objects.
5436         if (CheckNontrivialField(FD))
5437           Invalid = true;
5438       } else if (Mem->isImplicit()) {
5439         // Any implicit members are fine.
5440       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5441         // This is a type that showed up in an
5442         // elaborated-type-specifier inside the anonymous struct or
5443         // union, but which actually declares a type outside of the
5444         // anonymous struct or union. It's okay.
5445       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5446         if (!MemRecord->isAnonymousStructOrUnion() &&
5447             MemRecord->getDeclName()) {
5448           // Visual C++ allows type definition in anonymous struct or union.
5449           if (getLangOpts().MicrosoftExt)
5450             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5451               << Record->isUnion();
5452           else {
5453             // This is a nested type declaration.
5454             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5455               << Record->isUnion();
5456             Invalid = true;
5457           }
5458         } else {
5459           // This is an anonymous type definition within another anonymous type.
5460           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5461           // not part of standard C++.
5462           Diag(MemRecord->getLocation(),
5463                diag::ext_anonymous_record_with_anonymous_type)
5464             << Record->isUnion();
5465         }
5466       } else if (isa<AccessSpecDecl>(Mem)) {
5467         // Any access specifier is fine.
5468       } else if (isa<StaticAssertDecl>(Mem)) {
5469         // In C++1z, static_assert declarations are also fine.
5470       } else {
5471         // We have something that isn't a non-static data
5472         // member. Complain about it.
5473         unsigned DK = diag::err_anonymous_record_bad_member;
5474         if (isa<TypeDecl>(Mem))
5475           DK = diag::err_anonymous_record_with_type;
5476         else if (isa<FunctionDecl>(Mem))
5477           DK = diag::err_anonymous_record_with_function;
5478         else if (isa<VarDecl>(Mem))
5479           DK = diag::err_anonymous_record_with_static;
5480 
5481         // Visual C++ allows type definition in anonymous struct or union.
5482         if (getLangOpts().MicrosoftExt &&
5483             DK == diag::err_anonymous_record_with_type)
5484           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5485             << Record->isUnion();
5486         else {
5487           Diag(Mem->getLocation(), DK) << Record->isUnion();
5488           Invalid = true;
5489         }
5490       }
5491     }
5492 
5493     // C++11 [class.union]p8 (DR1460):
5494     //   At most one variant member of a union may have a
5495     //   brace-or-equal-initializer.
5496     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5497         Owner->isRecord())
5498       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5499                                 cast<CXXRecordDecl>(Record));
5500   }
5501 
5502   if (!Record->isUnion() && !Owner->isRecord()) {
5503     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5504       << getLangOpts().CPlusPlus;
5505     Invalid = true;
5506   }
5507 
5508   // C++ [dcl.dcl]p3:
5509   //   [If there are no declarators], and except for the declaration of an
5510   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5511   //   names into the program
5512   // C++ [class.mem]p2:
5513   //   each such member-declaration shall either declare at least one member
5514   //   name of the class or declare at least one unnamed bit-field
5515   //
5516   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5517   if (getLangOpts().CPlusPlus && Record->field_empty())
5518     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5519 
5520   // Mock up a declarator.
5521   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5522   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5523   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5524 
5525   // Create a declaration for this anonymous struct/union.
5526   NamedDecl *Anon = nullptr;
5527   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5528     Anon = FieldDecl::Create(
5529         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5530         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5531         /*BitWidth=*/nullptr, /*Mutable=*/false,
5532         /*InitStyle=*/ICIS_NoInit);
5533     Anon->setAccess(AS);
5534     ProcessDeclAttributes(S, Anon, Dc);
5535 
5536     if (getLangOpts().CPlusPlus)
5537       FieldCollector->Add(cast<FieldDecl>(Anon));
5538   } else {
5539     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5540     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5541     if (SCSpec == DeclSpec::SCS_mutable) {
5542       // mutable can only appear on non-static class members, so it's always
5543       // an error here
5544       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5545       Invalid = true;
5546       SC = SC_None;
5547     }
5548 
5549     assert(DS.getAttributes().empty() && "No attribute expected");
5550     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5551                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5552                            Context.getTypeDeclType(Record), TInfo, SC);
5553 
5554     // Default-initialize the implicit variable. This initialization will be
5555     // trivial in almost all cases, except if a union member has an in-class
5556     // initializer:
5557     //   union { int n = 0; };
5558     ActOnUninitializedDecl(Anon);
5559   }
5560   Anon->setImplicit();
5561 
5562   // Mark this as an anonymous struct/union type.
5563   Record->setAnonymousStructOrUnion(true);
5564 
5565   // Add the anonymous struct/union object to the current
5566   // context. We'll be referencing this object when we refer to one of
5567   // its members.
5568   Owner->addDecl(Anon);
5569 
5570   // Inject the members of the anonymous struct/union into the owning
5571   // context and into the identifier resolver chain for name lookup
5572   // purposes.
5573   SmallVector<NamedDecl*, 2> Chain;
5574   Chain.push_back(Anon);
5575 
5576   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5577     Invalid = true;
5578 
5579   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5580     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5581       MangleNumberingContext *MCtx;
5582       Decl *ManglingContextDecl;
5583       std::tie(MCtx, ManglingContextDecl) =
5584           getCurrentMangleNumberContext(NewVD->getDeclContext());
5585       if (MCtx) {
5586         Context.setManglingNumber(
5587             NewVD, MCtx->getManglingNumber(
5588                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5589         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5590       }
5591     }
5592   }
5593 
5594   if (Invalid)
5595     Anon->setInvalidDecl();
5596 
5597   return Anon;
5598 }
5599 
5600 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5601 /// Microsoft C anonymous structure.
5602 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5603 /// Example:
5604 ///
5605 /// struct A { int a; };
5606 /// struct B { struct A; int b; };
5607 ///
5608 /// void foo() {
5609 ///   B var;
5610 ///   var.a = 3;
5611 /// }
5612 ///
5613 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5614                                            RecordDecl *Record) {
5615   assert(Record && "expected a record!");
5616 
5617   // Mock up a declarator.
5618   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5619   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5620   assert(TInfo && "couldn't build declarator info for anonymous struct");
5621 
5622   auto *ParentDecl = cast<RecordDecl>(CurContext);
5623   QualType RecTy = Context.getTypeDeclType(Record);
5624 
5625   // Create a declaration for this anonymous struct.
5626   NamedDecl *Anon =
5627       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5628                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5629                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5630                         /*InitStyle=*/ICIS_NoInit);
5631   Anon->setImplicit();
5632 
5633   // Add the anonymous struct object to the current context.
5634   CurContext->addDecl(Anon);
5635 
5636   // Inject the members of the anonymous struct into the current
5637   // context and into the identifier resolver chain for name lookup
5638   // purposes.
5639   SmallVector<NamedDecl*, 2> Chain;
5640   Chain.push_back(Anon);
5641 
5642   RecordDecl *RecordDef = Record->getDefinition();
5643   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5644                                diag::err_field_incomplete_or_sizeless) ||
5645       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5646                                           AS_none, Chain)) {
5647     Anon->setInvalidDecl();
5648     ParentDecl->setInvalidDecl();
5649   }
5650 
5651   return Anon;
5652 }
5653 
5654 /// GetNameForDeclarator - Determine the full declaration name for the
5655 /// given Declarator.
5656 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5657   return GetNameFromUnqualifiedId(D.getName());
5658 }
5659 
5660 /// Retrieves the declaration name from a parsed unqualified-id.
5661 DeclarationNameInfo
5662 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5663   DeclarationNameInfo NameInfo;
5664   NameInfo.setLoc(Name.StartLocation);
5665 
5666   switch (Name.getKind()) {
5667 
5668   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5669   case UnqualifiedIdKind::IK_Identifier:
5670     NameInfo.setName(Name.Identifier);
5671     return NameInfo;
5672 
5673   case UnqualifiedIdKind::IK_DeductionGuideName: {
5674     // C++ [temp.deduct.guide]p3:
5675     //   The simple-template-id shall name a class template specialization.
5676     //   The template-name shall be the same identifier as the template-name
5677     //   of the simple-template-id.
5678     // These together intend to imply that the template-name shall name a
5679     // class template.
5680     // FIXME: template<typename T> struct X {};
5681     //        template<typename T> using Y = X<T>;
5682     //        Y(int) -> Y<int>;
5683     //   satisfies these rules but does not name a class template.
5684     TemplateName TN = Name.TemplateName.get().get();
5685     auto *Template = TN.getAsTemplateDecl();
5686     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5687       Diag(Name.StartLocation,
5688            diag::err_deduction_guide_name_not_class_template)
5689         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5690       if (Template)
5691         Diag(Template->getLocation(), diag::note_template_decl_here);
5692       return DeclarationNameInfo();
5693     }
5694 
5695     NameInfo.setName(
5696         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5697     return NameInfo;
5698   }
5699 
5700   case UnqualifiedIdKind::IK_OperatorFunctionId:
5701     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5702                                            Name.OperatorFunctionId.Operator));
5703     NameInfo.setCXXOperatorNameRange(SourceRange(
5704         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5705     return NameInfo;
5706 
5707   case UnqualifiedIdKind::IK_LiteralOperatorId:
5708     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5709                                                            Name.Identifier));
5710     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5711     return NameInfo;
5712 
5713   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5714     TypeSourceInfo *TInfo;
5715     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5716     if (Ty.isNull())
5717       return DeclarationNameInfo();
5718     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5719                                                Context.getCanonicalType(Ty)));
5720     NameInfo.setNamedTypeInfo(TInfo);
5721     return NameInfo;
5722   }
5723 
5724   case UnqualifiedIdKind::IK_ConstructorName: {
5725     TypeSourceInfo *TInfo;
5726     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5727     if (Ty.isNull())
5728       return DeclarationNameInfo();
5729     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5730                                               Context.getCanonicalType(Ty)));
5731     NameInfo.setNamedTypeInfo(TInfo);
5732     return NameInfo;
5733   }
5734 
5735   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5736     // In well-formed code, we can only have a constructor
5737     // template-id that refers to the current context, so go there
5738     // to find the actual type being constructed.
5739     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5740     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5741       return DeclarationNameInfo();
5742 
5743     // Determine the type of the class being constructed.
5744     QualType CurClassType = Context.getTypeDeclType(CurClass);
5745 
5746     // FIXME: Check two things: that the template-id names the same type as
5747     // CurClassType, and that the template-id does not occur when the name
5748     // was qualified.
5749 
5750     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5751                                     Context.getCanonicalType(CurClassType)));
5752     // FIXME: should we retrieve TypeSourceInfo?
5753     NameInfo.setNamedTypeInfo(nullptr);
5754     return NameInfo;
5755   }
5756 
5757   case UnqualifiedIdKind::IK_DestructorName: {
5758     TypeSourceInfo *TInfo;
5759     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5760     if (Ty.isNull())
5761       return DeclarationNameInfo();
5762     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5763                                               Context.getCanonicalType(Ty)));
5764     NameInfo.setNamedTypeInfo(TInfo);
5765     return NameInfo;
5766   }
5767 
5768   case UnqualifiedIdKind::IK_TemplateId: {
5769     TemplateName TName = Name.TemplateId->Template.get();
5770     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5771     return Context.getNameForTemplate(TName, TNameLoc);
5772   }
5773 
5774   } // switch (Name.getKind())
5775 
5776   llvm_unreachable("Unknown name kind");
5777 }
5778 
5779 static QualType getCoreType(QualType Ty) {
5780   do {
5781     if (Ty->isPointerType() || Ty->isReferenceType())
5782       Ty = Ty->getPointeeType();
5783     else if (Ty->isArrayType())
5784       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5785     else
5786       return Ty.withoutLocalFastQualifiers();
5787   } while (true);
5788 }
5789 
5790 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5791 /// and Definition have "nearly" matching parameters. This heuristic is
5792 /// used to improve diagnostics in the case where an out-of-line function
5793 /// definition doesn't match any declaration within the class or namespace.
5794 /// Also sets Params to the list of indices to the parameters that differ
5795 /// between the declaration and the definition. If hasSimilarParameters
5796 /// returns true and Params is empty, then all of the parameters match.
5797 static bool hasSimilarParameters(ASTContext &Context,
5798                                      FunctionDecl *Declaration,
5799                                      FunctionDecl *Definition,
5800                                      SmallVectorImpl<unsigned> &Params) {
5801   Params.clear();
5802   if (Declaration->param_size() != Definition->param_size())
5803     return false;
5804   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5805     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5806     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5807 
5808     // The parameter types are identical
5809     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5810       continue;
5811 
5812     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5813     QualType DefParamBaseTy = getCoreType(DefParamTy);
5814     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5815     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5816 
5817     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5818         (DeclTyName && DeclTyName == DefTyName))
5819       Params.push_back(Idx);
5820     else  // The two parameters aren't even close
5821       return false;
5822   }
5823 
5824   return true;
5825 }
5826 
5827 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5828 /// declarator needs to be rebuilt in the current instantiation.
5829 /// Any bits of declarator which appear before the name are valid for
5830 /// consideration here.  That's specifically the type in the decl spec
5831 /// and the base type in any member-pointer chunks.
5832 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5833                                                     DeclarationName Name) {
5834   // The types we specifically need to rebuild are:
5835   //   - typenames, typeofs, and decltypes
5836   //   - types which will become injected class names
5837   // Of course, we also need to rebuild any type referencing such a
5838   // type.  It's safest to just say "dependent", but we call out a
5839   // few cases here.
5840 
5841   DeclSpec &DS = D.getMutableDeclSpec();
5842   switch (DS.getTypeSpecType()) {
5843   case DeclSpec::TST_typename:
5844   case DeclSpec::TST_typeofType:
5845   case DeclSpec::TST_underlyingType:
5846   case DeclSpec::TST_atomic: {
5847     // Grab the type from the parser.
5848     TypeSourceInfo *TSI = nullptr;
5849     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5850     if (T.isNull() || !T->isInstantiationDependentType()) break;
5851 
5852     // Make sure there's a type source info.  This isn't really much
5853     // of a waste; most dependent types should have type source info
5854     // attached already.
5855     if (!TSI)
5856       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5857 
5858     // Rebuild the type in the current instantiation.
5859     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5860     if (!TSI) return true;
5861 
5862     // Store the new type back in the decl spec.
5863     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5864     DS.UpdateTypeRep(LocType);
5865     break;
5866   }
5867 
5868   case DeclSpec::TST_decltype:
5869   case DeclSpec::TST_typeofExpr: {
5870     Expr *E = DS.getRepAsExpr();
5871     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5872     if (Result.isInvalid()) return true;
5873     DS.UpdateExprRep(Result.get());
5874     break;
5875   }
5876 
5877   default:
5878     // Nothing to do for these decl specs.
5879     break;
5880   }
5881 
5882   // It doesn't matter what order we do this in.
5883   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5884     DeclaratorChunk &Chunk = D.getTypeObject(I);
5885 
5886     // The only type information in the declarator which can come
5887     // before the declaration name is the base type of a member
5888     // pointer.
5889     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5890       continue;
5891 
5892     // Rebuild the scope specifier in-place.
5893     CXXScopeSpec &SS = Chunk.Mem.Scope();
5894     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5895       return true;
5896   }
5897 
5898   return false;
5899 }
5900 
5901 /// Returns true if the declaration is declared in a system header or from a
5902 /// system macro.
5903 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5904   return SM.isInSystemHeader(D->getLocation()) ||
5905          SM.isInSystemMacro(D->getLocation());
5906 }
5907 
5908 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5909   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5910   // of system decl.
5911   if (D->getPreviousDecl() || D->isImplicit())
5912     return;
5913   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5914   if (Status != ReservedIdentifierStatus::NotReserved &&
5915       !isFromSystemHeader(Context.getSourceManager(), D)) {
5916     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5917         << D << static_cast<int>(Status);
5918   }
5919 }
5920 
5921 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5922   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5923 
5924   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5925   // declaration only if the `bind_to_declaration` extension is set.
5926   SmallVector<FunctionDecl *, 4> Bases;
5927   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
5928     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
5929               implementation_extension_bind_to_declaration))
5930     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
5931         S, D, MultiTemplateParamsArg(), Bases);
5932 
5933   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5934 
5935   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5936       Dcl && Dcl->getDeclContext()->isFileContext())
5937     Dcl->setTopLevelDeclInObjCContainer();
5938 
5939   if (!Bases.empty())
5940     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
5941 
5942   return Dcl;
5943 }
5944 
5945 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5946 ///   If T is the name of a class, then each of the following shall have a
5947 ///   name different from T:
5948 ///     - every static data member of class T;
5949 ///     - every member function of class T
5950 ///     - every member of class T that is itself a type;
5951 /// \returns true if the declaration name violates these rules.
5952 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5953                                    DeclarationNameInfo NameInfo) {
5954   DeclarationName Name = NameInfo.getName();
5955 
5956   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5957   while (Record && Record->isAnonymousStructOrUnion())
5958     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5959   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5960     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5961     return true;
5962   }
5963 
5964   return false;
5965 }
5966 
5967 /// Diagnose a declaration whose declarator-id has the given
5968 /// nested-name-specifier.
5969 ///
5970 /// \param SS The nested-name-specifier of the declarator-id.
5971 ///
5972 /// \param DC The declaration context to which the nested-name-specifier
5973 /// resolves.
5974 ///
5975 /// \param Name The name of the entity being declared.
5976 ///
5977 /// \param Loc The location of the name of the entity being declared.
5978 ///
5979 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5980 /// we're declaring an explicit / partial specialization / instantiation.
5981 ///
5982 /// \returns true if we cannot safely recover from this error, false otherwise.
5983 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5984                                         DeclarationName Name,
5985                                         SourceLocation Loc, bool IsTemplateId) {
5986   DeclContext *Cur = CurContext;
5987   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5988     Cur = Cur->getParent();
5989 
5990   // If the user provided a superfluous scope specifier that refers back to the
5991   // class in which the entity is already declared, diagnose and ignore it.
5992   //
5993   // class X {
5994   //   void X::f();
5995   // };
5996   //
5997   // Note, it was once ill-formed to give redundant qualification in all
5998   // contexts, but that rule was removed by DR482.
5999   if (Cur->Equals(DC)) {
6000     if (Cur->isRecord()) {
6001       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6002                                       : diag::err_member_extra_qualification)
6003         << Name << FixItHint::CreateRemoval(SS.getRange());
6004       SS.clear();
6005     } else {
6006       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6007     }
6008     return false;
6009   }
6010 
6011   // Check whether the qualifying scope encloses the scope of the original
6012   // declaration. For a template-id, we perform the checks in
6013   // CheckTemplateSpecializationScope.
6014   if (!Cur->Encloses(DC) && !IsTemplateId) {
6015     if (Cur->isRecord())
6016       Diag(Loc, diag::err_member_qualification)
6017         << Name << SS.getRange();
6018     else if (isa<TranslationUnitDecl>(DC))
6019       Diag(Loc, diag::err_invalid_declarator_global_scope)
6020         << Name << SS.getRange();
6021     else if (isa<FunctionDecl>(Cur))
6022       Diag(Loc, diag::err_invalid_declarator_in_function)
6023         << Name << SS.getRange();
6024     else if (isa<BlockDecl>(Cur))
6025       Diag(Loc, diag::err_invalid_declarator_in_block)
6026         << Name << SS.getRange();
6027     else if (isa<ExportDecl>(Cur)) {
6028       if (!isa<NamespaceDecl>(DC))
6029         Diag(Loc, diag::err_export_non_namespace_scope_name)
6030             << Name << SS.getRange();
6031       else
6032         // The cases that DC is not NamespaceDecl should be handled in
6033         // CheckRedeclarationExported.
6034         return false;
6035     } else
6036       Diag(Loc, diag::err_invalid_declarator_scope)
6037       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6038 
6039     return true;
6040   }
6041 
6042   if (Cur->isRecord()) {
6043     // Cannot qualify members within a class.
6044     Diag(Loc, diag::err_member_qualification)
6045       << Name << SS.getRange();
6046     SS.clear();
6047 
6048     // C++ constructors and destructors with incorrect scopes can break
6049     // our AST invariants by having the wrong underlying types. If
6050     // that's the case, then drop this declaration entirely.
6051     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6052          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6053         !Context.hasSameType(Name.getCXXNameType(),
6054                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6055       return true;
6056 
6057     return false;
6058   }
6059 
6060   // C++11 [dcl.meaning]p1:
6061   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6062   //   not begin with a decltype-specifer"
6063   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6064   while (SpecLoc.getPrefix())
6065     SpecLoc = SpecLoc.getPrefix();
6066   if (isa_and_nonnull<DecltypeType>(
6067           SpecLoc.getNestedNameSpecifier()->getAsType()))
6068     Diag(Loc, diag::err_decltype_in_declarator)
6069       << SpecLoc.getTypeLoc().getSourceRange();
6070 
6071   return false;
6072 }
6073 
6074 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6075                                   MultiTemplateParamsArg TemplateParamLists) {
6076   // TODO: consider using NameInfo for diagnostic.
6077   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6078   DeclarationName Name = NameInfo.getName();
6079 
6080   // All of these full declarators require an identifier.  If it doesn't have
6081   // one, the ParsedFreeStandingDeclSpec action should be used.
6082   if (D.isDecompositionDeclarator()) {
6083     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6084   } else if (!Name) {
6085     if (!D.isInvalidType())  // Reject this if we think it is valid.
6086       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6087           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6088     return nullptr;
6089   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6090     return nullptr;
6091 
6092   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6093   // we find one that is.
6094   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6095          (S->getFlags() & Scope::TemplateParamScope) != 0)
6096     S = S->getParent();
6097 
6098   DeclContext *DC = CurContext;
6099   if (D.getCXXScopeSpec().isInvalid())
6100     D.setInvalidType();
6101   else if (D.getCXXScopeSpec().isSet()) {
6102     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6103                                         UPPC_DeclarationQualifier))
6104       return nullptr;
6105 
6106     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6107     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6108     if (!DC || isa<EnumDecl>(DC)) {
6109       // If we could not compute the declaration context, it's because the
6110       // declaration context is dependent but does not refer to a class,
6111       // class template, or class template partial specialization. Complain
6112       // and return early, to avoid the coming semantic disaster.
6113       Diag(D.getIdentifierLoc(),
6114            diag::err_template_qualified_declarator_no_match)
6115         << D.getCXXScopeSpec().getScopeRep()
6116         << D.getCXXScopeSpec().getRange();
6117       return nullptr;
6118     }
6119     bool IsDependentContext = DC->isDependentContext();
6120 
6121     if (!IsDependentContext &&
6122         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6123       return nullptr;
6124 
6125     // If a class is incomplete, do not parse entities inside it.
6126     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6127       Diag(D.getIdentifierLoc(),
6128            diag::err_member_def_undefined_record)
6129         << Name << DC << D.getCXXScopeSpec().getRange();
6130       return nullptr;
6131     }
6132     if (!D.getDeclSpec().isFriendSpecified()) {
6133       if (diagnoseQualifiedDeclaration(
6134               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6135               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6136         if (DC->isRecord())
6137           return nullptr;
6138 
6139         D.setInvalidType();
6140       }
6141     }
6142 
6143     // Check whether we need to rebuild the type of the given
6144     // declaration in the current instantiation.
6145     if (EnteringContext && IsDependentContext &&
6146         TemplateParamLists.size() != 0) {
6147       ContextRAII SavedContext(*this, DC);
6148       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6149         D.setInvalidType();
6150     }
6151   }
6152 
6153   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6154   QualType R = TInfo->getType();
6155 
6156   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6157                                       UPPC_DeclarationType))
6158     D.setInvalidType();
6159 
6160   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6161                         forRedeclarationInCurContext());
6162 
6163   // See if this is a redefinition of a variable in the same scope.
6164   if (!D.getCXXScopeSpec().isSet()) {
6165     bool IsLinkageLookup = false;
6166     bool CreateBuiltins = false;
6167 
6168     // If the declaration we're planning to build will be a function
6169     // or object with linkage, then look for another declaration with
6170     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6171     //
6172     // If the declaration we're planning to build will be declared with
6173     // external linkage in the translation unit, create any builtin with
6174     // the same name.
6175     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6176       /* Do nothing*/;
6177     else if (CurContext->isFunctionOrMethod() &&
6178              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6179               R->isFunctionType())) {
6180       IsLinkageLookup = true;
6181       CreateBuiltins =
6182           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6183     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6184                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6185       CreateBuiltins = true;
6186 
6187     if (IsLinkageLookup) {
6188       Previous.clear(LookupRedeclarationWithLinkage);
6189       Previous.setRedeclarationKind(ForExternalRedeclaration);
6190     }
6191 
6192     LookupName(Previous, S, CreateBuiltins);
6193   } else { // Something like "int foo::x;"
6194     LookupQualifiedName(Previous, DC);
6195 
6196     // C++ [dcl.meaning]p1:
6197     //   When the declarator-id is qualified, the declaration shall refer to a
6198     //  previously declared member of the class or namespace to which the
6199     //  qualifier refers (or, in the case of a namespace, of an element of the
6200     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6201     //  thereof; [...]
6202     //
6203     // Note that we already checked the context above, and that we do not have
6204     // enough information to make sure that Previous contains the declaration
6205     // we want to match. For example, given:
6206     //
6207     //   class X {
6208     //     void f();
6209     //     void f(float);
6210     //   };
6211     //
6212     //   void X::f(int) { } // ill-formed
6213     //
6214     // In this case, Previous will point to the overload set
6215     // containing the two f's declared in X, but neither of them
6216     // matches.
6217 
6218     // C++ [dcl.meaning]p1:
6219     //   [...] the member shall not merely have been introduced by a
6220     //   using-declaration in the scope of the class or namespace nominated by
6221     //   the nested-name-specifier of the declarator-id.
6222     RemoveUsingDecls(Previous);
6223   }
6224 
6225   if (Previous.isSingleResult() &&
6226       Previous.getFoundDecl()->isTemplateParameter()) {
6227     // Maybe we will complain about the shadowed template parameter.
6228     if (!D.isInvalidType())
6229       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6230                                       Previous.getFoundDecl());
6231 
6232     // Just pretend that we didn't see the previous declaration.
6233     Previous.clear();
6234   }
6235 
6236   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6237     // Forget that the previous declaration is the injected-class-name.
6238     Previous.clear();
6239 
6240   // In C++, the previous declaration we find might be a tag type
6241   // (class or enum). In this case, the new declaration will hide the
6242   // tag type. Note that this applies to functions, function templates, and
6243   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6244   if (Previous.isSingleTagDecl() &&
6245       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6246       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6247     Previous.clear();
6248 
6249   // Check that there are no default arguments other than in the parameters
6250   // of a function declaration (C++ only).
6251   if (getLangOpts().CPlusPlus)
6252     CheckExtraCXXDefaultArguments(D);
6253 
6254   NamedDecl *New;
6255 
6256   bool AddToScope = true;
6257   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6258     if (TemplateParamLists.size()) {
6259       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6260       return nullptr;
6261     }
6262 
6263     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6264   } else if (R->isFunctionType()) {
6265     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6266                                   TemplateParamLists,
6267                                   AddToScope);
6268   } else {
6269     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6270                                   AddToScope);
6271   }
6272 
6273   if (!New)
6274     return nullptr;
6275 
6276   // If this has an identifier and is not a function template specialization,
6277   // add it to the scope stack.
6278   if (New->getDeclName() && AddToScope)
6279     PushOnScopeChains(New, S);
6280 
6281   if (isInOpenMPDeclareTargetContext())
6282     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6283 
6284   return New;
6285 }
6286 
6287 /// Helper method to turn variable array types into constant array
6288 /// types in certain situations which would otherwise be errors (for
6289 /// GCC compatibility).
6290 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6291                                                     ASTContext &Context,
6292                                                     bool &SizeIsNegative,
6293                                                     llvm::APSInt &Oversized) {
6294   // This method tries to turn a variable array into a constant
6295   // array even when the size isn't an ICE.  This is necessary
6296   // for compatibility with code that depends on gcc's buggy
6297   // constant expression folding, like struct {char x[(int)(char*)2];}
6298   SizeIsNegative = false;
6299   Oversized = 0;
6300 
6301   if (T->isDependentType())
6302     return QualType();
6303 
6304   QualifierCollector Qs;
6305   const Type *Ty = Qs.strip(T);
6306 
6307   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6308     QualType Pointee = PTy->getPointeeType();
6309     QualType FixedType =
6310         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6311                                             Oversized);
6312     if (FixedType.isNull()) return FixedType;
6313     FixedType = Context.getPointerType(FixedType);
6314     return Qs.apply(Context, FixedType);
6315   }
6316   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6317     QualType Inner = PTy->getInnerType();
6318     QualType FixedType =
6319         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6320                                             Oversized);
6321     if (FixedType.isNull()) return FixedType;
6322     FixedType = Context.getParenType(FixedType);
6323     return Qs.apply(Context, FixedType);
6324   }
6325 
6326   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6327   if (!VLATy)
6328     return QualType();
6329 
6330   QualType ElemTy = VLATy->getElementType();
6331   if (ElemTy->isVariablyModifiedType()) {
6332     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6333                                                  SizeIsNegative, Oversized);
6334     if (ElemTy.isNull())
6335       return QualType();
6336   }
6337 
6338   Expr::EvalResult Result;
6339   if (!VLATy->getSizeExpr() ||
6340       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6341     return QualType();
6342 
6343   llvm::APSInt Res = Result.Val.getInt();
6344 
6345   // Check whether the array size is negative.
6346   if (Res.isSigned() && Res.isNegative()) {
6347     SizeIsNegative = true;
6348     return QualType();
6349   }
6350 
6351   // Check whether the array is too large to be addressed.
6352   unsigned ActiveSizeBits =
6353       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6354        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6355           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6356           : Res.getActiveBits();
6357   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6358     Oversized = Res;
6359     return QualType();
6360   }
6361 
6362   QualType FoldedArrayType = Context.getConstantArrayType(
6363       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6364   return Qs.apply(Context, FoldedArrayType);
6365 }
6366 
6367 static void
6368 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6369   SrcTL = SrcTL.getUnqualifiedLoc();
6370   DstTL = DstTL.getUnqualifiedLoc();
6371   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6372     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6373     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6374                                       DstPTL.getPointeeLoc());
6375     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6376     return;
6377   }
6378   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6379     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6380     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6381                                       DstPTL.getInnerLoc());
6382     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6383     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6384     return;
6385   }
6386   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6387   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6388   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6389   TypeLoc DstElemTL = DstATL.getElementLoc();
6390   if (VariableArrayTypeLoc SrcElemATL =
6391           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6392     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6393     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6394   } else {
6395     DstElemTL.initializeFullCopy(SrcElemTL);
6396   }
6397   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6398   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6399   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6400 }
6401 
6402 /// Helper method to turn variable array types into constant array
6403 /// types in certain situations which would otherwise be errors (for
6404 /// GCC compatibility).
6405 static TypeSourceInfo*
6406 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6407                                               ASTContext &Context,
6408                                               bool &SizeIsNegative,
6409                                               llvm::APSInt &Oversized) {
6410   QualType FixedTy
6411     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6412                                           SizeIsNegative, Oversized);
6413   if (FixedTy.isNull())
6414     return nullptr;
6415   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6416   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6417                                     FixedTInfo->getTypeLoc());
6418   return FixedTInfo;
6419 }
6420 
6421 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6422 /// true if we were successful.
6423 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6424                                            QualType &T, SourceLocation Loc,
6425                                            unsigned FailedFoldDiagID) {
6426   bool SizeIsNegative;
6427   llvm::APSInt Oversized;
6428   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6429       TInfo, Context, SizeIsNegative, Oversized);
6430   if (FixedTInfo) {
6431     Diag(Loc, diag::ext_vla_folded_to_constant);
6432     TInfo = FixedTInfo;
6433     T = FixedTInfo->getType();
6434     return true;
6435   }
6436 
6437   if (SizeIsNegative)
6438     Diag(Loc, diag::err_typecheck_negative_array_size);
6439   else if (Oversized.getBoolValue())
6440     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6441   else if (FailedFoldDiagID)
6442     Diag(Loc, FailedFoldDiagID);
6443   return false;
6444 }
6445 
6446 /// Register the given locally-scoped extern "C" declaration so
6447 /// that it can be found later for redeclarations. We include any extern "C"
6448 /// declaration that is not visible in the translation unit here, not just
6449 /// function-scope declarations.
6450 void
6451 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6452   if (!getLangOpts().CPlusPlus &&
6453       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6454     // Don't need to track declarations in the TU in C.
6455     return;
6456 
6457   // Note that we have a locally-scoped external with this name.
6458   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6459 }
6460 
6461 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6462   // FIXME: We can have multiple results via __attribute__((overloadable)).
6463   auto Result = Context.getExternCContextDecl()->lookup(Name);
6464   return Result.empty() ? nullptr : *Result.begin();
6465 }
6466 
6467 /// Diagnose function specifiers on a declaration of an identifier that
6468 /// does not identify a function.
6469 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6470   // FIXME: We should probably indicate the identifier in question to avoid
6471   // confusion for constructs like "virtual int a(), b;"
6472   if (DS.isVirtualSpecified())
6473     Diag(DS.getVirtualSpecLoc(),
6474          diag::err_virtual_non_function);
6475 
6476   if (DS.hasExplicitSpecifier())
6477     Diag(DS.getExplicitSpecLoc(),
6478          diag::err_explicit_non_function);
6479 
6480   if (DS.isNoreturnSpecified())
6481     Diag(DS.getNoreturnSpecLoc(),
6482          diag::err_noreturn_non_function);
6483 }
6484 
6485 NamedDecl*
6486 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6487                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6488   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6489   if (D.getCXXScopeSpec().isSet()) {
6490     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6491       << D.getCXXScopeSpec().getRange();
6492     D.setInvalidType();
6493     // Pretend we didn't see the scope specifier.
6494     DC = CurContext;
6495     Previous.clear();
6496   }
6497 
6498   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6499 
6500   if (D.getDeclSpec().isInlineSpecified())
6501     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6502         << getLangOpts().CPlusPlus17;
6503   if (D.getDeclSpec().hasConstexprSpecifier())
6504     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6505         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6506 
6507   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6508     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6509       Diag(D.getName().StartLocation,
6510            diag::err_deduction_guide_invalid_specifier)
6511           << "typedef";
6512     else
6513       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6514           << D.getName().getSourceRange();
6515     return nullptr;
6516   }
6517 
6518   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6519   if (!NewTD) return nullptr;
6520 
6521   // Handle attributes prior to checking for duplicates in MergeVarDecl
6522   ProcessDeclAttributes(S, NewTD, D);
6523 
6524   CheckTypedefForVariablyModifiedType(S, NewTD);
6525 
6526   bool Redeclaration = D.isRedeclaration();
6527   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6528   D.setRedeclaration(Redeclaration);
6529   return ND;
6530 }
6531 
6532 void
6533 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6534   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6535   // then it shall have block scope.
6536   // Note that variably modified types must be fixed before merging the decl so
6537   // that redeclarations will match.
6538   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6539   QualType T = TInfo->getType();
6540   if (T->isVariablyModifiedType()) {
6541     setFunctionHasBranchProtectedScope();
6542 
6543     if (S->getFnParent() == nullptr) {
6544       bool SizeIsNegative;
6545       llvm::APSInt Oversized;
6546       TypeSourceInfo *FixedTInfo =
6547         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6548                                                       SizeIsNegative,
6549                                                       Oversized);
6550       if (FixedTInfo) {
6551         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6552         NewTD->setTypeSourceInfo(FixedTInfo);
6553       } else {
6554         if (SizeIsNegative)
6555           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6556         else if (T->isVariableArrayType())
6557           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6558         else if (Oversized.getBoolValue())
6559           Diag(NewTD->getLocation(), diag::err_array_too_large)
6560             << toString(Oversized, 10);
6561         else
6562           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6563         NewTD->setInvalidDecl();
6564       }
6565     }
6566   }
6567 }
6568 
6569 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6570 /// declares a typedef-name, either using the 'typedef' type specifier or via
6571 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6572 NamedDecl*
6573 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6574                            LookupResult &Previous, bool &Redeclaration) {
6575 
6576   // Find the shadowed declaration before filtering for scope.
6577   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6578 
6579   // Merge the decl with the existing one if appropriate. If the decl is
6580   // in an outer scope, it isn't the same thing.
6581   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6582                        /*AllowInlineNamespace*/false);
6583   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6584   if (!Previous.empty()) {
6585     Redeclaration = true;
6586     MergeTypedefNameDecl(S, NewTD, Previous);
6587   } else {
6588     inferGslPointerAttribute(NewTD);
6589   }
6590 
6591   if (ShadowedDecl && !Redeclaration)
6592     CheckShadow(NewTD, ShadowedDecl, Previous);
6593 
6594   // If this is the C FILE type, notify the AST context.
6595   if (IdentifierInfo *II = NewTD->getIdentifier())
6596     if (!NewTD->isInvalidDecl() &&
6597         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6598       if (II->isStr("FILE"))
6599         Context.setFILEDecl(NewTD);
6600       else if (II->isStr("jmp_buf"))
6601         Context.setjmp_bufDecl(NewTD);
6602       else if (II->isStr("sigjmp_buf"))
6603         Context.setsigjmp_bufDecl(NewTD);
6604       else if (II->isStr("ucontext_t"))
6605         Context.setucontext_tDecl(NewTD);
6606     }
6607 
6608   return NewTD;
6609 }
6610 
6611 /// Determines whether the given declaration is an out-of-scope
6612 /// previous declaration.
6613 ///
6614 /// This routine should be invoked when name lookup has found a
6615 /// previous declaration (PrevDecl) that is not in the scope where a
6616 /// new declaration by the same name is being introduced. If the new
6617 /// declaration occurs in a local scope, previous declarations with
6618 /// linkage may still be considered previous declarations (C99
6619 /// 6.2.2p4-5, C++ [basic.link]p6).
6620 ///
6621 /// \param PrevDecl the previous declaration found by name
6622 /// lookup
6623 ///
6624 /// \param DC the context in which the new declaration is being
6625 /// declared.
6626 ///
6627 /// \returns true if PrevDecl is an out-of-scope previous declaration
6628 /// for a new delcaration with the same name.
6629 static bool
6630 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6631                                 ASTContext &Context) {
6632   if (!PrevDecl)
6633     return false;
6634 
6635   if (!PrevDecl->hasLinkage())
6636     return false;
6637 
6638   if (Context.getLangOpts().CPlusPlus) {
6639     // C++ [basic.link]p6:
6640     //   If there is a visible declaration of an entity with linkage
6641     //   having the same name and type, ignoring entities declared
6642     //   outside the innermost enclosing namespace scope, the block
6643     //   scope declaration declares that same entity and receives the
6644     //   linkage of the previous declaration.
6645     DeclContext *OuterContext = DC->getRedeclContext();
6646     if (!OuterContext->isFunctionOrMethod())
6647       // This rule only applies to block-scope declarations.
6648       return false;
6649 
6650     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6651     if (PrevOuterContext->isRecord())
6652       // We found a member function: ignore it.
6653       return false;
6654 
6655     // Find the innermost enclosing namespace for the new and
6656     // previous declarations.
6657     OuterContext = OuterContext->getEnclosingNamespaceContext();
6658     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6659 
6660     // The previous declaration is in a different namespace, so it
6661     // isn't the same function.
6662     if (!OuterContext->Equals(PrevOuterContext))
6663       return false;
6664   }
6665 
6666   return true;
6667 }
6668 
6669 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6670   CXXScopeSpec &SS = D.getCXXScopeSpec();
6671   if (!SS.isSet()) return;
6672   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6673 }
6674 
6675 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6676   QualType type = decl->getType();
6677   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6678   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6679     // Various kinds of declaration aren't allowed to be __autoreleasing.
6680     unsigned kind = -1U;
6681     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6682       if (var->hasAttr<BlocksAttr>())
6683         kind = 0; // __block
6684       else if (!var->hasLocalStorage())
6685         kind = 1; // global
6686     } else if (isa<ObjCIvarDecl>(decl)) {
6687       kind = 3; // ivar
6688     } else if (isa<FieldDecl>(decl)) {
6689       kind = 2; // field
6690     }
6691 
6692     if (kind != -1U) {
6693       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6694         << kind;
6695     }
6696   } else if (lifetime == Qualifiers::OCL_None) {
6697     // Try to infer lifetime.
6698     if (!type->isObjCLifetimeType())
6699       return false;
6700 
6701     lifetime = type->getObjCARCImplicitLifetime();
6702     type = Context.getLifetimeQualifiedType(type, lifetime);
6703     decl->setType(type);
6704   }
6705 
6706   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6707     // Thread-local variables cannot have lifetime.
6708     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6709         var->getTLSKind()) {
6710       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6711         << var->getType();
6712       return true;
6713     }
6714   }
6715 
6716   return false;
6717 }
6718 
6719 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6720   if (Decl->getType().hasAddressSpace())
6721     return;
6722   if (Decl->getType()->isDependentType())
6723     return;
6724   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6725     QualType Type = Var->getType();
6726     if (Type->isSamplerT() || Type->isVoidType())
6727       return;
6728     LangAS ImplAS = LangAS::opencl_private;
6729     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6730     // __opencl_c_program_scope_global_variables feature, the address space
6731     // for a variable at program scope or a static or extern variable inside
6732     // a function are inferred to be __global.
6733     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6734         Var->hasGlobalStorage())
6735       ImplAS = LangAS::opencl_global;
6736     // If the original type from a decayed type is an array type and that array
6737     // type has no address space yet, deduce it now.
6738     if (auto DT = dyn_cast<DecayedType>(Type)) {
6739       auto OrigTy = DT->getOriginalType();
6740       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6741         // Add the address space to the original array type and then propagate
6742         // that to the element type through `getAsArrayType`.
6743         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6744         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6745         // Re-generate the decayed type.
6746         Type = Context.getDecayedType(OrigTy);
6747       }
6748     }
6749     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6750     // Apply any qualifiers (including address space) from the array type to
6751     // the element type. This implements C99 6.7.3p8: "If the specification of
6752     // an array type includes any type qualifiers, the element type is so
6753     // qualified, not the array type."
6754     if (Type->isArrayType())
6755       Type = QualType(Context.getAsArrayType(Type), 0);
6756     Decl->setType(Type);
6757   }
6758 }
6759 
6760 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6761   // Ensure that an auto decl is deduced otherwise the checks below might cache
6762   // the wrong linkage.
6763   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6764 
6765   // 'weak' only applies to declarations with external linkage.
6766   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6767     if (!ND.isExternallyVisible()) {
6768       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6769       ND.dropAttr<WeakAttr>();
6770     }
6771   }
6772   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6773     if (ND.isExternallyVisible()) {
6774       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6775       ND.dropAttr<WeakRefAttr>();
6776       ND.dropAttr<AliasAttr>();
6777     }
6778   }
6779 
6780   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6781     if (VD->hasInit()) {
6782       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6783         assert(VD->isThisDeclarationADefinition() &&
6784                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6785         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6786         VD->dropAttr<AliasAttr>();
6787       }
6788     }
6789   }
6790 
6791   // 'selectany' only applies to externally visible variable declarations.
6792   // It does not apply to functions.
6793   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6794     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6795       S.Diag(Attr->getLocation(),
6796              diag::err_attribute_selectany_non_extern_data);
6797       ND.dropAttr<SelectAnyAttr>();
6798     }
6799   }
6800 
6801   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6802     auto *VD = dyn_cast<VarDecl>(&ND);
6803     bool IsAnonymousNS = false;
6804     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6805     if (VD) {
6806       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6807       while (NS && !IsAnonymousNS) {
6808         IsAnonymousNS = NS->isAnonymousNamespace();
6809         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6810       }
6811     }
6812     // dll attributes require external linkage. Static locals may have external
6813     // linkage but still cannot be explicitly imported or exported.
6814     // In Microsoft mode, a variable defined in anonymous namespace must have
6815     // external linkage in order to be exported.
6816     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6817     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6818         (!AnonNSInMicrosoftMode &&
6819          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6820       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6821         << &ND << Attr;
6822       ND.setInvalidDecl();
6823     }
6824   }
6825 
6826   // Check the attributes on the function type, if any.
6827   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6828     // Don't declare this variable in the second operand of the for-statement;
6829     // GCC miscompiles that by ending its lifetime before evaluating the
6830     // third operand. See gcc.gnu.org/PR86769.
6831     AttributedTypeLoc ATL;
6832     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6833          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6834          TL = ATL.getModifiedLoc()) {
6835       // The [[lifetimebound]] attribute can be applied to the implicit object
6836       // parameter of a non-static member function (other than a ctor or dtor)
6837       // by applying it to the function type.
6838       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6839         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6840         if (!MD || MD->isStatic()) {
6841           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6842               << !MD << A->getRange();
6843         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6844           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6845               << isa<CXXDestructorDecl>(MD) << A->getRange();
6846         }
6847       }
6848     }
6849   }
6850 }
6851 
6852 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6853                                            NamedDecl *NewDecl,
6854                                            bool IsSpecialization,
6855                                            bool IsDefinition) {
6856   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6857     return;
6858 
6859   bool IsTemplate = false;
6860   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6861     OldDecl = OldTD->getTemplatedDecl();
6862     IsTemplate = true;
6863     if (!IsSpecialization)
6864       IsDefinition = false;
6865   }
6866   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6867     NewDecl = NewTD->getTemplatedDecl();
6868     IsTemplate = true;
6869   }
6870 
6871   if (!OldDecl || !NewDecl)
6872     return;
6873 
6874   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6875   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6876   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6877   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6878 
6879   // dllimport and dllexport are inheritable attributes so we have to exclude
6880   // inherited attribute instances.
6881   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6882                     (NewExportAttr && !NewExportAttr->isInherited());
6883 
6884   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6885   // the only exception being explicit specializations.
6886   // Implicitly generated declarations are also excluded for now because there
6887   // is no other way to switch these to use dllimport or dllexport.
6888   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6889 
6890   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6891     // Allow with a warning for free functions and global variables.
6892     bool JustWarn = false;
6893     if (!OldDecl->isCXXClassMember()) {
6894       auto *VD = dyn_cast<VarDecl>(OldDecl);
6895       if (VD && !VD->getDescribedVarTemplate())
6896         JustWarn = true;
6897       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6898       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6899         JustWarn = true;
6900     }
6901 
6902     // We cannot change a declaration that's been used because IR has already
6903     // been emitted. Dllimported functions will still work though (modulo
6904     // address equality) as they can use the thunk.
6905     if (OldDecl->isUsed())
6906       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6907         JustWarn = false;
6908 
6909     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6910                                : diag::err_attribute_dll_redeclaration;
6911     S.Diag(NewDecl->getLocation(), DiagID)
6912         << NewDecl
6913         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6914     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6915     if (!JustWarn) {
6916       NewDecl->setInvalidDecl();
6917       return;
6918     }
6919   }
6920 
6921   // A redeclaration is not allowed to drop a dllimport attribute, the only
6922   // exceptions being inline function definitions (except for function
6923   // templates), local extern declarations, qualified friend declarations or
6924   // special MSVC extension: in the last case, the declaration is treated as if
6925   // it were marked dllexport.
6926   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6927   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6928   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6929     // Ignore static data because out-of-line definitions are diagnosed
6930     // separately.
6931     IsStaticDataMember = VD->isStaticDataMember();
6932     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6933                    VarDecl::DeclarationOnly;
6934   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6935     IsInline = FD->isInlined();
6936     IsQualifiedFriend = FD->getQualifier() &&
6937                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6938   }
6939 
6940   if (OldImportAttr && !HasNewAttr &&
6941       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6942       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6943     if (IsMicrosoftABI && IsDefinition) {
6944       S.Diag(NewDecl->getLocation(),
6945              diag::warn_redeclaration_without_import_attribute)
6946           << NewDecl;
6947       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6948       NewDecl->dropAttr<DLLImportAttr>();
6949       NewDecl->addAttr(
6950           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6951     } else {
6952       S.Diag(NewDecl->getLocation(),
6953              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6954           << NewDecl << OldImportAttr;
6955       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6956       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6957       OldDecl->dropAttr<DLLImportAttr>();
6958       NewDecl->dropAttr<DLLImportAttr>();
6959     }
6960   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6961     // In MinGW, seeing a function declared inline drops the dllimport
6962     // attribute.
6963     OldDecl->dropAttr<DLLImportAttr>();
6964     NewDecl->dropAttr<DLLImportAttr>();
6965     S.Diag(NewDecl->getLocation(),
6966            diag::warn_dllimport_dropped_from_inline_function)
6967         << NewDecl << OldImportAttr;
6968   }
6969 
6970   // A specialization of a class template member function is processed here
6971   // since it's a redeclaration. If the parent class is dllexport, the
6972   // specialization inherits that attribute. This doesn't happen automatically
6973   // since the parent class isn't instantiated until later.
6974   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6975     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6976         !NewImportAttr && !NewExportAttr) {
6977       if (const DLLExportAttr *ParentExportAttr =
6978               MD->getParent()->getAttr<DLLExportAttr>()) {
6979         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6980         NewAttr->setInherited(true);
6981         NewDecl->addAttr(NewAttr);
6982       }
6983     }
6984   }
6985 }
6986 
6987 /// Given that we are within the definition of the given function,
6988 /// will that definition behave like C99's 'inline', where the
6989 /// definition is discarded except for optimization purposes?
6990 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6991   // Try to avoid calling GetGVALinkageForFunction.
6992 
6993   // All cases of this require the 'inline' keyword.
6994   if (!FD->isInlined()) return false;
6995 
6996   // This is only possible in C++ with the gnu_inline attribute.
6997   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6998     return false;
6999 
7000   // Okay, go ahead and call the relatively-more-expensive function.
7001   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7002 }
7003 
7004 /// Determine whether a variable is extern "C" prior to attaching
7005 /// an initializer. We can't just call isExternC() here, because that
7006 /// will also compute and cache whether the declaration is externally
7007 /// visible, which might change when we attach the initializer.
7008 ///
7009 /// This can only be used if the declaration is known to not be a
7010 /// redeclaration of an internal linkage declaration.
7011 ///
7012 /// For instance:
7013 ///
7014 ///   auto x = []{};
7015 ///
7016 /// Attaching the initializer here makes this declaration not externally
7017 /// visible, because its type has internal linkage.
7018 ///
7019 /// FIXME: This is a hack.
7020 template<typename T>
7021 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7022   if (S.getLangOpts().CPlusPlus) {
7023     // In C++, the overloadable attribute negates the effects of extern "C".
7024     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7025       return false;
7026 
7027     // So do CUDA's host/device attributes.
7028     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7029                                  D->template hasAttr<CUDAHostAttr>()))
7030       return false;
7031   }
7032   return D->isExternC();
7033 }
7034 
7035 static bool shouldConsiderLinkage(const VarDecl *VD) {
7036   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7037   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7038       isa<OMPDeclareMapperDecl>(DC))
7039     return VD->hasExternalStorage();
7040   if (DC->isFileContext())
7041     return true;
7042   if (DC->isRecord())
7043     return false;
7044   if (isa<RequiresExprBodyDecl>(DC))
7045     return false;
7046   llvm_unreachable("Unexpected context");
7047 }
7048 
7049 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7050   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7051   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7052       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7053     return true;
7054   if (DC->isRecord())
7055     return false;
7056   llvm_unreachable("Unexpected context");
7057 }
7058 
7059 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7060                           ParsedAttr::Kind Kind) {
7061   // Check decl attributes on the DeclSpec.
7062   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7063     return true;
7064 
7065   // Walk the declarator structure, checking decl attributes that were in a type
7066   // position to the decl itself.
7067   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7068     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7069       return true;
7070   }
7071 
7072   // Finally, check attributes on the decl itself.
7073   return PD.getAttributes().hasAttribute(Kind) ||
7074          PD.getDeclarationAttributes().hasAttribute(Kind);
7075 }
7076 
7077 /// Adjust the \c DeclContext for a function or variable that might be a
7078 /// function-local external declaration.
7079 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7080   if (!DC->isFunctionOrMethod())
7081     return false;
7082 
7083   // If this is a local extern function or variable declared within a function
7084   // template, don't add it into the enclosing namespace scope until it is
7085   // instantiated; it might have a dependent type right now.
7086   if (DC->isDependentContext())
7087     return true;
7088 
7089   // C++11 [basic.link]p7:
7090   //   When a block scope declaration of an entity with linkage is not found to
7091   //   refer to some other declaration, then that entity is a member of the
7092   //   innermost enclosing namespace.
7093   //
7094   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7095   // semantically-enclosing namespace, not a lexically-enclosing one.
7096   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7097     DC = DC->getParent();
7098   return true;
7099 }
7100 
7101 /// Returns true if given declaration has external C language linkage.
7102 static bool isDeclExternC(const Decl *D) {
7103   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7104     return FD->isExternC();
7105   if (const auto *VD = dyn_cast<VarDecl>(D))
7106     return VD->isExternC();
7107 
7108   llvm_unreachable("Unknown type of decl!");
7109 }
7110 
7111 /// Returns true if there hasn't been any invalid type diagnosed.
7112 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7113   DeclContext *DC = NewVD->getDeclContext();
7114   QualType R = NewVD->getType();
7115 
7116   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7117   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7118   // argument.
7119   if (R->isImageType() || R->isPipeType()) {
7120     Se.Diag(NewVD->getLocation(),
7121             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7122         << R;
7123     NewVD->setInvalidDecl();
7124     return false;
7125   }
7126 
7127   // OpenCL v1.2 s6.9.r:
7128   // The event type cannot be used to declare a program scope variable.
7129   // OpenCL v2.0 s6.9.q:
7130   // The clk_event_t and reserve_id_t types cannot be declared in program
7131   // scope.
7132   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7133     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7134       Se.Diag(NewVD->getLocation(),
7135               diag::err_invalid_type_for_program_scope_var)
7136           << R;
7137       NewVD->setInvalidDecl();
7138       return false;
7139     }
7140   }
7141 
7142   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7143   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7144                                                Se.getLangOpts())) {
7145     QualType NR = R.getCanonicalType();
7146     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7147            NR->isReferenceType()) {
7148       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7149           NR->isFunctionReferenceType()) {
7150         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7151             << NR->isReferenceType();
7152         NewVD->setInvalidDecl();
7153         return false;
7154       }
7155       NR = NR->getPointeeType();
7156     }
7157   }
7158 
7159   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7160                                                Se.getLangOpts())) {
7161     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7162     // half array type (unless the cl_khr_fp16 extension is enabled).
7163     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7164       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7165       NewVD->setInvalidDecl();
7166       return false;
7167     }
7168   }
7169 
7170   // OpenCL v1.2 s6.9.r:
7171   // The event type cannot be used with the __local, __constant and __global
7172   // address space qualifiers.
7173   if (R->isEventT()) {
7174     if (R.getAddressSpace() != LangAS::opencl_private) {
7175       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7176       NewVD->setInvalidDecl();
7177       return false;
7178     }
7179   }
7180 
7181   if (R->isSamplerT()) {
7182     // OpenCL v1.2 s6.9.b p4:
7183     // The sampler type cannot be used with the __local and __global address
7184     // space qualifiers.
7185     if (R.getAddressSpace() == LangAS::opencl_local ||
7186         R.getAddressSpace() == LangAS::opencl_global) {
7187       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7188       NewVD->setInvalidDecl();
7189     }
7190 
7191     // OpenCL v1.2 s6.12.14.1:
7192     // A global sampler must be declared with either the constant address
7193     // space qualifier or with the const qualifier.
7194     if (DC->isTranslationUnit() &&
7195         !(R.getAddressSpace() == LangAS::opencl_constant ||
7196           R.isConstQualified())) {
7197       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7198       NewVD->setInvalidDecl();
7199     }
7200     if (NewVD->isInvalidDecl())
7201       return false;
7202   }
7203 
7204   return true;
7205 }
7206 
7207 template <typename AttrTy>
7208 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7209   const TypedefNameDecl *TND = TT->getDecl();
7210   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7211     AttrTy *Clone = Attribute->clone(S.Context);
7212     Clone->setInherited(true);
7213     D->addAttr(Clone);
7214   }
7215 }
7216 
7217 NamedDecl *Sema::ActOnVariableDeclarator(
7218     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7219     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7220     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7221   QualType R = TInfo->getType();
7222   DeclarationName Name = GetNameForDeclarator(D).getName();
7223 
7224   IdentifierInfo *II = Name.getAsIdentifierInfo();
7225 
7226   if (D.isDecompositionDeclarator()) {
7227     // Take the name of the first declarator as our name for diagnostic
7228     // purposes.
7229     auto &Decomp = D.getDecompositionDeclarator();
7230     if (!Decomp.bindings().empty()) {
7231       II = Decomp.bindings()[0].Name;
7232       Name = II;
7233     }
7234   } else if (!II) {
7235     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7236     return nullptr;
7237   }
7238 
7239 
7240   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7241   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7242 
7243   // dllimport globals without explicit storage class are treated as extern. We
7244   // have to change the storage class this early to get the right DeclContext.
7245   if (SC == SC_None && !DC->isRecord() &&
7246       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7247       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7248     SC = SC_Extern;
7249 
7250   DeclContext *OriginalDC = DC;
7251   bool IsLocalExternDecl = SC == SC_Extern &&
7252                            adjustContextForLocalExternDecl(DC);
7253 
7254   if (SCSpec == DeclSpec::SCS_mutable) {
7255     // mutable can only appear on non-static class members, so it's always
7256     // an error here
7257     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7258     D.setInvalidType();
7259     SC = SC_None;
7260   }
7261 
7262   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7263       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7264                               D.getDeclSpec().getStorageClassSpecLoc())) {
7265     // In C++11, the 'register' storage class specifier is deprecated.
7266     // Suppress the warning in system macros, it's used in macros in some
7267     // popular C system headers, such as in glibc's htonl() macro.
7268     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7269          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7270                                    : diag::warn_deprecated_register)
7271       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7272   }
7273 
7274   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7275 
7276   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7277     // C99 6.9p2: The storage-class specifiers auto and register shall not
7278     // appear in the declaration specifiers in an external declaration.
7279     // Global Register+Asm is a GNU extension we support.
7280     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7281       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7282       D.setInvalidType();
7283     }
7284   }
7285 
7286   // If this variable has a VLA type and an initializer, try to
7287   // fold to a constant-sized type. This is otherwise invalid.
7288   if (D.hasInitializer() && R->isVariableArrayType())
7289     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7290                                     /*DiagID=*/0);
7291 
7292   bool IsMemberSpecialization = false;
7293   bool IsVariableTemplateSpecialization = false;
7294   bool IsPartialSpecialization = false;
7295   bool IsVariableTemplate = false;
7296   VarDecl *NewVD = nullptr;
7297   VarTemplateDecl *NewTemplate = nullptr;
7298   TemplateParameterList *TemplateParams = nullptr;
7299   if (!getLangOpts().CPlusPlus) {
7300     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7301                             II, R, TInfo, SC);
7302 
7303     if (R->getContainedDeducedType())
7304       ParsingInitForAutoVars.insert(NewVD);
7305 
7306     if (D.isInvalidType())
7307       NewVD->setInvalidDecl();
7308 
7309     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7310         NewVD->hasLocalStorage())
7311       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7312                             NTCUC_AutoVar, NTCUK_Destruct);
7313   } else {
7314     bool Invalid = false;
7315 
7316     if (DC->isRecord() && !CurContext->isRecord()) {
7317       // This is an out-of-line definition of a static data member.
7318       switch (SC) {
7319       case SC_None:
7320         break;
7321       case SC_Static:
7322         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7323              diag::err_static_out_of_line)
7324           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7325         break;
7326       case SC_Auto:
7327       case SC_Register:
7328       case SC_Extern:
7329         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7330         // to names of variables declared in a block or to function parameters.
7331         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7332         // of class members
7333 
7334         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7335              diag::err_storage_class_for_static_member)
7336           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7337         break;
7338       case SC_PrivateExtern:
7339         llvm_unreachable("C storage class in c++!");
7340       }
7341     }
7342 
7343     if (SC == SC_Static && CurContext->isRecord()) {
7344       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7345         // Walk up the enclosing DeclContexts to check for any that are
7346         // incompatible with static data members.
7347         const DeclContext *FunctionOrMethod = nullptr;
7348         const CXXRecordDecl *AnonStruct = nullptr;
7349         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7350           if (Ctxt->isFunctionOrMethod()) {
7351             FunctionOrMethod = Ctxt;
7352             break;
7353           }
7354           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7355           if (ParentDecl && !ParentDecl->getDeclName()) {
7356             AnonStruct = ParentDecl;
7357             break;
7358           }
7359         }
7360         if (FunctionOrMethod) {
7361           // C++ [class.static.data]p5: A local class shall not have static data
7362           // members.
7363           Diag(D.getIdentifierLoc(),
7364                diag::err_static_data_member_not_allowed_in_local_class)
7365             << Name << RD->getDeclName() << RD->getTagKind();
7366         } else if (AnonStruct) {
7367           // C++ [class.static.data]p4: Unnamed classes and classes contained
7368           // directly or indirectly within unnamed classes shall not contain
7369           // static data members.
7370           Diag(D.getIdentifierLoc(),
7371                diag::err_static_data_member_not_allowed_in_anon_struct)
7372             << Name << AnonStruct->getTagKind();
7373           Invalid = true;
7374         } else if (RD->isUnion()) {
7375           // C++98 [class.union]p1: If a union contains a static data member,
7376           // the program is ill-formed. C++11 drops this restriction.
7377           Diag(D.getIdentifierLoc(),
7378                getLangOpts().CPlusPlus11
7379                  ? diag::warn_cxx98_compat_static_data_member_in_union
7380                  : diag::ext_static_data_member_in_union) << Name;
7381         }
7382       }
7383     }
7384 
7385     // Match up the template parameter lists with the scope specifier, then
7386     // determine whether we have a template or a template specialization.
7387     bool InvalidScope = false;
7388     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7389         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7390         D.getCXXScopeSpec(),
7391         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7392             ? D.getName().TemplateId
7393             : nullptr,
7394         TemplateParamLists,
7395         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7396     Invalid |= InvalidScope;
7397 
7398     if (TemplateParams) {
7399       if (!TemplateParams->size() &&
7400           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7401         // There is an extraneous 'template<>' for this variable. Complain
7402         // about it, but allow the declaration of the variable.
7403         Diag(TemplateParams->getTemplateLoc(),
7404              diag::err_template_variable_noparams)
7405           << II
7406           << SourceRange(TemplateParams->getTemplateLoc(),
7407                          TemplateParams->getRAngleLoc());
7408         TemplateParams = nullptr;
7409       } else {
7410         // Check that we can declare a template here.
7411         if (CheckTemplateDeclScope(S, TemplateParams))
7412           return nullptr;
7413 
7414         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7415           // This is an explicit specialization or a partial specialization.
7416           IsVariableTemplateSpecialization = true;
7417           IsPartialSpecialization = TemplateParams->size() > 0;
7418         } else { // if (TemplateParams->size() > 0)
7419           // This is a template declaration.
7420           IsVariableTemplate = true;
7421 
7422           // Only C++1y supports variable templates (N3651).
7423           Diag(D.getIdentifierLoc(),
7424                getLangOpts().CPlusPlus14
7425                    ? diag::warn_cxx11_compat_variable_template
7426                    : diag::ext_variable_template);
7427         }
7428       }
7429     } else {
7430       // Check that we can declare a member specialization here.
7431       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7432           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7433         return nullptr;
7434       assert((Invalid ||
7435               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7436              "should have a 'template<>' for this decl");
7437     }
7438 
7439     if (IsVariableTemplateSpecialization) {
7440       SourceLocation TemplateKWLoc =
7441           TemplateParamLists.size() > 0
7442               ? TemplateParamLists[0]->getTemplateLoc()
7443               : SourceLocation();
7444       DeclResult Res = ActOnVarTemplateSpecialization(
7445           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7446           IsPartialSpecialization);
7447       if (Res.isInvalid())
7448         return nullptr;
7449       NewVD = cast<VarDecl>(Res.get());
7450       AddToScope = false;
7451     } else if (D.isDecompositionDeclarator()) {
7452       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7453                                         D.getIdentifierLoc(), R, TInfo, SC,
7454                                         Bindings);
7455     } else
7456       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7457                               D.getIdentifierLoc(), II, R, TInfo, SC);
7458 
7459     // If this is supposed to be a variable template, create it as such.
7460     if (IsVariableTemplate) {
7461       NewTemplate =
7462           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7463                                   TemplateParams, NewVD);
7464       NewVD->setDescribedVarTemplate(NewTemplate);
7465     }
7466 
7467     // If this decl has an auto type in need of deduction, make a note of the
7468     // Decl so we can diagnose uses of it in its own initializer.
7469     if (R->getContainedDeducedType())
7470       ParsingInitForAutoVars.insert(NewVD);
7471 
7472     if (D.isInvalidType() || Invalid) {
7473       NewVD->setInvalidDecl();
7474       if (NewTemplate)
7475         NewTemplate->setInvalidDecl();
7476     }
7477 
7478     SetNestedNameSpecifier(*this, NewVD, D);
7479 
7480     // If we have any template parameter lists that don't directly belong to
7481     // the variable (matching the scope specifier), store them.
7482     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7483     if (TemplateParamLists.size() > VDTemplateParamLists)
7484       NewVD->setTemplateParameterListsInfo(
7485           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7486   }
7487 
7488   if (D.getDeclSpec().isInlineSpecified()) {
7489     if (!getLangOpts().CPlusPlus) {
7490       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7491           << 0;
7492     } else if (CurContext->isFunctionOrMethod()) {
7493       // 'inline' is not allowed on block scope variable declaration.
7494       Diag(D.getDeclSpec().getInlineSpecLoc(),
7495            diag::err_inline_declaration_block_scope) << Name
7496         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7497     } else {
7498       Diag(D.getDeclSpec().getInlineSpecLoc(),
7499            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7500                                      : diag::ext_inline_variable);
7501       NewVD->setInlineSpecified();
7502     }
7503   }
7504 
7505   // Set the lexical context. If the declarator has a C++ scope specifier, the
7506   // lexical context will be different from the semantic context.
7507   NewVD->setLexicalDeclContext(CurContext);
7508   if (NewTemplate)
7509     NewTemplate->setLexicalDeclContext(CurContext);
7510 
7511   if (IsLocalExternDecl) {
7512     if (D.isDecompositionDeclarator())
7513       for (auto *B : Bindings)
7514         B->setLocalExternDecl();
7515     else
7516       NewVD->setLocalExternDecl();
7517   }
7518 
7519   bool EmitTLSUnsupportedError = false;
7520   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7521     // C++11 [dcl.stc]p4:
7522     //   When thread_local is applied to a variable of block scope the
7523     //   storage-class-specifier static is implied if it does not appear
7524     //   explicitly.
7525     // Core issue: 'static' is not implied if the variable is declared
7526     //   'extern'.
7527     if (NewVD->hasLocalStorage() &&
7528         (SCSpec != DeclSpec::SCS_unspecified ||
7529          TSCS != DeclSpec::TSCS_thread_local ||
7530          !DC->isFunctionOrMethod()))
7531       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7532            diag::err_thread_non_global)
7533         << DeclSpec::getSpecifierName(TSCS);
7534     else if (!Context.getTargetInfo().isTLSSupported()) {
7535       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7536           getLangOpts().SYCLIsDevice) {
7537         // Postpone error emission until we've collected attributes required to
7538         // figure out whether it's a host or device variable and whether the
7539         // error should be ignored.
7540         EmitTLSUnsupportedError = true;
7541         // We still need to mark the variable as TLS so it shows up in AST with
7542         // proper storage class for other tools to use even if we're not going
7543         // to emit any code for it.
7544         NewVD->setTSCSpec(TSCS);
7545       } else
7546         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7547              diag::err_thread_unsupported);
7548     } else
7549       NewVD->setTSCSpec(TSCS);
7550   }
7551 
7552   switch (D.getDeclSpec().getConstexprSpecifier()) {
7553   case ConstexprSpecKind::Unspecified:
7554     break;
7555 
7556   case ConstexprSpecKind::Consteval:
7557     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7558          diag::err_constexpr_wrong_decl_kind)
7559         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7560     LLVM_FALLTHROUGH;
7561 
7562   case ConstexprSpecKind::Constexpr:
7563     NewVD->setConstexpr(true);
7564     // C++1z [dcl.spec.constexpr]p1:
7565     //   A static data member declared with the constexpr specifier is
7566     //   implicitly an inline variable.
7567     if (NewVD->isStaticDataMember() &&
7568         (getLangOpts().CPlusPlus17 ||
7569          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7570       NewVD->setImplicitlyInline();
7571     break;
7572 
7573   case ConstexprSpecKind::Constinit:
7574     if (!NewVD->hasGlobalStorage())
7575       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7576            diag::err_constinit_local_variable);
7577     else
7578       NewVD->addAttr(ConstInitAttr::Create(
7579           Context, D.getDeclSpec().getConstexprSpecLoc(),
7580           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7581     break;
7582   }
7583 
7584   // C99 6.7.4p3
7585   //   An inline definition of a function with external linkage shall
7586   //   not contain a definition of a modifiable object with static or
7587   //   thread storage duration...
7588   // We only apply this when the function is required to be defined
7589   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7590   // that a local variable with thread storage duration still has to
7591   // be marked 'static'.  Also note that it's possible to get these
7592   // semantics in C++ using __attribute__((gnu_inline)).
7593   if (SC == SC_Static && S->getFnParent() != nullptr &&
7594       !NewVD->getType().isConstQualified()) {
7595     FunctionDecl *CurFD = getCurFunctionDecl();
7596     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7597       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7598            diag::warn_static_local_in_extern_inline);
7599       MaybeSuggestAddingStaticToDecl(CurFD);
7600     }
7601   }
7602 
7603   if (D.getDeclSpec().isModulePrivateSpecified()) {
7604     if (IsVariableTemplateSpecialization)
7605       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7606           << (IsPartialSpecialization ? 1 : 0)
7607           << FixItHint::CreateRemoval(
7608                  D.getDeclSpec().getModulePrivateSpecLoc());
7609     else if (IsMemberSpecialization)
7610       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7611         << 2
7612         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7613     else if (NewVD->hasLocalStorage())
7614       Diag(NewVD->getLocation(), diag::err_module_private_local)
7615           << 0 << NewVD
7616           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7617           << FixItHint::CreateRemoval(
7618                  D.getDeclSpec().getModulePrivateSpecLoc());
7619     else {
7620       NewVD->setModulePrivate();
7621       if (NewTemplate)
7622         NewTemplate->setModulePrivate();
7623       for (auto *B : Bindings)
7624         B->setModulePrivate();
7625     }
7626   }
7627 
7628   if (getLangOpts().OpenCL) {
7629     deduceOpenCLAddressSpace(NewVD);
7630 
7631     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7632     if (TSC != TSCS_unspecified) {
7633       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7634            diag::err_opencl_unknown_type_specifier)
7635           << getLangOpts().getOpenCLVersionString()
7636           << DeclSpec::getSpecifierName(TSC) << 1;
7637       NewVD->setInvalidDecl();
7638     }
7639   }
7640 
7641   // Handle attributes prior to checking for duplicates in MergeVarDecl
7642   ProcessDeclAttributes(S, NewVD, D);
7643 
7644   // FIXME: This is probably the wrong location to be doing this and we should
7645   // probably be doing this for more attributes (especially for function
7646   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7647   // the code to copy attributes would be generated by TableGen.
7648   if (R->isFunctionPointerType())
7649     if (const auto *TT = R->getAs<TypedefType>())
7650       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7651 
7652   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7653       getLangOpts().SYCLIsDevice) {
7654     if (EmitTLSUnsupportedError &&
7655         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7656          (getLangOpts().OpenMPIsDevice &&
7657           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7658       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7659            diag::err_thread_unsupported);
7660 
7661     if (EmitTLSUnsupportedError &&
7662         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7663       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7664     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7665     // storage [duration]."
7666     if (SC == SC_None && S->getFnParent() != nullptr &&
7667         (NewVD->hasAttr<CUDASharedAttr>() ||
7668          NewVD->hasAttr<CUDAConstantAttr>())) {
7669       NewVD->setStorageClass(SC_Static);
7670     }
7671   }
7672 
7673   // Ensure that dllimport globals without explicit storage class are treated as
7674   // extern. The storage class is set above using parsed attributes. Now we can
7675   // check the VarDecl itself.
7676   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7677          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7678          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7679 
7680   // In auto-retain/release, infer strong retension for variables of
7681   // retainable type.
7682   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7683     NewVD->setInvalidDecl();
7684 
7685   // Handle GNU asm-label extension (encoded as an attribute).
7686   if (Expr *E = (Expr*)D.getAsmLabel()) {
7687     // The parser guarantees this is a string.
7688     StringLiteral *SE = cast<StringLiteral>(E);
7689     StringRef Label = SE->getString();
7690     if (S->getFnParent() != nullptr) {
7691       switch (SC) {
7692       case SC_None:
7693       case SC_Auto:
7694         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7695         break;
7696       case SC_Register:
7697         // Local Named register
7698         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7699             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7700           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7701         break;
7702       case SC_Static:
7703       case SC_Extern:
7704       case SC_PrivateExtern:
7705         break;
7706       }
7707     } else if (SC == SC_Register) {
7708       // Global Named register
7709       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7710         const auto &TI = Context.getTargetInfo();
7711         bool HasSizeMismatch;
7712 
7713         if (!TI.isValidGCCRegisterName(Label))
7714           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7715         else if (!TI.validateGlobalRegisterVariable(Label,
7716                                                     Context.getTypeSize(R),
7717                                                     HasSizeMismatch))
7718           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7719         else if (HasSizeMismatch)
7720           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7721       }
7722 
7723       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7724         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7725         NewVD->setInvalidDecl(true);
7726       }
7727     }
7728 
7729     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7730                                         /*IsLiteralLabel=*/true,
7731                                         SE->getStrTokenLoc(0)));
7732   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7733     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7734       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7735     if (I != ExtnameUndeclaredIdentifiers.end()) {
7736       if (isDeclExternC(NewVD)) {
7737         NewVD->addAttr(I->second);
7738         ExtnameUndeclaredIdentifiers.erase(I);
7739       } else
7740         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7741             << /*Variable*/1 << NewVD;
7742     }
7743   }
7744 
7745   // Find the shadowed declaration before filtering for scope.
7746   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7747                                 ? getShadowedDeclaration(NewVD, Previous)
7748                                 : nullptr;
7749 
7750   // Don't consider existing declarations that are in a different
7751   // scope and are out-of-semantic-context declarations (if the new
7752   // declaration has linkage).
7753   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7754                        D.getCXXScopeSpec().isNotEmpty() ||
7755                        IsMemberSpecialization ||
7756                        IsVariableTemplateSpecialization);
7757 
7758   // Check whether the previous declaration is in the same block scope. This
7759   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7760   if (getLangOpts().CPlusPlus &&
7761       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7762     NewVD->setPreviousDeclInSameBlockScope(
7763         Previous.isSingleResult() && !Previous.isShadowed() &&
7764         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7765 
7766   if (!getLangOpts().CPlusPlus) {
7767     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7768   } else {
7769     // If this is an explicit specialization of a static data member, check it.
7770     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7771         CheckMemberSpecialization(NewVD, Previous))
7772       NewVD->setInvalidDecl();
7773 
7774     // Merge the decl with the existing one if appropriate.
7775     if (!Previous.empty()) {
7776       if (Previous.isSingleResult() &&
7777           isa<FieldDecl>(Previous.getFoundDecl()) &&
7778           D.getCXXScopeSpec().isSet()) {
7779         // The user tried to define a non-static data member
7780         // out-of-line (C++ [dcl.meaning]p1).
7781         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7782           << D.getCXXScopeSpec().getRange();
7783         Previous.clear();
7784         NewVD->setInvalidDecl();
7785       }
7786     } else if (D.getCXXScopeSpec().isSet()) {
7787       // No previous declaration in the qualifying scope.
7788       Diag(D.getIdentifierLoc(), diag::err_no_member)
7789         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7790         << D.getCXXScopeSpec().getRange();
7791       NewVD->setInvalidDecl();
7792     }
7793 
7794     if (!IsVariableTemplateSpecialization)
7795       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7796 
7797     if (NewTemplate) {
7798       VarTemplateDecl *PrevVarTemplate =
7799           NewVD->getPreviousDecl()
7800               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7801               : nullptr;
7802 
7803       // Check the template parameter list of this declaration, possibly
7804       // merging in the template parameter list from the previous variable
7805       // template declaration.
7806       if (CheckTemplateParameterList(
7807               TemplateParams,
7808               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7809                               : nullptr,
7810               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7811                DC->isDependentContext())
7812                   ? TPC_ClassTemplateMember
7813                   : TPC_VarTemplate))
7814         NewVD->setInvalidDecl();
7815 
7816       // If we are providing an explicit specialization of a static variable
7817       // template, make a note of that.
7818       if (PrevVarTemplate &&
7819           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7820         PrevVarTemplate->setMemberSpecialization();
7821     }
7822   }
7823 
7824   // Diagnose shadowed variables iff this isn't a redeclaration.
7825   if (ShadowedDecl && !D.isRedeclaration())
7826     CheckShadow(NewVD, ShadowedDecl, Previous);
7827 
7828   ProcessPragmaWeak(S, NewVD);
7829 
7830   // If this is the first declaration of an extern C variable, update
7831   // the map of such variables.
7832   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7833       isIncompleteDeclExternC(*this, NewVD))
7834     RegisterLocallyScopedExternCDecl(NewVD, S);
7835 
7836   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7837     MangleNumberingContext *MCtx;
7838     Decl *ManglingContextDecl;
7839     std::tie(MCtx, ManglingContextDecl) =
7840         getCurrentMangleNumberContext(NewVD->getDeclContext());
7841     if (MCtx) {
7842       Context.setManglingNumber(
7843           NewVD, MCtx->getManglingNumber(
7844                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7845       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7846     }
7847   }
7848 
7849   // Special handling of variable named 'main'.
7850   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7851       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7852       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7853 
7854     // C++ [basic.start.main]p3
7855     // A program that declares a variable main at global scope is ill-formed.
7856     if (getLangOpts().CPlusPlus)
7857       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7858 
7859     // In C, and external-linkage variable named main results in undefined
7860     // behavior.
7861     else if (NewVD->hasExternalFormalLinkage())
7862       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7863   }
7864 
7865   if (D.isRedeclaration() && !Previous.empty()) {
7866     NamedDecl *Prev = Previous.getRepresentativeDecl();
7867     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7868                                    D.isFunctionDefinition());
7869   }
7870 
7871   if (NewTemplate) {
7872     if (NewVD->isInvalidDecl())
7873       NewTemplate->setInvalidDecl();
7874     ActOnDocumentableDecl(NewTemplate);
7875     return NewTemplate;
7876   }
7877 
7878   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7879     CompleteMemberSpecialization(NewVD, Previous);
7880 
7881   return NewVD;
7882 }
7883 
7884 /// Enum describing the %select options in diag::warn_decl_shadow.
7885 enum ShadowedDeclKind {
7886   SDK_Local,
7887   SDK_Global,
7888   SDK_StaticMember,
7889   SDK_Field,
7890   SDK_Typedef,
7891   SDK_Using,
7892   SDK_StructuredBinding
7893 };
7894 
7895 /// Determine what kind of declaration we're shadowing.
7896 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7897                                                 const DeclContext *OldDC) {
7898   if (isa<TypeAliasDecl>(ShadowedDecl))
7899     return SDK_Using;
7900   else if (isa<TypedefDecl>(ShadowedDecl))
7901     return SDK_Typedef;
7902   else if (isa<BindingDecl>(ShadowedDecl))
7903     return SDK_StructuredBinding;
7904   else if (isa<RecordDecl>(OldDC))
7905     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7906 
7907   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7908 }
7909 
7910 /// Return the location of the capture if the given lambda captures the given
7911 /// variable \p VD, or an invalid source location otherwise.
7912 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7913                                          const VarDecl *VD) {
7914   for (const Capture &Capture : LSI->Captures) {
7915     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7916       return Capture.getLocation();
7917   }
7918   return SourceLocation();
7919 }
7920 
7921 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7922                                      const LookupResult &R) {
7923   // Only diagnose if we're shadowing an unambiguous field or variable.
7924   if (R.getResultKind() != LookupResult::Found)
7925     return false;
7926 
7927   // Return false if warning is ignored.
7928   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7929 }
7930 
7931 /// Return the declaration shadowed by the given variable \p D, or null
7932 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7933 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7934                                         const LookupResult &R) {
7935   if (!shouldWarnIfShadowedDecl(Diags, R))
7936     return nullptr;
7937 
7938   // Don't diagnose declarations at file scope.
7939   if (D->hasGlobalStorage())
7940     return nullptr;
7941 
7942   NamedDecl *ShadowedDecl = R.getFoundDecl();
7943   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7944                                                             : nullptr;
7945 }
7946 
7947 /// Return the declaration shadowed by the given typedef \p D, or null
7948 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7949 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7950                                         const LookupResult &R) {
7951   // Don't warn if typedef declaration is part of a class
7952   if (D->getDeclContext()->isRecord())
7953     return nullptr;
7954 
7955   if (!shouldWarnIfShadowedDecl(Diags, R))
7956     return nullptr;
7957 
7958   NamedDecl *ShadowedDecl = R.getFoundDecl();
7959   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7960 }
7961 
7962 /// Return the declaration shadowed by the given variable \p D, or null
7963 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7964 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7965                                         const LookupResult &R) {
7966   if (!shouldWarnIfShadowedDecl(Diags, R))
7967     return nullptr;
7968 
7969   NamedDecl *ShadowedDecl = R.getFoundDecl();
7970   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7971                                                             : nullptr;
7972 }
7973 
7974 /// Diagnose variable or built-in function shadowing.  Implements
7975 /// -Wshadow.
7976 ///
7977 /// This method is called whenever a VarDecl is added to a "useful"
7978 /// scope.
7979 ///
7980 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7981 /// \param R the lookup of the name
7982 ///
7983 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7984                        const LookupResult &R) {
7985   DeclContext *NewDC = D->getDeclContext();
7986 
7987   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7988     // Fields are not shadowed by variables in C++ static methods.
7989     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7990       if (MD->isStatic())
7991         return;
7992 
7993     // Fields shadowed by constructor parameters are a special case. Usually
7994     // the constructor initializes the field with the parameter.
7995     if (isa<CXXConstructorDecl>(NewDC))
7996       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7997         // Remember that this was shadowed so we can either warn about its
7998         // modification or its existence depending on warning settings.
7999         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8000         return;
8001       }
8002   }
8003 
8004   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8005     if (shadowedVar->isExternC()) {
8006       // For shadowing external vars, make sure that we point to the global
8007       // declaration, not a locally scoped extern declaration.
8008       for (auto I : shadowedVar->redecls())
8009         if (I->isFileVarDecl()) {
8010           ShadowedDecl = I;
8011           break;
8012         }
8013     }
8014 
8015   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8016 
8017   unsigned WarningDiag = diag::warn_decl_shadow;
8018   SourceLocation CaptureLoc;
8019   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8020       isa<CXXMethodDecl>(NewDC)) {
8021     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8022       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8023         if (RD->getLambdaCaptureDefault() == LCD_None) {
8024           // Try to avoid warnings for lambdas with an explicit capture list.
8025           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8026           // Warn only when the lambda captures the shadowed decl explicitly.
8027           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8028           if (CaptureLoc.isInvalid())
8029             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8030         } else {
8031           // Remember that this was shadowed so we can avoid the warning if the
8032           // shadowed decl isn't captured and the warning settings allow it.
8033           cast<LambdaScopeInfo>(getCurFunction())
8034               ->ShadowingDecls.push_back(
8035                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8036           return;
8037         }
8038       }
8039 
8040       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8041         // A variable can't shadow a local variable in an enclosing scope, if
8042         // they are separated by a non-capturing declaration context.
8043         for (DeclContext *ParentDC = NewDC;
8044              ParentDC && !ParentDC->Equals(OldDC);
8045              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8046           // Only block literals, captured statements, and lambda expressions
8047           // can capture; other scopes don't.
8048           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8049               !isLambdaCallOperator(ParentDC)) {
8050             return;
8051           }
8052         }
8053       }
8054     }
8055   }
8056 
8057   // Only warn about certain kinds of shadowing for class members.
8058   if (NewDC && NewDC->isRecord()) {
8059     // In particular, don't warn about shadowing non-class members.
8060     if (!OldDC->isRecord())
8061       return;
8062 
8063     // TODO: should we warn about static data members shadowing
8064     // static data members from base classes?
8065 
8066     // TODO: don't diagnose for inaccessible shadowed members.
8067     // This is hard to do perfectly because we might friend the
8068     // shadowing context, but that's just a false negative.
8069   }
8070 
8071 
8072   DeclarationName Name = R.getLookupName();
8073 
8074   // Emit warning and note.
8075   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8076   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8077   if (!CaptureLoc.isInvalid())
8078     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8079         << Name << /*explicitly*/ 1;
8080   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8081 }
8082 
8083 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8084 /// when these variables are captured by the lambda.
8085 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8086   for (const auto &Shadow : LSI->ShadowingDecls) {
8087     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8088     // Try to avoid the warning when the shadowed decl isn't captured.
8089     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8090     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8091     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8092                                        ? diag::warn_decl_shadow_uncaptured_local
8093                                        : diag::warn_decl_shadow)
8094         << Shadow.VD->getDeclName()
8095         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8096     if (!CaptureLoc.isInvalid())
8097       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8098           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8099     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8100   }
8101 }
8102 
8103 /// Check -Wshadow without the advantage of a previous lookup.
8104 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8105   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8106     return;
8107 
8108   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8109                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8110   LookupName(R, S);
8111   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8112     CheckShadow(D, ShadowedDecl, R);
8113 }
8114 
8115 /// Check if 'E', which is an expression that is about to be modified, refers
8116 /// to a constructor parameter that shadows a field.
8117 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8118   // Quickly ignore expressions that can't be shadowing ctor parameters.
8119   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8120     return;
8121   E = E->IgnoreParenImpCasts();
8122   auto *DRE = dyn_cast<DeclRefExpr>(E);
8123   if (!DRE)
8124     return;
8125   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8126   auto I = ShadowingDecls.find(D);
8127   if (I == ShadowingDecls.end())
8128     return;
8129   const NamedDecl *ShadowedDecl = I->second;
8130   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8131   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8132   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8133   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8134 
8135   // Avoid issuing multiple warnings about the same decl.
8136   ShadowingDecls.erase(I);
8137 }
8138 
8139 /// Check for conflict between this global or extern "C" declaration and
8140 /// previous global or extern "C" declarations. This is only used in C++.
8141 template<typename T>
8142 static bool checkGlobalOrExternCConflict(
8143     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8144   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8145   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8146 
8147   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8148     // The common case: this global doesn't conflict with any extern "C"
8149     // declaration.
8150     return false;
8151   }
8152 
8153   if (Prev) {
8154     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8155       // Both the old and new declarations have C language linkage. This is a
8156       // redeclaration.
8157       Previous.clear();
8158       Previous.addDecl(Prev);
8159       return true;
8160     }
8161 
8162     // This is a global, non-extern "C" declaration, and there is a previous
8163     // non-global extern "C" declaration. Diagnose if this is a variable
8164     // declaration.
8165     if (!isa<VarDecl>(ND))
8166       return false;
8167   } else {
8168     // The declaration is extern "C". Check for any declaration in the
8169     // translation unit which might conflict.
8170     if (IsGlobal) {
8171       // We have already performed the lookup into the translation unit.
8172       IsGlobal = false;
8173       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8174            I != E; ++I) {
8175         if (isa<VarDecl>(*I)) {
8176           Prev = *I;
8177           break;
8178         }
8179       }
8180     } else {
8181       DeclContext::lookup_result R =
8182           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8183       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8184            I != E; ++I) {
8185         if (isa<VarDecl>(*I)) {
8186           Prev = *I;
8187           break;
8188         }
8189         // FIXME: If we have any other entity with this name in global scope,
8190         // the declaration is ill-formed, but that is a defect: it breaks the
8191         // 'stat' hack, for instance. Only variables can have mangled name
8192         // clashes with extern "C" declarations, so only they deserve a
8193         // diagnostic.
8194       }
8195     }
8196 
8197     if (!Prev)
8198       return false;
8199   }
8200 
8201   // Use the first declaration's location to ensure we point at something which
8202   // is lexically inside an extern "C" linkage-spec.
8203   assert(Prev && "should have found a previous declaration to diagnose");
8204   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8205     Prev = FD->getFirstDecl();
8206   else
8207     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8208 
8209   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8210     << IsGlobal << ND;
8211   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8212     << IsGlobal;
8213   return false;
8214 }
8215 
8216 /// Apply special rules for handling extern "C" declarations. Returns \c true
8217 /// if we have found that this is a redeclaration of some prior entity.
8218 ///
8219 /// Per C++ [dcl.link]p6:
8220 ///   Two declarations [for a function or variable] with C language linkage
8221 ///   with the same name that appear in different scopes refer to the same
8222 ///   [entity]. An entity with C language linkage shall not be declared with
8223 ///   the same name as an entity in global scope.
8224 template<typename T>
8225 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8226                                                   LookupResult &Previous) {
8227   if (!S.getLangOpts().CPlusPlus) {
8228     // In C, when declaring a global variable, look for a corresponding 'extern'
8229     // variable declared in function scope. We don't need this in C++, because
8230     // we find local extern decls in the surrounding file-scope DeclContext.
8231     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8232       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8233         Previous.clear();
8234         Previous.addDecl(Prev);
8235         return true;
8236       }
8237     }
8238     return false;
8239   }
8240 
8241   // A declaration in the translation unit can conflict with an extern "C"
8242   // declaration.
8243   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8244     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8245 
8246   // An extern "C" declaration can conflict with a declaration in the
8247   // translation unit or can be a redeclaration of an extern "C" declaration
8248   // in another scope.
8249   if (isIncompleteDeclExternC(S,ND))
8250     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8251 
8252   // Neither global nor extern "C": nothing to do.
8253   return false;
8254 }
8255 
8256 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8257   // If the decl is already known invalid, don't check it.
8258   if (NewVD->isInvalidDecl())
8259     return;
8260 
8261   QualType T = NewVD->getType();
8262 
8263   // Defer checking an 'auto' type until its initializer is attached.
8264   if (T->isUndeducedType())
8265     return;
8266 
8267   if (NewVD->hasAttrs())
8268     CheckAlignasUnderalignment(NewVD);
8269 
8270   if (T->isObjCObjectType()) {
8271     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8272       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8273     T = Context.getObjCObjectPointerType(T);
8274     NewVD->setType(T);
8275   }
8276 
8277   // Emit an error if an address space was applied to decl with local storage.
8278   // This includes arrays of objects with address space qualifiers, but not
8279   // automatic variables that point to other address spaces.
8280   // ISO/IEC TR 18037 S5.1.2
8281   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8282       T.getAddressSpace() != LangAS::Default) {
8283     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8284     NewVD->setInvalidDecl();
8285     return;
8286   }
8287 
8288   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8289   // scope.
8290   if (getLangOpts().OpenCLVersion == 120 &&
8291       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8292                                             getLangOpts()) &&
8293       NewVD->isStaticLocal()) {
8294     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8295     NewVD->setInvalidDecl();
8296     return;
8297   }
8298 
8299   if (getLangOpts().OpenCL) {
8300     if (!diagnoseOpenCLTypes(*this, NewVD))
8301       return;
8302 
8303     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8304     if (NewVD->hasAttr<BlocksAttr>()) {
8305       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8306       return;
8307     }
8308 
8309     if (T->isBlockPointerType()) {
8310       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8311       // can't use 'extern' storage class.
8312       if (!T.isConstQualified()) {
8313         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8314             << 0 /*const*/;
8315         NewVD->setInvalidDecl();
8316         return;
8317       }
8318       if (NewVD->hasExternalStorage()) {
8319         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8320         NewVD->setInvalidDecl();
8321         return;
8322       }
8323     }
8324 
8325     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8326     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8327         NewVD->hasExternalStorage()) {
8328       if (!T->isSamplerT() && !T->isDependentType() &&
8329           !(T.getAddressSpace() == LangAS::opencl_constant ||
8330             (T.getAddressSpace() == LangAS::opencl_global &&
8331              getOpenCLOptions().areProgramScopeVariablesSupported(
8332                  getLangOpts())))) {
8333         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8334         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8335           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8336               << Scope << "global or constant";
8337         else
8338           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8339               << Scope << "constant";
8340         NewVD->setInvalidDecl();
8341         return;
8342       }
8343     } else {
8344       if (T.getAddressSpace() == LangAS::opencl_global) {
8345         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8346             << 1 /*is any function*/ << "global";
8347         NewVD->setInvalidDecl();
8348         return;
8349       }
8350       if (T.getAddressSpace() == LangAS::opencl_constant ||
8351           T.getAddressSpace() == LangAS::opencl_local) {
8352         FunctionDecl *FD = getCurFunctionDecl();
8353         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8354         // in functions.
8355         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8356           if (T.getAddressSpace() == LangAS::opencl_constant)
8357             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8358                 << 0 /*non-kernel only*/ << "constant";
8359           else
8360             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8361                 << 0 /*non-kernel only*/ << "local";
8362           NewVD->setInvalidDecl();
8363           return;
8364         }
8365         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8366         // in the outermost scope of a kernel function.
8367         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8368           if (!getCurScope()->isFunctionScope()) {
8369             if (T.getAddressSpace() == LangAS::opencl_constant)
8370               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8371                   << "constant";
8372             else
8373               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8374                   << "local";
8375             NewVD->setInvalidDecl();
8376             return;
8377           }
8378         }
8379       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8380                  // If we are parsing a template we didn't deduce an addr
8381                  // space yet.
8382                  T.getAddressSpace() != LangAS::Default) {
8383         // Do not allow other address spaces on automatic variable.
8384         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8385         NewVD->setInvalidDecl();
8386         return;
8387       }
8388     }
8389   }
8390 
8391   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8392       && !NewVD->hasAttr<BlocksAttr>()) {
8393     if (getLangOpts().getGC() != LangOptions::NonGC)
8394       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8395     else {
8396       assert(!getLangOpts().ObjCAutoRefCount);
8397       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8398     }
8399   }
8400 
8401   bool isVM = T->isVariablyModifiedType();
8402   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8403       NewVD->hasAttr<BlocksAttr>())
8404     setFunctionHasBranchProtectedScope();
8405 
8406   if ((isVM && NewVD->hasLinkage()) ||
8407       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8408     bool SizeIsNegative;
8409     llvm::APSInt Oversized;
8410     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8411         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8412     QualType FixedT;
8413     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8414       FixedT = FixedTInfo->getType();
8415     else if (FixedTInfo) {
8416       // Type and type-as-written are canonically different. We need to fix up
8417       // both types separately.
8418       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8419                                                    Oversized);
8420     }
8421     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8422       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8423       // FIXME: This won't give the correct result for
8424       // int a[10][n];
8425       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8426 
8427       if (NewVD->isFileVarDecl())
8428         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8429         << SizeRange;
8430       else if (NewVD->isStaticLocal())
8431         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8432         << SizeRange;
8433       else
8434         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8435         << SizeRange;
8436       NewVD->setInvalidDecl();
8437       return;
8438     }
8439 
8440     if (!FixedTInfo) {
8441       if (NewVD->isFileVarDecl())
8442         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8443       else
8444         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8445       NewVD->setInvalidDecl();
8446       return;
8447     }
8448 
8449     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8450     NewVD->setType(FixedT);
8451     NewVD->setTypeSourceInfo(FixedTInfo);
8452   }
8453 
8454   if (T->isVoidType()) {
8455     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8456     //                    of objects and functions.
8457     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8458       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8459         << T;
8460       NewVD->setInvalidDecl();
8461       return;
8462     }
8463   }
8464 
8465   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8466     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8467     NewVD->setInvalidDecl();
8468     return;
8469   }
8470 
8471   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8472     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8473     NewVD->setInvalidDecl();
8474     return;
8475   }
8476 
8477   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8478     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8479     NewVD->setInvalidDecl();
8480     return;
8481   }
8482 
8483   if (NewVD->isConstexpr() && !T->isDependentType() &&
8484       RequireLiteralType(NewVD->getLocation(), T,
8485                          diag::err_constexpr_var_non_literal)) {
8486     NewVD->setInvalidDecl();
8487     return;
8488   }
8489 
8490   // PPC MMA non-pointer types are not allowed as non-local variable types.
8491   if (Context.getTargetInfo().getTriple().isPPC64() &&
8492       !NewVD->isLocalVarDecl() &&
8493       CheckPPCMMAType(T, NewVD->getLocation())) {
8494     NewVD->setInvalidDecl();
8495     return;
8496   }
8497 }
8498 
8499 /// Perform semantic checking on a newly-created variable
8500 /// declaration.
8501 ///
8502 /// This routine performs all of the type-checking required for a
8503 /// variable declaration once it has been built. It is used both to
8504 /// check variables after they have been parsed and their declarators
8505 /// have been translated into a declaration, and to check variables
8506 /// that have been instantiated from a template.
8507 ///
8508 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8509 ///
8510 /// Returns true if the variable declaration is a redeclaration.
8511 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8512   CheckVariableDeclarationType(NewVD);
8513 
8514   // If the decl is already known invalid, don't check it.
8515   if (NewVD->isInvalidDecl())
8516     return false;
8517 
8518   // If we did not find anything by this name, look for a non-visible
8519   // extern "C" declaration with the same name.
8520   if (Previous.empty() &&
8521       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8522     Previous.setShadowed();
8523 
8524   if (!Previous.empty()) {
8525     MergeVarDecl(NewVD, Previous);
8526     return true;
8527   }
8528   return false;
8529 }
8530 
8531 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8532 /// and if so, check that it's a valid override and remember it.
8533 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8534   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8535 
8536   // Look for methods in base classes that this method might override.
8537   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8538                      /*DetectVirtual=*/false);
8539   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8540     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8541     DeclarationName Name = MD->getDeclName();
8542 
8543     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8544       // We really want to find the base class destructor here.
8545       QualType T = Context.getTypeDeclType(BaseRecord);
8546       CanQualType CT = Context.getCanonicalType(T);
8547       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8548     }
8549 
8550     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8551       CXXMethodDecl *BaseMD =
8552           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8553       if (!BaseMD || !BaseMD->isVirtual() ||
8554           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8555                      /*ConsiderCudaAttrs=*/true,
8556                      // C++2a [class.virtual]p2 does not consider requires
8557                      // clauses when overriding.
8558                      /*ConsiderRequiresClauses=*/false))
8559         continue;
8560 
8561       if (Overridden.insert(BaseMD).second) {
8562         MD->addOverriddenMethod(BaseMD);
8563         CheckOverridingFunctionReturnType(MD, BaseMD);
8564         CheckOverridingFunctionAttributes(MD, BaseMD);
8565         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8566         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8567       }
8568 
8569       // A method can only override one function from each base class. We
8570       // don't track indirectly overridden methods from bases of bases.
8571       return true;
8572     }
8573 
8574     return false;
8575   };
8576 
8577   DC->lookupInBases(VisitBase, Paths);
8578   return !Overridden.empty();
8579 }
8580 
8581 namespace {
8582   // Struct for holding all of the extra arguments needed by
8583   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8584   struct ActOnFDArgs {
8585     Scope *S;
8586     Declarator &D;
8587     MultiTemplateParamsArg TemplateParamLists;
8588     bool AddToScope;
8589   };
8590 } // end anonymous namespace
8591 
8592 namespace {
8593 
8594 // Callback to only accept typo corrections that have a non-zero edit distance.
8595 // Also only accept corrections that have the same parent decl.
8596 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8597  public:
8598   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8599                             CXXRecordDecl *Parent)
8600       : Context(Context), OriginalFD(TypoFD),
8601         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8602 
8603   bool ValidateCandidate(const TypoCorrection &candidate) override {
8604     if (candidate.getEditDistance() == 0)
8605       return false;
8606 
8607     SmallVector<unsigned, 1> MismatchedParams;
8608     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8609                                           CDeclEnd = candidate.end();
8610          CDecl != CDeclEnd; ++CDecl) {
8611       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8612 
8613       if (FD && !FD->hasBody() &&
8614           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8615         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8616           CXXRecordDecl *Parent = MD->getParent();
8617           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8618             return true;
8619         } else if (!ExpectedParent) {
8620           return true;
8621         }
8622       }
8623     }
8624 
8625     return false;
8626   }
8627 
8628   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8629     return std::make_unique<DifferentNameValidatorCCC>(*this);
8630   }
8631 
8632  private:
8633   ASTContext &Context;
8634   FunctionDecl *OriginalFD;
8635   CXXRecordDecl *ExpectedParent;
8636 };
8637 
8638 } // end anonymous namespace
8639 
8640 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8641   TypoCorrectedFunctionDefinitions.insert(F);
8642 }
8643 
8644 /// Generate diagnostics for an invalid function redeclaration.
8645 ///
8646 /// This routine handles generating the diagnostic messages for an invalid
8647 /// function redeclaration, including finding possible similar declarations
8648 /// or performing typo correction if there are no previous declarations with
8649 /// the same name.
8650 ///
8651 /// Returns a NamedDecl iff typo correction was performed and substituting in
8652 /// the new declaration name does not cause new errors.
8653 static NamedDecl *DiagnoseInvalidRedeclaration(
8654     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8655     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8656   DeclarationName Name = NewFD->getDeclName();
8657   DeclContext *NewDC = NewFD->getDeclContext();
8658   SmallVector<unsigned, 1> MismatchedParams;
8659   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8660   TypoCorrection Correction;
8661   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8662   unsigned DiagMsg =
8663     IsLocalFriend ? diag::err_no_matching_local_friend :
8664     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8665     diag::err_member_decl_does_not_match;
8666   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8667                     IsLocalFriend ? Sema::LookupLocalFriendName
8668                                   : Sema::LookupOrdinaryName,
8669                     Sema::ForVisibleRedeclaration);
8670 
8671   NewFD->setInvalidDecl();
8672   if (IsLocalFriend)
8673     SemaRef.LookupName(Prev, S);
8674   else
8675     SemaRef.LookupQualifiedName(Prev, NewDC);
8676   assert(!Prev.isAmbiguous() &&
8677          "Cannot have an ambiguity in previous-declaration lookup");
8678   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8679   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8680                                 MD ? MD->getParent() : nullptr);
8681   if (!Prev.empty()) {
8682     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8683          Func != FuncEnd; ++Func) {
8684       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8685       if (FD &&
8686           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8687         // Add 1 to the index so that 0 can mean the mismatch didn't
8688         // involve a parameter
8689         unsigned ParamNum =
8690             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8691         NearMatches.push_back(std::make_pair(FD, ParamNum));
8692       }
8693     }
8694   // If the qualified name lookup yielded nothing, try typo correction
8695   } else if ((Correction = SemaRef.CorrectTypo(
8696                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8697                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8698                   IsLocalFriend ? nullptr : NewDC))) {
8699     // Set up everything for the call to ActOnFunctionDeclarator
8700     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8701                               ExtraArgs.D.getIdentifierLoc());
8702     Previous.clear();
8703     Previous.setLookupName(Correction.getCorrection());
8704     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8705                                     CDeclEnd = Correction.end();
8706          CDecl != CDeclEnd; ++CDecl) {
8707       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8708       if (FD && !FD->hasBody() &&
8709           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8710         Previous.addDecl(FD);
8711       }
8712     }
8713     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8714 
8715     NamedDecl *Result;
8716     // Retry building the function declaration with the new previous
8717     // declarations, and with errors suppressed.
8718     {
8719       // Trap errors.
8720       Sema::SFINAETrap Trap(SemaRef);
8721 
8722       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8723       // pieces need to verify the typo-corrected C++ declaration and hopefully
8724       // eliminate the need for the parameter pack ExtraArgs.
8725       Result = SemaRef.ActOnFunctionDeclarator(
8726           ExtraArgs.S, ExtraArgs.D,
8727           Correction.getCorrectionDecl()->getDeclContext(),
8728           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8729           ExtraArgs.AddToScope);
8730 
8731       if (Trap.hasErrorOccurred())
8732         Result = nullptr;
8733     }
8734 
8735     if (Result) {
8736       // Determine which correction we picked.
8737       Decl *Canonical = Result->getCanonicalDecl();
8738       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8739            I != E; ++I)
8740         if ((*I)->getCanonicalDecl() == Canonical)
8741           Correction.setCorrectionDecl(*I);
8742 
8743       // Let Sema know about the correction.
8744       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8745       SemaRef.diagnoseTypo(
8746           Correction,
8747           SemaRef.PDiag(IsLocalFriend
8748                           ? diag::err_no_matching_local_friend_suggest
8749                           : diag::err_member_decl_does_not_match_suggest)
8750             << Name << NewDC << IsDefinition);
8751       return Result;
8752     }
8753 
8754     // Pretend the typo correction never occurred
8755     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8756                               ExtraArgs.D.getIdentifierLoc());
8757     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8758     Previous.clear();
8759     Previous.setLookupName(Name);
8760   }
8761 
8762   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8763       << Name << NewDC << IsDefinition << NewFD->getLocation();
8764 
8765   bool NewFDisConst = false;
8766   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8767     NewFDisConst = NewMD->isConst();
8768 
8769   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8770        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8771        NearMatch != NearMatchEnd; ++NearMatch) {
8772     FunctionDecl *FD = NearMatch->first;
8773     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8774     bool FDisConst = MD && MD->isConst();
8775     bool IsMember = MD || !IsLocalFriend;
8776 
8777     // FIXME: These notes are poorly worded for the local friend case.
8778     if (unsigned Idx = NearMatch->second) {
8779       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8780       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8781       if (Loc.isInvalid()) Loc = FD->getLocation();
8782       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8783                                  : diag::note_local_decl_close_param_match)
8784         << Idx << FDParam->getType()
8785         << NewFD->getParamDecl(Idx - 1)->getType();
8786     } else if (FDisConst != NewFDisConst) {
8787       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8788           << NewFDisConst << FD->getSourceRange().getEnd()
8789           << (NewFDisConst
8790                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8791                                                  .getConstQualifierLoc())
8792                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8793                                                    .getRParenLoc()
8794                                                    .getLocWithOffset(1),
8795                                                " const"));
8796     } else
8797       SemaRef.Diag(FD->getLocation(),
8798                    IsMember ? diag::note_member_def_close_match
8799                             : diag::note_local_decl_close_match);
8800   }
8801   return nullptr;
8802 }
8803 
8804 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8805   switch (D.getDeclSpec().getStorageClassSpec()) {
8806   default: llvm_unreachable("Unknown storage class!");
8807   case DeclSpec::SCS_auto:
8808   case DeclSpec::SCS_register:
8809   case DeclSpec::SCS_mutable:
8810     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8811                  diag::err_typecheck_sclass_func);
8812     D.getMutableDeclSpec().ClearStorageClassSpecs();
8813     D.setInvalidType();
8814     break;
8815   case DeclSpec::SCS_unspecified: break;
8816   case DeclSpec::SCS_extern:
8817     if (D.getDeclSpec().isExternInLinkageSpec())
8818       return SC_None;
8819     return SC_Extern;
8820   case DeclSpec::SCS_static: {
8821     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8822       // C99 6.7.1p5:
8823       //   The declaration of an identifier for a function that has
8824       //   block scope shall have no explicit storage-class specifier
8825       //   other than extern
8826       // See also (C++ [dcl.stc]p4).
8827       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8828                    diag::err_static_block_func);
8829       break;
8830     } else
8831       return SC_Static;
8832   }
8833   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8834   }
8835 
8836   // No explicit storage class has already been returned
8837   return SC_None;
8838 }
8839 
8840 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8841                                            DeclContext *DC, QualType &R,
8842                                            TypeSourceInfo *TInfo,
8843                                            StorageClass SC,
8844                                            bool &IsVirtualOkay) {
8845   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8846   DeclarationName Name = NameInfo.getName();
8847 
8848   FunctionDecl *NewFD = nullptr;
8849   bool isInline = D.getDeclSpec().isInlineSpecified();
8850 
8851   if (!SemaRef.getLangOpts().CPlusPlus) {
8852     // Determine whether the function was written with a prototype. This is
8853     // true when:
8854     //   - there is a prototype in the declarator, or
8855     //   - the type R of the function is some kind of typedef or other non-
8856     //     attributed reference to a type name (which eventually refers to a
8857     //     function type). Note, we can't always look at the adjusted type to
8858     //     check this case because attributes may cause a non-function
8859     //     declarator to still have a function type. e.g.,
8860     //       typedef void func(int a);
8861     //       __attribute__((noreturn)) func other_func; // This has a prototype
8862     bool HasPrototype =
8863         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8864         (D.getDeclSpec().isTypeRep() &&
8865          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8866         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8867     assert(
8868         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8869         "Strict prototypes are required");
8870 
8871     NewFD = FunctionDecl::Create(
8872         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8873         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8874         ConstexprSpecKind::Unspecified,
8875         /*TrailingRequiresClause=*/nullptr);
8876     if (D.isInvalidType())
8877       NewFD->setInvalidDecl();
8878 
8879     return NewFD;
8880   }
8881 
8882   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8883 
8884   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8885   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8886     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8887                  diag::err_constexpr_wrong_decl_kind)
8888         << static_cast<int>(ConstexprKind);
8889     ConstexprKind = ConstexprSpecKind::Unspecified;
8890     D.getMutableDeclSpec().ClearConstexprSpec();
8891   }
8892   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8893 
8894   // Check that the return type is not an abstract class type.
8895   // For record types, this is done by the AbstractClassUsageDiagnoser once
8896   // the class has been completely parsed.
8897   if (!DC->isRecord() &&
8898       SemaRef.RequireNonAbstractType(
8899           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8900           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8901     D.setInvalidType();
8902 
8903   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8904     // This is a C++ constructor declaration.
8905     assert(DC->isRecord() &&
8906            "Constructors can only be declared in a member context");
8907 
8908     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8909     return CXXConstructorDecl::Create(
8910         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8911         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8912         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8913         InheritedConstructor(), TrailingRequiresClause);
8914 
8915   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8916     // This is a C++ destructor declaration.
8917     if (DC->isRecord()) {
8918       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8919       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8920       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8921           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8922           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8923           /*isImplicitlyDeclared=*/false, ConstexprKind,
8924           TrailingRequiresClause);
8925       // User defined destructors start as not selected if the class definition is still
8926       // not done.
8927       if (Record->isBeingDefined())
8928         NewDD->setIneligibleOrNotSelected(true);
8929 
8930       // If the destructor needs an implicit exception specification, set it
8931       // now. FIXME: It'd be nice to be able to create the right type to start
8932       // with, but the type needs to reference the destructor declaration.
8933       if (SemaRef.getLangOpts().CPlusPlus11)
8934         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8935 
8936       IsVirtualOkay = true;
8937       return NewDD;
8938 
8939     } else {
8940       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8941       D.setInvalidType();
8942 
8943       // Create a FunctionDecl to satisfy the function definition parsing
8944       // code path.
8945       return FunctionDecl::Create(
8946           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8947           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8948           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8949     }
8950 
8951   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8952     if (!DC->isRecord()) {
8953       SemaRef.Diag(D.getIdentifierLoc(),
8954            diag::err_conv_function_not_member);
8955       return nullptr;
8956     }
8957 
8958     SemaRef.CheckConversionDeclarator(D, R, SC);
8959     if (D.isInvalidType())
8960       return nullptr;
8961 
8962     IsVirtualOkay = true;
8963     return CXXConversionDecl::Create(
8964         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8965         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8966         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8967         TrailingRequiresClause);
8968 
8969   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8970     if (TrailingRequiresClause)
8971       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8972                    diag::err_trailing_requires_clause_on_deduction_guide)
8973           << TrailingRequiresClause->getSourceRange();
8974     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8975 
8976     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8977                                          ExplicitSpecifier, NameInfo, R, TInfo,
8978                                          D.getEndLoc());
8979   } else if (DC->isRecord()) {
8980     // If the name of the function is the same as the name of the record,
8981     // then this must be an invalid constructor that has a return type.
8982     // (The parser checks for a return type and makes the declarator a
8983     // constructor if it has no return type).
8984     if (Name.getAsIdentifierInfo() &&
8985         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8986       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8987         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8988         << SourceRange(D.getIdentifierLoc());
8989       return nullptr;
8990     }
8991 
8992     // This is a C++ method declaration.
8993     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8994         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8995         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8996         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8997     IsVirtualOkay = !Ret->isStatic();
8998     return Ret;
8999   } else {
9000     bool isFriend =
9001         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9002     if (!isFriend && SemaRef.CurContext->isRecord())
9003       return nullptr;
9004 
9005     // Determine whether the function was written with a
9006     // prototype. This true when:
9007     //   - we're in C++ (where every function has a prototype),
9008     return FunctionDecl::Create(
9009         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9010         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9011         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9012   }
9013 }
9014 
9015 enum OpenCLParamType {
9016   ValidKernelParam,
9017   PtrPtrKernelParam,
9018   PtrKernelParam,
9019   InvalidAddrSpacePtrKernelParam,
9020   InvalidKernelParam,
9021   RecordKernelParam
9022 };
9023 
9024 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9025   // Size dependent types are just typedefs to normal integer types
9026   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9027   // integers other than by their names.
9028   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9029 
9030   // Remove typedefs one by one until we reach a typedef
9031   // for a size dependent type.
9032   QualType DesugaredTy = Ty;
9033   do {
9034     ArrayRef<StringRef> Names(SizeTypeNames);
9035     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9036     if (Names.end() != Match)
9037       return true;
9038 
9039     Ty = DesugaredTy;
9040     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9041   } while (DesugaredTy != Ty);
9042 
9043   return false;
9044 }
9045 
9046 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9047   if (PT->isDependentType())
9048     return InvalidKernelParam;
9049 
9050   if (PT->isPointerType() || PT->isReferenceType()) {
9051     QualType PointeeType = PT->getPointeeType();
9052     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9053         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9054         PointeeType.getAddressSpace() == LangAS::Default)
9055       return InvalidAddrSpacePtrKernelParam;
9056 
9057     if (PointeeType->isPointerType()) {
9058       // This is a pointer to pointer parameter.
9059       // Recursively check inner type.
9060       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9061       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9062           ParamKind == InvalidKernelParam)
9063         return ParamKind;
9064 
9065       return PtrPtrKernelParam;
9066     }
9067 
9068     // C++ for OpenCL v1.0 s2.4:
9069     // Moreover the types used in parameters of the kernel functions must be:
9070     // Standard layout types for pointer parameters. The same applies to
9071     // reference if an implementation supports them in kernel parameters.
9072     if (S.getLangOpts().OpenCLCPlusPlus &&
9073         !S.getOpenCLOptions().isAvailableOption(
9074             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9075         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9076         !PointeeType->isStandardLayoutType())
9077       return InvalidKernelParam;
9078 
9079     return PtrKernelParam;
9080   }
9081 
9082   // OpenCL v1.2 s6.9.k:
9083   // Arguments to kernel functions in a program cannot be declared with the
9084   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9085   // uintptr_t or a struct and/or union that contain fields declared to be one
9086   // of these built-in scalar types.
9087   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9088     return InvalidKernelParam;
9089 
9090   if (PT->isImageType())
9091     return PtrKernelParam;
9092 
9093   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9094     return InvalidKernelParam;
9095 
9096   // OpenCL extension spec v1.2 s9.5:
9097   // This extension adds support for half scalar and vector types as built-in
9098   // types that can be used for arithmetic operations, conversions etc.
9099   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9100       PT->isHalfType())
9101     return InvalidKernelParam;
9102 
9103   // Look into an array argument to check if it has a forbidden type.
9104   if (PT->isArrayType()) {
9105     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9106     // Call ourself to check an underlying type of an array. Since the
9107     // getPointeeOrArrayElementType returns an innermost type which is not an
9108     // array, this recursive call only happens once.
9109     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9110   }
9111 
9112   // C++ for OpenCL v1.0 s2.4:
9113   // Moreover the types used in parameters of the kernel functions must be:
9114   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9115   // types) for parameters passed by value;
9116   if (S.getLangOpts().OpenCLCPlusPlus &&
9117       !S.getOpenCLOptions().isAvailableOption(
9118           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9119       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9120     return InvalidKernelParam;
9121 
9122   if (PT->isRecordType())
9123     return RecordKernelParam;
9124 
9125   return ValidKernelParam;
9126 }
9127 
9128 static void checkIsValidOpenCLKernelParameter(
9129   Sema &S,
9130   Declarator &D,
9131   ParmVarDecl *Param,
9132   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9133   QualType PT = Param->getType();
9134 
9135   // Cache the valid types we encounter to avoid rechecking structs that are
9136   // used again
9137   if (ValidTypes.count(PT.getTypePtr()))
9138     return;
9139 
9140   switch (getOpenCLKernelParameterType(S, PT)) {
9141   case PtrPtrKernelParam:
9142     // OpenCL v3.0 s6.11.a:
9143     // A kernel function argument cannot be declared as a pointer to a pointer
9144     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9145     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9146       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9147       D.setInvalidType();
9148       return;
9149     }
9150 
9151     ValidTypes.insert(PT.getTypePtr());
9152     return;
9153 
9154   case InvalidAddrSpacePtrKernelParam:
9155     // OpenCL v1.0 s6.5:
9156     // __kernel function arguments declared to be a pointer of a type can point
9157     // to one of the following address spaces only : __global, __local or
9158     // __constant.
9159     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9160     D.setInvalidType();
9161     return;
9162 
9163     // OpenCL v1.2 s6.9.k:
9164     // Arguments to kernel functions in a program cannot be declared with the
9165     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9166     // uintptr_t or a struct and/or union that contain fields declared to be
9167     // one of these built-in scalar types.
9168 
9169   case InvalidKernelParam:
9170     // OpenCL v1.2 s6.8 n:
9171     // A kernel function argument cannot be declared
9172     // of event_t type.
9173     // Do not diagnose half type since it is diagnosed as invalid argument
9174     // type for any function elsewhere.
9175     if (!PT->isHalfType()) {
9176       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9177 
9178       // Explain what typedefs are involved.
9179       const TypedefType *Typedef = nullptr;
9180       while ((Typedef = PT->getAs<TypedefType>())) {
9181         SourceLocation Loc = Typedef->getDecl()->getLocation();
9182         // SourceLocation may be invalid for a built-in type.
9183         if (Loc.isValid())
9184           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9185         PT = Typedef->desugar();
9186       }
9187     }
9188 
9189     D.setInvalidType();
9190     return;
9191 
9192   case PtrKernelParam:
9193   case ValidKernelParam:
9194     ValidTypes.insert(PT.getTypePtr());
9195     return;
9196 
9197   case RecordKernelParam:
9198     break;
9199   }
9200 
9201   // Track nested structs we will inspect
9202   SmallVector<const Decl *, 4> VisitStack;
9203 
9204   // Track where we are in the nested structs. Items will migrate from
9205   // VisitStack to HistoryStack as we do the DFS for bad field.
9206   SmallVector<const FieldDecl *, 4> HistoryStack;
9207   HistoryStack.push_back(nullptr);
9208 
9209   // At this point we already handled everything except of a RecordType or
9210   // an ArrayType of a RecordType.
9211   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9212   const RecordType *RecTy =
9213       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9214   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9215 
9216   VisitStack.push_back(RecTy->getDecl());
9217   assert(VisitStack.back() && "First decl null?");
9218 
9219   do {
9220     const Decl *Next = VisitStack.pop_back_val();
9221     if (!Next) {
9222       assert(!HistoryStack.empty());
9223       // Found a marker, we have gone up a level
9224       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9225         ValidTypes.insert(Hist->getType().getTypePtr());
9226 
9227       continue;
9228     }
9229 
9230     // Adds everything except the original parameter declaration (which is not a
9231     // field itself) to the history stack.
9232     const RecordDecl *RD;
9233     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9234       HistoryStack.push_back(Field);
9235 
9236       QualType FieldTy = Field->getType();
9237       // Other field types (known to be valid or invalid) are handled while we
9238       // walk around RecordDecl::fields().
9239       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9240              "Unexpected type.");
9241       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9242 
9243       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9244     } else {
9245       RD = cast<RecordDecl>(Next);
9246     }
9247 
9248     // Add a null marker so we know when we've gone back up a level
9249     VisitStack.push_back(nullptr);
9250 
9251     for (const auto *FD : RD->fields()) {
9252       QualType QT = FD->getType();
9253 
9254       if (ValidTypes.count(QT.getTypePtr()))
9255         continue;
9256 
9257       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9258       if (ParamType == ValidKernelParam)
9259         continue;
9260 
9261       if (ParamType == RecordKernelParam) {
9262         VisitStack.push_back(FD);
9263         continue;
9264       }
9265 
9266       // OpenCL v1.2 s6.9.p:
9267       // Arguments to kernel functions that are declared to be a struct or union
9268       // do not allow OpenCL objects to be passed as elements of the struct or
9269       // union.
9270       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9271           ParamType == InvalidAddrSpacePtrKernelParam) {
9272         S.Diag(Param->getLocation(),
9273                diag::err_record_with_pointers_kernel_param)
9274           << PT->isUnionType()
9275           << PT;
9276       } else {
9277         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9278       }
9279 
9280       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9281           << OrigRecDecl->getDeclName();
9282 
9283       // We have an error, now let's go back up through history and show where
9284       // the offending field came from
9285       for (ArrayRef<const FieldDecl *>::const_iterator
9286                I = HistoryStack.begin() + 1,
9287                E = HistoryStack.end();
9288            I != E; ++I) {
9289         const FieldDecl *OuterField = *I;
9290         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9291           << OuterField->getType();
9292       }
9293 
9294       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9295         << QT->isPointerType()
9296         << QT;
9297       D.setInvalidType();
9298       return;
9299     }
9300   } while (!VisitStack.empty());
9301 }
9302 
9303 /// Find the DeclContext in which a tag is implicitly declared if we see an
9304 /// elaborated type specifier in the specified context, and lookup finds
9305 /// nothing.
9306 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9307   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9308     DC = DC->getParent();
9309   return DC;
9310 }
9311 
9312 /// Find the Scope in which a tag is implicitly declared if we see an
9313 /// elaborated type specifier in the specified context, and lookup finds
9314 /// nothing.
9315 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9316   while (S->isClassScope() ||
9317          (LangOpts.CPlusPlus &&
9318           S->isFunctionPrototypeScope()) ||
9319          ((S->getFlags() & Scope::DeclScope) == 0) ||
9320          (S->getEntity() && S->getEntity()->isTransparentContext()))
9321     S = S->getParent();
9322   return S;
9323 }
9324 
9325 /// Determine whether a declaration matches a known function in namespace std.
9326 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9327                          unsigned BuiltinID) {
9328   switch (BuiltinID) {
9329   case Builtin::BI__GetExceptionInfo:
9330     // No type checking whatsoever.
9331     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9332 
9333   case Builtin::BIaddressof:
9334   case Builtin::BI__addressof:
9335   case Builtin::BIforward:
9336   case Builtin::BImove:
9337   case Builtin::BImove_if_noexcept:
9338   case Builtin::BIas_const: {
9339     // Ensure that we don't treat the algorithm
9340     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9341     // as the builtin std::move.
9342     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9343     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9344   }
9345 
9346   default:
9347     return false;
9348   }
9349 }
9350 
9351 NamedDecl*
9352 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9353                               TypeSourceInfo *TInfo, LookupResult &Previous,
9354                               MultiTemplateParamsArg TemplateParamListsRef,
9355                               bool &AddToScope) {
9356   QualType R = TInfo->getType();
9357 
9358   assert(R->isFunctionType());
9359   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9360     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9361 
9362   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9363   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9364   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9365     if (!TemplateParamLists.empty() &&
9366         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9367       TemplateParamLists.back() = Invented;
9368     else
9369       TemplateParamLists.push_back(Invented);
9370   }
9371 
9372   // TODO: consider using NameInfo for diagnostic.
9373   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9374   DeclarationName Name = NameInfo.getName();
9375   StorageClass SC = getFunctionStorageClass(*this, D);
9376 
9377   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9378     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9379          diag::err_invalid_thread)
9380       << DeclSpec::getSpecifierName(TSCS);
9381 
9382   if (D.isFirstDeclarationOfMember())
9383     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9384                            D.getIdentifierLoc());
9385 
9386   bool isFriend = false;
9387   FunctionTemplateDecl *FunctionTemplate = nullptr;
9388   bool isMemberSpecialization = false;
9389   bool isFunctionTemplateSpecialization = false;
9390 
9391   bool isDependentClassScopeExplicitSpecialization = false;
9392   bool HasExplicitTemplateArgs = false;
9393   TemplateArgumentListInfo TemplateArgs;
9394 
9395   bool isVirtualOkay = false;
9396 
9397   DeclContext *OriginalDC = DC;
9398   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9399 
9400   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9401                                               isVirtualOkay);
9402   if (!NewFD) return nullptr;
9403 
9404   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9405     NewFD->setTopLevelDeclInObjCContainer();
9406 
9407   // Set the lexical context. If this is a function-scope declaration, or has a
9408   // C++ scope specifier, or is the object of a friend declaration, the lexical
9409   // context will be different from the semantic context.
9410   NewFD->setLexicalDeclContext(CurContext);
9411 
9412   if (IsLocalExternDecl)
9413     NewFD->setLocalExternDecl();
9414 
9415   if (getLangOpts().CPlusPlus) {
9416     bool isInline = D.getDeclSpec().isInlineSpecified();
9417     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9418     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9419     isFriend = D.getDeclSpec().isFriendSpecified();
9420     if (isFriend && !isInline && D.isFunctionDefinition()) {
9421       // C++ [class.friend]p5
9422       //   A function can be defined in a friend declaration of a
9423       //   class . . . . Such a function is implicitly inline.
9424       NewFD->setImplicitlyInline();
9425     }
9426 
9427     // If this is a method defined in an __interface, and is not a constructor
9428     // or an overloaded operator, then set the pure flag (isVirtual will already
9429     // return true).
9430     if (const CXXRecordDecl *Parent =
9431           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9432       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9433         NewFD->setPure(true);
9434 
9435       // C++ [class.union]p2
9436       //   A union can have member functions, but not virtual functions.
9437       if (isVirtual && Parent->isUnion()) {
9438         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9439         NewFD->setInvalidDecl();
9440       }
9441       if ((Parent->isClass() || Parent->isStruct()) &&
9442           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9443           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9444           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9445         if (auto *Def = Parent->getDefinition())
9446           Def->setInitMethod(true);
9447       }
9448     }
9449 
9450     SetNestedNameSpecifier(*this, NewFD, D);
9451     isMemberSpecialization = false;
9452     isFunctionTemplateSpecialization = false;
9453     if (D.isInvalidType())
9454       NewFD->setInvalidDecl();
9455 
9456     // Match up the template parameter lists with the scope specifier, then
9457     // determine whether we have a template or a template specialization.
9458     bool Invalid = false;
9459     TemplateParameterList *TemplateParams =
9460         MatchTemplateParametersToScopeSpecifier(
9461             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9462             D.getCXXScopeSpec(),
9463             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9464                 ? D.getName().TemplateId
9465                 : nullptr,
9466             TemplateParamLists, isFriend, isMemberSpecialization,
9467             Invalid);
9468     if (TemplateParams) {
9469       // Check that we can declare a template here.
9470       if (CheckTemplateDeclScope(S, TemplateParams))
9471         NewFD->setInvalidDecl();
9472 
9473       if (TemplateParams->size() > 0) {
9474         // This is a function template
9475 
9476         // A destructor cannot be a template.
9477         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9478           Diag(NewFD->getLocation(), diag::err_destructor_template);
9479           NewFD->setInvalidDecl();
9480         }
9481 
9482         // If we're adding a template to a dependent context, we may need to
9483         // rebuilding some of the types used within the template parameter list,
9484         // now that we know what the current instantiation is.
9485         if (DC->isDependentContext()) {
9486           ContextRAII SavedContext(*this, DC);
9487           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9488             Invalid = true;
9489         }
9490 
9491         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9492                                                         NewFD->getLocation(),
9493                                                         Name, TemplateParams,
9494                                                         NewFD);
9495         FunctionTemplate->setLexicalDeclContext(CurContext);
9496         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9497 
9498         // For source fidelity, store the other template param lists.
9499         if (TemplateParamLists.size() > 1) {
9500           NewFD->setTemplateParameterListsInfo(Context,
9501               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9502                   .drop_back(1));
9503         }
9504       } else {
9505         // This is a function template specialization.
9506         isFunctionTemplateSpecialization = true;
9507         // For source fidelity, store all the template param lists.
9508         if (TemplateParamLists.size() > 0)
9509           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9510 
9511         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9512         if (isFriend) {
9513           // We want to remove the "template<>", found here.
9514           SourceRange RemoveRange = TemplateParams->getSourceRange();
9515 
9516           // If we remove the template<> and the name is not a
9517           // template-id, we're actually silently creating a problem:
9518           // the friend declaration will refer to an untemplated decl,
9519           // and clearly the user wants a template specialization.  So
9520           // we need to insert '<>' after the name.
9521           SourceLocation InsertLoc;
9522           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9523             InsertLoc = D.getName().getSourceRange().getEnd();
9524             InsertLoc = getLocForEndOfToken(InsertLoc);
9525           }
9526 
9527           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9528             << Name << RemoveRange
9529             << FixItHint::CreateRemoval(RemoveRange)
9530             << FixItHint::CreateInsertion(InsertLoc, "<>");
9531           Invalid = true;
9532         }
9533       }
9534     } else {
9535       // Check that we can declare a template here.
9536       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9537           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9538         NewFD->setInvalidDecl();
9539 
9540       // All template param lists were matched against the scope specifier:
9541       // this is NOT (an explicit specialization of) a template.
9542       if (TemplateParamLists.size() > 0)
9543         // For source fidelity, store all the template param lists.
9544         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9545     }
9546 
9547     if (Invalid) {
9548       NewFD->setInvalidDecl();
9549       if (FunctionTemplate)
9550         FunctionTemplate->setInvalidDecl();
9551     }
9552 
9553     // C++ [dcl.fct.spec]p5:
9554     //   The virtual specifier shall only be used in declarations of
9555     //   nonstatic class member functions that appear within a
9556     //   member-specification of a class declaration; see 10.3.
9557     //
9558     if (isVirtual && !NewFD->isInvalidDecl()) {
9559       if (!isVirtualOkay) {
9560         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9561              diag::err_virtual_non_function);
9562       } else if (!CurContext->isRecord()) {
9563         // 'virtual' was specified outside of the class.
9564         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9565              diag::err_virtual_out_of_class)
9566           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9567       } else if (NewFD->getDescribedFunctionTemplate()) {
9568         // C++ [temp.mem]p3:
9569         //  A member function template shall not be virtual.
9570         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9571              diag::err_virtual_member_function_template)
9572           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9573       } else {
9574         // Okay: Add virtual to the method.
9575         NewFD->setVirtualAsWritten(true);
9576       }
9577 
9578       if (getLangOpts().CPlusPlus14 &&
9579           NewFD->getReturnType()->isUndeducedType())
9580         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9581     }
9582 
9583     if (getLangOpts().CPlusPlus14 &&
9584         (NewFD->isDependentContext() ||
9585          (isFriend && CurContext->isDependentContext())) &&
9586         NewFD->getReturnType()->isUndeducedType()) {
9587       // If the function template is referenced directly (for instance, as a
9588       // member of the current instantiation), pretend it has a dependent type.
9589       // This is not really justified by the standard, but is the only sane
9590       // thing to do.
9591       // FIXME: For a friend function, we have not marked the function as being
9592       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9593       const FunctionProtoType *FPT =
9594           NewFD->getType()->castAs<FunctionProtoType>();
9595       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9596       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9597                                              FPT->getExtProtoInfo()));
9598     }
9599 
9600     // C++ [dcl.fct.spec]p3:
9601     //  The inline specifier shall not appear on a block scope function
9602     //  declaration.
9603     if (isInline && !NewFD->isInvalidDecl()) {
9604       if (CurContext->isFunctionOrMethod()) {
9605         // 'inline' is not allowed on block scope function declaration.
9606         Diag(D.getDeclSpec().getInlineSpecLoc(),
9607              diag::err_inline_declaration_block_scope) << Name
9608           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9609       }
9610     }
9611 
9612     // C++ [dcl.fct.spec]p6:
9613     //  The explicit specifier shall be used only in the declaration of a
9614     //  constructor or conversion function within its class definition;
9615     //  see 12.3.1 and 12.3.2.
9616     if (hasExplicit && !NewFD->isInvalidDecl() &&
9617         !isa<CXXDeductionGuideDecl>(NewFD)) {
9618       if (!CurContext->isRecord()) {
9619         // 'explicit' was specified outside of the class.
9620         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9621              diag::err_explicit_out_of_class)
9622             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9623       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9624                  !isa<CXXConversionDecl>(NewFD)) {
9625         // 'explicit' was specified on a function that wasn't a constructor
9626         // or conversion function.
9627         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9628              diag::err_explicit_non_ctor_or_conv_function)
9629             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9630       }
9631     }
9632 
9633     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9634     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9635       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9636       // are implicitly inline.
9637       NewFD->setImplicitlyInline();
9638 
9639       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9640       // be either constructors or to return a literal type. Therefore,
9641       // destructors cannot be declared constexpr.
9642       if (isa<CXXDestructorDecl>(NewFD) &&
9643           (!getLangOpts().CPlusPlus20 ||
9644            ConstexprKind == ConstexprSpecKind::Consteval)) {
9645         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9646             << static_cast<int>(ConstexprKind);
9647         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9648                                     ? ConstexprSpecKind::Unspecified
9649                                     : ConstexprSpecKind::Constexpr);
9650       }
9651       // C++20 [dcl.constexpr]p2: An allocation function, or a
9652       // deallocation function shall not be declared with the consteval
9653       // specifier.
9654       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9655           (NewFD->getOverloadedOperator() == OO_New ||
9656            NewFD->getOverloadedOperator() == OO_Array_New ||
9657            NewFD->getOverloadedOperator() == OO_Delete ||
9658            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9659         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9660              diag::err_invalid_consteval_decl_kind)
9661             << NewFD;
9662         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9663       }
9664     }
9665 
9666     // If __module_private__ was specified, mark the function accordingly.
9667     if (D.getDeclSpec().isModulePrivateSpecified()) {
9668       if (isFunctionTemplateSpecialization) {
9669         SourceLocation ModulePrivateLoc
9670           = D.getDeclSpec().getModulePrivateSpecLoc();
9671         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9672           << 0
9673           << FixItHint::CreateRemoval(ModulePrivateLoc);
9674       } else {
9675         NewFD->setModulePrivate();
9676         if (FunctionTemplate)
9677           FunctionTemplate->setModulePrivate();
9678       }
9679     }
9680 
9681     if (isFriend) {
9682       if (FunctionTemplate) {
9683         FunctionTemplate->setObjectOfFriendDecl();
9684         FunctionTemplate->setAccess(AS_public);
9685       }
9686       NewFD->setObjectOfFriendDecl();
9687       NewFD->setAccess(AS_public);
9688     }
9689 
9690     // If a function is defined as defaulted or deleted, mark it as such now.
9691     // We'll do the relevant checks on defaulted / deleted functions later.
9692     switch (D.getFunctionDefinitionKind()) {
9693     case FunctionDefinitionKind::Declaration:
9694     case FunctionDefinitionKind::Definition:
9695       break;
9696 
9697     case FunctionDefinitionKind::Defaulted:
9698       NewFD->setDefaulted();
9699       break;
9700 
9701     case FunctionDefinitionKind::Deleted:
9702       NewFD->setDeletedAsWritten();
9703       break;
9704     }
9705 
9706     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9707         D.isFunctionDefinition()) {
9708       // C++ [class.mfct]p2:
9709       //   A member function may be defined (8.4) in its class definition, in
9710       //   which case it is an inline member function (7.1.2)
9711       NewFD->setImplicitlyInline();
9712     }
9713 
9714     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9715         !CurContext->isRecord()) {
9716       // C++ [class.static]p1:
9717       //   A data or function member of a class may be declared static
9718       //   in a class definition, in which case it is a static member of
9719       //   the class.
9720 
9721       // Complain about the 'static' specifier if it's on an out-of-line
9722       // member function definition.
9723 
9724       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9725       // member function template declaration and class member template
9726       // declaration (MSVC versions before 2015), warn about this.
9727       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9728            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9729              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9730            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9731            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9732         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9733     }
9734 
9735     // C++11 [except.spec]p15:
9736     //   A deallocation function with no exception-specification is treated
9737     //   as if it were specified with noexcept(true).
9738     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9739     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9740          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9741         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9742       NewFD->setType(Context.getFunctionType(
9743           FPT->getReturnType(), FPT->getParamTypes(),
9744           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9745   }
9746 
9747   // Filter out previous declarations that don't match the scope.
9748   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9749                        D.getCXXScopeSpec().isNotEmpty() ||
9750                        isMemberSpecialization ||
9751                        isFunctionTemplateSpecialization);
9752 
9753   // Handle GNU asm-label extension (encoded as an attribute).
9754   if (Expr *E = (Expr*) D.getAsmLabel()) {
9755     // The parser guarantees this is a string.
9756     StringLiteral *SE = cast<StringLiteral>(E);
9757     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9758                                         /*IsLiteralLabel=*/true,
9759                                         SE->getStrTokenLoc(0)));
9760   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9761     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9762       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9763     if (I != ExtnameUndeclaredIdentifiers.end()) {
9764       if (isDeclExternC(NewFD)) {
9765         NewFD->addAttr(I->second);
9766         ExtnameUndeclaredIdentifiers.erase(I);
9767       } else
9768         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9769             << /*Variable*/0 << NewFD;
9770     }
9771   }
9772 
9773   // Copy the parameter declarations from the declarator D to the function
9774   // declaration NewFD, if they are available.  First scavenge them into Params.
9775   SmallVector<ParmVarDecl*, 16> Params;
9776   unsigned FTIIdx;
9777   if (D.isFunctionDeclarator(FTIIdx)) {
9778     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9779 
9780     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9781     // function that takes no arguments, not a function that takes a
9782     // single void argument.
9783     // We let through "const void" here because Sema::GetTypeForDeclarator
9784     // already checks for that case.
9785     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9786       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9787         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9788         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9789         Param->setDeclContext(NewFD);
9790         Params.push_back(Param);
9791 
9792         if (Param->isInvalidDecl())
9793           NewFD->setInvalidDecl();
9794       }
9795     }
9796 
9797     if (!getLangOpts().CPlusPlus) {
9798       // In C, find all the tag declarations from the prototype and move them
9799       // into the function DeclContext. Remove them from the surrounding tag
9800       // injection context of the function, which is typically but not always
9801       // the TU.
9802       DeclContext *PrototypeTagContext =
9803           getTagInjectionContext(NewFD->getLexicalDeclContext());
9804       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9805         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9806 
9807         // We don't want to reparent enumerators. Look at their parent enum
9808         // instead.
9809         if (!TD) {
9810           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9811             TD = cast<EnumDecl>(ECD->getDeclContext());
9812         }
9813         if (!TD)
9814           continue;
9815         DeclContext *TagDC = TD->getLexicalDeclContext();
9816         if (!TagDC->containsDecl(TD))
9817           continue;
9818         TagDC->removeDecl(TD);
9819         TD->setDeclContext(NewFD);
9820         NewFD->addDecl(TD);
9821 
9822         // Preserve the lexical DeclContext if it is not the surrounding tag
9823         // injection context of the FD. In this example, the semantic context of
9824         // E will be f and the lexical context will be S, while both the
9825         // semantic and lexical contexts of S will be f:
9826         //   void f(struct S { enum E { a } f; } s);
9827         if (TagDC != PrototypeTagContext)
9828           TD->setLexicalDeclContext(TagDC);
9829       }
9830     }
9831   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9832     // When we're declaring a function with a typedef, typeof, etc as in the
9833     // following example, we'll need to synthesize (unnamed)
9834     // parameters for use in the declaration.
9835     //
9836     // @code
9837     // typedef void fn(int);
9838     // fn f;
9839     // @endcode
9840 
9841     // Synthesize a parameter for each argument type.
9842     for (const auto &AI : FT->param_types()) {
9843       ParmVarDecl *Param =
9844           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9845       Param->setScopeInfo(0, Params.size());
9846       Params.push_back(Param);
9847     }
9848   } else {
9849     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9850            "Should not need args for typedef of non-prototype fn");
9851   }
9852 
9853   // Finally, we know we have the right number of parameters, install them.
9854   NewFD->setParams(Params);
9855 
9856   if (D.getDeclSpec().isNoreturnSpecified())
9857     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9858                                            D.getDeclSpec().getNoreturnSpecLoc(),
9859                                            AttributeCommonInfo::AS_Keyword));
9860 
9861   // Functions returning a variably modified type violate C99 6.7.5.2p2
9862   // because all functions have linkage.
9863   if (!NewFD->isInvalidDecl() &&
9864       NewFD->getReturnType()->isVariablyModifiedType()) {
9865     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9866     NewFD->setInvalidDecl();
9867   }
9868 
9869   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9870   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9871       !NewFD->hasAttr<SectionAttr>())
9872     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9873         Context, PragmaClangTextSection.SectionName,
9874         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9875 
9876   // Apply an implicit SectionAttr if #pragma code_seg is active.
9877   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9878       !NewFD->hasAttr<SectionAttr>()) {
9879     NewFD->addAttr(SectionAttr::CreateImplicit(
9880         Context, CodeSegStack.CurrentValue->getString(),
9881         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9882         SectionAttr::Declspec_allocate));
9883     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9884                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9885                          ASTContext::PSF_Read,
9886                      NewFD))
9887       NewFD->dropAttr<SectionAttr>();
9888   }
9889 
9890   // Apply an implicit CodeSegAttr from class declspec or
9891   // apply an implicit SectionAttr from #pragma code_seg if active.
9892   if (!NewFD->hasAttr<CodeSegAttr>()) {
9893     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9894                                                                  D.isFunctionDefinition())) {
9895       NewFD->addAttr(SAttr);
9896     }
9897   }
9898 
9899   // Handle attributes.
9900   ProcessDeclAttributes(S, NewFD, D);
9901 
9902   if (getLangOpts().OpenCL) {
9903     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9904     // type declaration will generate a compilation error.
9905     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9906     if (AddressSpace != LangAS::Default) {
9907       Diag(NewFD->getLocation(),
9908            diag::err_opencl_return_value_with_address_space);
9909       NewFD->setInvalidDecl();
9910     }
9911   }
9912 
9913   if (!getLangOpts().CPlusPlus) {
9914     // Perform semantic checking on the function declaration.
9915     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9916       CheckMain(NewFD, D.getDeclSpec());
9917 
9918     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9919       CheckMSVCRTEntryPoint(NewFD);
9920 
9921     if (!NewFD->isInvalidDecl())
9922       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9923                                                   isMemberSpecialization,
9924                                                   D.isFunctionDefinition()));
9925     else if (!Previous.empty())
9926       // Recover gracefully from an invalid redeclaration.
9927       D.setRedeclaration(true);
9928     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9929             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9930            "previous declaration set still overloaded");
9931 
9932     // Diagnose no-prototype function declarations with calling conventions that
9933     // don't support variadic calls. Only do this in C and do it after merging
9934     // possibly prototyped redeclarations.
9935     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9936     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9937       CallingConv CC = FT->getExtInfo().getCC();
9938       if (!supportsVariadicCall(CC)) {
9939         // Windows system headers sometimes accidentally use stdcall without
9940         // (void) parameters, so we relax this to a warning.
9941         int DiagID =
9942             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9943         Diag(NewFD->getLocation(), DiagID)
9944             << FunctionType::getNameForCallConv(CC);
9945       }
9946     }
9947 
9948    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9949        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9950      checkNonTrivialCUnion(NewFD->getReturnType(),
9951                            NewFD->getReturnTypeSourceRange().getBegin(),
9952                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9953   } else {
9954     // C++11 [replacement.functions]p3:
9955     //  The program's definitions shall not be specified as inline.
9956     //
9957     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9958     //
9959     // Suppress the diagnostic if the function is __attribute__((used)), since
9960     // that forces an external definition to be emitted.
9961     if (D.getDeclSpec().isInlineSpecified() &&
9962         NewFD->isReplaceableGlobalAllocationFunction() &&
9963         !NewFD->hasAttr<UsedAttr>())
9964       Diag(D.getDeclSpec().getInlineSpecLoc(),
9965            diag::ext_operator_new_delete_declared_inline)
9966         << NewFD->getDeclName();
9967 
9968     // If the declarator is a template-id, translate the parser's template
9969     // argument list into our AST format.
9970     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9971       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9972       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9973       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9974       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9975                                          TemplateId->NumArgs);
9976       translateTemplateArguments(TemplateArgsPtr,
9977                                  TemplateArgs);
9978 
9979       HasExplicitTemplateArgs = true;
9980 
9981       if (NewFD->isInvalidDecl()) {
9982         HasExplicitTemplateArgs = false;
9983       } else if (FunctionTemplate) {
9984         // Function template with explicit template arguments.
9985         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9986           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9987 
9988         HasExplicitTemplateArgs = false;
9989       } else {
9990         assert((isFunctionTemplateSpecialization ||
9991                 D.getDeclSpec().isFriendSpecified()) &&
9992                "should have a 'template<>' for this decl");
9993         // "friend void foo<>(int);" is an implicit specialization decl.
9994         isFunctionTemplateSpecialization = true;
9995       }
9996     } else if (isFriend && isFunctionTemplateSpecialization) {
9997       // This combination is only possible in a recovery case;  the user
9998       // wrote something like:
9999       //   template <> friend void foo(int);
10000       // which we're recovering from as if the user had written:
10001       //   friend void foo<>(int);
10002       // Go ahead and fake up a template id.
10003       HasExplicitTemplateArgs = true;
10004       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10005       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10006     }
10007 
10008     // We do not add HD attributes to specializations here because
10009     // they may have different constexpr-ness compared to their
10010     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10011     // may end up with different effective targets. Instead, a
10012     // specialization inherits its target attributes from its template
10013     // in the CheckFunctionTemplateSpecialization() call below.
10014     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10015       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10016 
10017     // If it's a friend (and only if it's a friend), it's possible
10018     // that either the specialized function type or the specialized
10019     // template is dependent, and therefore matching will fail.  In
10020     // this case, don't check the specialization yet.
10021     if (isFunctionTemplateSpecialization && isFriend &&
10022         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10023          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10024              TemplateArgs.arguments()))) {
10025       assert(HasExplicitTemplateArgs &&
10026              "friend function specialization without template args");
10027       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10028                                                        Previous))
10029         NewFD->setInvalidDecl();
10030     } else if (isFunctionTemplateSpecialization) {
10031       if (CurContext->isDependentContext() && CurContext->isRecord()
10032           && !isFriend) {
10033         isDependentClassScopeExplicitSpecialization = true;
10034       } else if (!NewFD->isInvalidDecl() &&
10035                  CheckFunctionTemplateSpecialization(
10036                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10037                      Previous))
10038         NewFD->setInvalidDecl();
10039 
10040       // C++ [dcl.stc]p1:
10041       //   A storage-class-specifier shall not be specified in an explicit
10042       //   specialization (14.7.3)
10043       FunctionTemplateSpecializationInfo *Info =
10044           NewFD->getTemplateSpecializationInfo();
10045       if (Info && SC != SC_None) {
10046         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10047           Diag(NewFD->getLocation(),
10048                diag::err_explicit_specialization_inconsistent_storage_class)
10049             << SC
10050             << FixItHint::CreateRemoval(
10051                                       D.getDeclSpec().getStorageClassSpecLoc());
10052 
10053         else
10054           Diag(NewFD->getLocation(),
10055                diag::ext_explicit_specialization_storage_class)
10056             << FixItHint::CreateRemoval(
10057                                       D.getDeclSpec().getStorageClassSpecLoc());
10058       }
10059     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10060       if (CheckMemberSpecialization(NewFD, Previous))
10061           NewFD->setInvalidDecl();
10062     }
10063 
10064     // Perform semantic checking on the function declaration.
10065     if (!isDependentClassScopeExplicitSpecialization) {
10066       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10067         CheckMain(NewFD, D.getDeclSpec());
10068 
10069       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10070         CheckMSVCRTEntryPoint(NewFD);
10071 
10072       if (!NewFD->isInvalidDecl())
10073         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10074                                                     isMemberSpecialization,
10075                                                     D.isFunctionDefinition()));
10076       else if (!Previous.empty())
10077         // Recover gracefully from an invalid redeclaration.
10078         D.setRedeclaration(true);
10079     }
10080 
10081     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10082             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10083            "previous declaration set still overloaded");
10084 
10085     NamedDecl *PrincipalDecl = (FunctionTemplate
10086                                 ? cast<NamedDecl>(FunctionTemplate)
10087                                 : NewFD);
10088 
10089     if (isFriend && NewFD->getPreviousDecl()) {
10090       AccessSpecifier Access = AS_public;
10091       if (!NewFD->isInvalidDecl())
10092         Access = NewFD->getPreviousDecl()->getAccess();
10093 
10094       NewFD->setAccess(Access);
10095       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10096     }
10097 
10098     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10099         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10100       PrincipalDecl->setNonMemberOperator();
10101 
10102     // If we have a function template, check the template parameter
10103     // list. This will check and merge default template arguments.
10104     if (FunctionTemplate) {
10105       FunctionTemplateDecl *PrevTemplate =
10106                                      FunctionTemplate->getPreviousDecl();
10107       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10108                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10109                                     : nullptr,
10110                             D.getDeclSpec().isFriendSpecified()
10111                               ? (D.isFunctionDefinition()
10112                                    ? TPC_FriendFunctionTemplateDefinition
10113                                    : TPC_FriendFunctionTemplate)
10114                               : (D.getCXXScopeSpec().isSet() &&
10115                                  DC && DC->isRecord() &&
10116                                  DC->isDependentContext())
10117                                   ? TPC_ClassTemplateMember
10118                                   : TPC_FunctionTemplate);
10119     }
10120 
10121     if (NewFD->isInvalidDecl()) {
10122       // Ignore all the rest of this.
10123     } else if (!D.isRedeclaration()) {
10124       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10125                                        AddToScope };
10126       // Fake up an access specifier if it's supposed to be a class member.
10127       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10128         NewFD->setAccess(AS_public);
10129 
10130       // Qualified decls generally require a previous declaration.
10131       if (D.getCXXScopeSpec().isSet()) {
10132         // ...with the major exception of templated-scope or
10133         // dependent-scope friend declarations.
10134 
10135         // TODO: we currently also suppress this check in dependent
10136         // contexts because (1) the parameter depth will be off when
10137         // matching friend templates and (2) we might actually be
10138         // selecting a friend based on a dependent factor.  But there
10139         // are situations where these conditions don't apply and we
10140         // can actually do this check immediately.
10141         //
10142         // Unless the scope is dependent, it's always an error if qualified
10143         // redeclaration lookup found nothing at all. Diagnose that now;
10144         // nothing will diagnose that error later.
10145         if (isFriend &&
10146             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10147              (!Previous.empty() && CurContext->isDependentContext()))) {
10148           // ignore these
10149         } else if (NewFD->isCPUDispatchMultiVersion() ||
10150                    NewFD->isCPUSpecificMultiVersion()) {
10151           // ignore this, we allow the redeclaration behavior here to create new
10152           // versions of the function.
10153         } else {
10154           // The user tried to provide an out-of-line definition for a
10155           // function that is a member of a class or namespace, but there
10156           // was no such member function declared (C++ [class.mfct]p2,
10157           // C++ [namespace.memdef]p2). For example:
10158           //
10159           // class X {
10160           //   void f() const;
10161           // };
10162           //
10163           // void X::f() { } // ill-formed
10164           //
10165           // Complain about this problem, and attempt to suggest close
10166           // matches (e.g., those that differ only in cv-qualifiers and
10167           // whether the parameter types are references).
10168 
10169           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10170                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10171             AddToScope = ExtraArgs.AddToScope;
10172             return Result;
10173           }
10174         }
10175 
10176         // Unqualified local friend declarations are required to resolve
10177         // to something.
10178       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10179         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10180                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10181           AddToScope = ExtraArgs.AddToScope;
10182           return Result;
10183         }
10184       }
10185     } else if (!D.isFunctionDefinition() &&
10186                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10187                !isFriend && !isFunctionTemplateSpecialization &&
10188                !isMemberSpecialization) {
10189       // An out-of-line member function declaration must also be a
10190       // definition (C++ [class.mfct]p2).
10191       // Note that this is not the case for explicit specializations of
10192       // function templates or member functions of class templates, per
10193       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10194       // extension for compatibility with old SWIG code which likes to
10195       // generate them.
10196       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10197         << D.getCXXScopeSpec().getRange();
10198     }
10199   }
10200 
10201   // If this is the first declaration of a library builtin function, add
10202   // attributes as appropriate.
10203   if (!D.isRedeclaration()) {
10204     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10205       if (unsigned BuiltinID = II->getBuiltinID()) {
10206         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10207         if (!InStdNamespace &&
10208             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10209           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10210             // Validate the type matches unless this builtin is specified as
10211             // matching regardless of its declared type.
10212             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10213               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10214             } else {
10215               ASTContext::GetBuiltinTypeError Error;
10216               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10217               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10218 
10219               if (!Error && !BuiltinType.isNull() &&
10220                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10221                       NewFD->getType(), BuiltinType))
10222                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10223             }
10224           }
10225         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10226                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10227           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10228         }
10229       }
10230     }
10231   }
10232 
10233   ProcessPragmaWeak(S, NewFD);
10234   checkAttributesAfterMerging(*this, *NewFD);
10235 
10236   AddKnownFunctionAttributes(NewFD);
10237 
10238   if (NewFD->hasAttr<OverloadableAttr>() &&
10239       !NewFD->getType()->getAs<FunctionProtoType>()) {
10240     Diag(NewFD->getLocation(),
10241          diag::err_attribute_overloadable_no_prototype)
10242       << NewFD;
10243 
10244     // Turn this into a variadic function with no parameters.
10245     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10246     FunctionProtoType::ExtProtoInfo EPI(
10247         Context.getDefaultCallingConvention(true, false));
10248     EPI.Variadic = true;
10249     EPI.ExtInfo = FT->getExtInfo();
10250 
10251     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10252     NewFD->setType(R);
10253   }
10254 
10255   // If there's a #pragma GCC visibility in scope, and this isn't a class
10256   // member, set the visibility of this function.
10257   if (!DC->isRecord() && NewFD->isExternallyVisible())
10258     AddPushedVisibilityAttribute(NewFD);
10259 
10260   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10261   // marking the function.
10262   AddCFAuditedAttribute(NewFD);
10263 
10264   // If this is a function definition, check if we have to apply any
10265   // attributes (i.e. optnone and no_builtin) due to a pragma.
10266   if (D.isFunctionDefinition()) {
10267     AddRangeBasedOptnone(NewFD);
10268     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10269     AddSectionMSAllocText(NewFD);
10270     ModifyFnAttributesMSPragmaOptimize(NewFD);
10271   }
10272 
10273   // If this is the first declaration of an extern C variable, update
10274   // the map of such variables.
10275   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10276       isIncompleteDeclExternC(*this, NewFD))
10277     RegisterLocallyScopedExternCDecl(NewFD, S);
10278 
10279   // Set this FunctionDecl's range up to the right paren.
10280   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10281 
10282   if (D.isRedeclaration() && !Previous.empty()) {
10283     NamedDecl *Prev = Previous.getRepresentativeDecl();
10284     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10285                                    isMemberSpecialization ||
10286                                        isFunctionTemplateSpecialization,
10287                                    D.isFunctionDefinition());
10288   }
10289 
10290   if (getLangOpts().CUDA) {
10291     IdentifierInfo *II = NewFD->getIdentifier();
10292     if (II && II->isStr(getCudaConfigureFuncName()) &&
10293         !NewFD->isInvalidDecl() &&
10294         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10295       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10296         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10297             << getCudaConfigureFuncName();
10298       Context.setcudaConfigureCallDecl(NewFD);
10299     }
10300 
10301     // Variadic functions, other than a *declaration* of printf, are not allowed
10302     // in device-side CUDA code, unless someone passed
10303     // -fcuda-allow-variadic-functions.
10304     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10305         (NewFD->hasAttr<CUDADeviceAttr>() ||
10306          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10307         !(II && II->isStr("printf") && NewFD->isExternC() &&
10308           !D.isFunctionDefinition())) {
10309       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10310     }
10311   }
10312 
10313   MarkUnusedFileScopedDecl(NewFD);
10314 
10315 
10316 
10317   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10318     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10319     if (SC == SC_Static) {
10320       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10321       D.setInvalidType();
10322     }
10323 
10324     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10325     if (!NewFD->getReturnType()->isVoidType()) {
10326       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10327       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10328           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10329                                 : FixItHint());
10330       D.setInvalidType();
10331     }
10332 
10333     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10334     for (auto Param : NewFD->parameters())
10335       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10336 
10337     if (getLangOpts().OpenCLCPlusPlus) {
10338       if (DC->isRecord()) {
10339         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10340         D.setInvalidType();
10341       }
10342       if (FunctionTemplate) {
10343         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10344         D.setInvalidType();
10345       }
10346     }
10347   }
10348 
10349   if (getLangOpts().CPlusPlus) {
10350     if (FunctionTemplate) {
10351       if (NewFD->isInvalidDecl())
10352         FunctionTemplate->setInvalidDecl();
10353       return FunctionTemplate;
10354     }
10355 
10356     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10357       CompleteMemberSpecialization(NewFD, Previous);
10358   }
10359 
10360   for (const ParmVarDecl *Param : NewFD->parameters()) {
10361     QualType PT = Param->getType();
10362 
10363     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10364     // types.
10365     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10366       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10367         QualType ElemTy = PipeTy->getElementType();
10368           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10369             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10370             D.setInvalidType();
10371           }
10372       }
10373     }
10374   }
10375 
10376   // Here we have an function template explicit specialization at class scope.
10377   // The actual specialization will be postponed to template instatiation
10378   // time via the ClassScopeFunctionSpecializationDecl node.
10379   if (isDependentClassScopeExplicitSpecialization) {
10380     ClassScopeFunctionSpecializationDecl *NewSpec =
10381                          ClassScopeFunctionSpecializationDecl::Create(
10382                                 Context, CurContext, NewFD->getLocation(),
10383                                 cast<CXXMethodDecl>(NewFD),
10384                                 HasExplicitTemplateArgs, TemplateArgs);
10385     CurContext->addDecl(NewSpec);
10386     AddToScope = false;
10387   }
10388 
10389   // Diagnose availability attributes. Availability cannot be used on functions
10390   // that are run during load/unload.
10391   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10392     if (NewFD->hasAttr<ConstructorAttr>()) {
10393       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10394           << 1;
10395       NewFD->dropAttr<AvailabilityAttr>();
10396     }
10397     if (NewFD->hasAttr<DestructorAttr>()) {
10398       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10399           << 2;
10400       NewFD->dropAttr<AvailabilityAttr>();
10401     }
10402   }
10403 
10404   // Diagnose no_builtin attribute on function declaration that are not a
10405   // definition.
10406   // FIXME: We should really be doing this in
10407   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10408   // the FunctionDecl and at this point of the code
10409   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10410   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10411   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10412     switch (D.getFunctionDefinitionKind()) {
10413     case FunctionDefinitionKind::Defaulted:
10414     case FunctionDefinitionKind::Deleted:
10415       Diag(NBA->getLocation(),
10416            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10417           << NBA->getSpelling();
10418       break;
10419     case FunctionDefinitionKind::Declaration:
10420       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10421           << NBA->getSpelling();
10422       break;
10423     case FunctionDefinitionKind::Definition:
10424       break;
10425     }
10426 
10427   return NewFD;
10428 }
10429 
10430 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10431 /// when __declspec(code_seg) "is applied to a class, all member functions of
10432 /// the class and nested classes -- this includes compiler-generated special
10433 /// member functions -- are put in the specified segment."
10434 /// The actual behavior is a little more complicated. The Microsoft compiler
10435 /// won't check outer classes if there is an active value from #pragma code_seg.
10436 /// The CodeSeg is always applied from the direct parent but only from outer
10437 /// classes when the #pragma code_seg stack is empty. See:
10438 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10439 /// available since MS has removed the page.
10440 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10441   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10442   if (!Method)
10443     return nullptr;
10444   const CXXRecordDecl *Parent = Method->getParent();
10445   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10446     Attr *NewAttr = SAttr->clone(S.getASTContext());
10447     NewAttr->setImplicit(true);
10448     return NewAttr;
10449   }
10450 
10451   // The Microsoft compiler won't check outer classes for the CodeSeg
10452   // when the #pragma code_seg stack is active.
10453   if (S.CodeSegStack.CurrentValue)
10454    return nullptr;
10455 
10456   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10457     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10458       Attr *NewAttr = SAttr->clone(S.getASTContext());
10459       NewAttr->setImplicit(true);
10460       return NewAttr;
10461     }
10462   }
10463   return nullptr;
10464 }
10465 
10466 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10467 /// containing class. Otherwise it will return implicit SectionAttr if the
10468 /// function is a definition and there is an active value on CodeSegStack
10469 /// (from the current #pragma code-seg value).
10470 ///
10471 /// \param FD Function being declared.
10472 /// \param IsDefinition Whether it is a definition or just a declarartion.
10473 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10474 ///          nullptr if no attribute should be added.
10475 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10476                                                        bool IsDefinition) {
10477   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10478     return A;
10479   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10480       CodeSegStack.CurrentValue)
10481     return SectionAttr::CreateImplicit(
10482         getASTContext(), CodeSegStack.CurrentValue->getString(),
10483         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10484         SectionAttr::Declspec_allocate);
10485   return nullptr;
10486 }
10487 
10488 /// Determines if we can perform a correct type check for \p D as a
10489 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10490 /// best-effort check.
10491 ///
10492 /// \param NewD The new declaration.
10493 /// \param OldD The old declaration.
10494 /// \param NewT The portion of the type of the new declaration to check.
10495 /// \param OldT The portion of the type of the old declaration to check.
10496 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10497                                           QualType NewT, QualType OldT) {
10498   if (!NewD->getLexicalDeclContext()->isDependentContext())
10499     return true;
10500 
10501   // For dependently-typed local extern declarations and friends, we can't
10502   // perform a correct type check in general until instantiation:
10503   //
10504   //   int f();
10505   //   template<typename T> void g() { T f(); }
10506   //
10507   // (valid if g() is only instantiated with T = int).
10508   if (NewT->isDependentType() &&
10509       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10510     return false;
10511 
10512   // Similarly, if the previous declaration was a dependent local extern
10513   // declaration, we don't really know its type yet.
10514   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10515     return false;
10516 
10517   return true;
10518 }
10519 
10520 /// Checks if the new declaration declared in dependent context must be
10521 /// put in the same redeclaration chain as the specified declaration.
10522 ///
10523 /// \param D Declaration that is checked.
10524 /// \param PrevDecl Previous declaration found with proper lookup method for the
10525 ///                 same declaration name.
10526 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10527 ///          belongs to.
10528 ///
10529 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10530   if (!D->getLexicalDeclContext()->isDependentContext())
10531     return true;
10532 
10533   // Don't chain dependent friend function definitions until instantiation, to
10534   // permit cases like
10535   //
10536   //   void func();
10537   //   template<typename T> class C1 { friend void func() {} };
10538   //   template<typename T> class C2 { friend void func() {} };
10539   //
10540   // ... which is valid if only one of C1 and C2 is ever instantiated.
10541   //
10542   // FIXME: This need only apply to function definitions. For now, we proxy
10543   // this by checking for a file-scope function. We do not want this to apply
10544   // to friend declarations nominating member functions, because that gets in
10545   // the way of access checks.
10546   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10547     return false;
10548 
10549   auto *VD = dyn_cast<ValueDecl>(D);
10550   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10551   return !VD || !PrevVD ||
10552          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10553                                         PrevVD->getType());
10554 }
10555 
10556 /// Check the target attribute of the function for MultiVersion
10557 /// validity.
10558 ///
10559 /// Returns true if there was an error, false otherwise.
10560 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10561   const auto *TA = FD->getAttr<TargetAttr>();
10562   assert(TA && "MultiVersion Candidate requires a target attribute");
10563   ParsedTargetAttr ParseInfo = TA->parse();
10564   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10565   enum ErrType { Feature = 0, Architecture = 1 };
10566 
10567   if (!ParseInfo.Architecture.empty() &&
10568       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10569     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10570         << Architecture << ParseInfo.Architecture;
10571     return true;
10572   }
10573 
10574   for (const auto &Feat : ParseInfo.Features) {
10575     auto BareFeat = StringRef{Feat}.substr(1);
10576     if (Feat[0] == '-') {
10577       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10578           << Feature << ("no-" + BareFeat).str();
10579       return true;
10580     }
10581 
10582     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10583         !TargetInfo.isValidFeatureName(BareFeat)) {
10584       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10585           << Feature << BareFeat;
10586       return true;
10587     }
10588   }
10589   return false;
10590 }
10591 
10592 // Provide a white-list of attributes that are allowed to be combined with
10593 // multiversion functions.
10594 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10595                                            MultiVersionKind MVKind) {
10596   // Note: this list/diagnosis must match the list in
10597   // checkMultiversionAttributesAllSame.
10598   switch (Kind) {
10599   default:
10600     return false;
10601   case attr::Used:
10602     return MVKind == MultiVersionKind::Target;
10603   case attr::NonNull:
10604   case attr::NoThrow:
10605     return true;
10606   }
10607 }
10608 
10609 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10610                                                  const FunctionDecl *FD,
10611                                                  const FunctionDecl *CausedFD,
10612                                                  MultiVersionKind MVKind) {
10613   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10614     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10615         << static_cast<unsigned>(MVKind) << A;
10616     if (CausedFD)
10617       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10618     return true;
10619   };
10620 
10621   for (const Attr *A : FD->attrs()) {
10622     switch (A->getKind()) {
10623     case attr::CPUDispatch:
10624     case attr::CPUSpecific:
10625       if (MVKind != MultiVersionKind::CPUDispatch &&
10626           MVKind != MultiVersionKind::CPUSpecific)
10627         return Diagnose(S, A);
10628       break;
10629     case attr::Target:
10630       if (MVKind != MultiVersionKind::Target)
10631         return Diagnose(S, A);
10632       break;
10633     case attr::TargetClones:
10634       if (MVKind != MultiVersionKind::TargetClones)
10635         return Diagnose(S, A);
10636       break;
10637     default:
10638       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10639         return Diagnose(S, A);
10640       break;
10641     }
10642   }
10643   return false;
10644 }
10645 
10646 bool Sema::areMultiversionVariantFunctionsCompatible(
10647     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10648     const PartialDiagnostic &NoProtoDiagID,
10649     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10650     const PartialDiagnosticAt &NoSupportDiagIDAt,
10651     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10652     bool ConstexprSupported, bool CLinkageMayDiffer) {
10653   enum DoesntSupport {
10654     FuncTemplates = 0,
10655     VirtFuncs = 1,
10656     DeducedReturn = 2,
10657     Constructors = 3,
10658     Destructors = 4,
10659     DeletedFuncs = 5,
10660     DefaultedFuncs = 6,
10661     ConstexprFuncs = 7,
10662     ConstevalFuncs = 8,
10663     Lambda = 9,
10664   };
10665   enum Different {
10666     CallingConv = 0,
10667     ReturnType = 1,
10668     ConstexprSpec = 2,
10669     InlineSpec = 3,
10670     Linkage = 4,
10671     LanguageLinkage = 5,
10672   };
10673 
10674   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10675       !OldFD->getType()->getAs<FunctionProtoType>()) {
10676     Diag(OldFD->getLocation(), NoProtoDiagID);
10677     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10678     return true;
10679   }
10680 
10681   if (NoProtoDiagID.getDiagID() != 0 &&
10682       !NewFD->getType()->getAs<FunctionProtoType>())
10683     return Diag(NewFD->getLocation(), NoProtoDiagID);
10684 
10685   if (!TemplatesSupported &&
10686       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10687     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10688            << FuncTemplates;
10689 
10690   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10691     if (NewCXXFD->isVirtual())
10692       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10693              << VirtFuncs;
10694 
10695     if (isa<CXXConstructorDecl>(NewCXXFD))
10696       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10697              << Constructors;
10698 
10699     if (isa<CXXDestructorDecl>(NewCXXFD))
10700       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10701              << Destructors;
10702   }
10703 
10704   if (NewFD->isDeleted())
10705     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10706            << DeletedFuncs;
10707 
10708   if (NewFD->isDefaulted())
10709     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10710            << DefaultedFuncs;
10711 
10712   if (!ConstexprSupported && NewFD->isConstexpr())
10713     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10714            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10715 
10716   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10717   const auto *NewType = cast<FunctionType>(NewQType);
10718   QualType NewReturnType = NewType->getReturnType();
10719 
10720   if (NewReturnType->isUndeducedType())
10721     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10722            << DeducedReturn;
10723 
10724   // Ensure the return type is identical.
10725   if (OldFD) {
10726     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10727     const auto *OldType = cast<FunctionType>(OldQType);
10728     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10729     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10730 
10731     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10732       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10733 
10734     QualType OldReturnType = OldType->getReturnType();
10735 
10736     if (OldReturnType != NewReturnType)
10737       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10738 
10739     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10740       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10741 
10742     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10743       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10744 
10745     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10746       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10747 
10748     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10749       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10750 
10751     if (CheckEquivalentExceptionSpec(
10752             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10753             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10754       return true;
10755   }
10756   return false;
10757 }
10758 
10759 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10760                                              const FunctionDecl *NewFD,
10761                                              bool CausesMV,
10762                                              MultiVersionKind MVKind) {
10763   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10764     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10765     if (OldFD)
10766       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10767     return true;
10768   }
10769 
10770   bool IsCPUSpecificCPUDispatchMVKind =
10771       MVKind == MultiVersionKind::CPUDispatch ||
10772       MVKind == MultiVersionKind::CPUSpecific;
10773 
10774   if (CausesMV && OldFD &&
10775       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10776     return true;
10777 
10778   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10779     return true;
10780 
10781   // Only allow transition to MultiVersion if it hasn't been used.
10782   if (OldFD && CausesMV && OldFD->isUsed(false))
10783     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10784 
10785   return S.areMultiversionVariantFunctionsCompatible(
10786       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10787       PartialDiagnosticAt(NewFD->getLocation(),
10788                           S.PDiag(diag::note_multiversioning_caused_here)),
10789       PartialDiagnosticAt(NewFD->getLocation(),
10790                           S.PDiag(diag::err_multiversion_doesnt_support)
10791                               << static_cast<unsigned>(MVKind)),
10792       PartialDiagnosticAt(NewFD->getLocation(),
10793                           S.PDiag(diag::err_multiversion_diff)),
10794       /*TemplatesSupported=*/false,
10795       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10796       /*CLinkageMayDiffer=*/false);
10797 }
10798 
10799 /// Check the validity of a multiversion function declaration that is the
10800 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10801 ///
10802 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10803 ///
10804 /// Returns true if there was an error, false otherwise.
10805 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10806                                            MultiVersionKind MVKind,
10807                                            const TargetAttr *TA) {
10808   assert(MVKind != MultiVersionKind::None &&
10809          "Function lacks multiversion attribute");
10810 
10811   // Target only causes MV if it is default, otherwise this is a normal
10812   // function.
10813   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10814     return false;
10815 
10816   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10817     FD->setInvalidDecl();
10818     return true;
10819   }
10820 
10821   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10822     FD->setInvalidDecl();
10823     return true;
10824   }
10825 
10826   FD->setIsMultiVersion();
10827   return false;
10828 }
10829 
10830 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10831   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10832     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10833       return true;
10834   }
10835 
10836   return false;
10837 }
10838 
10839 static bool CheckTargetCausesMultiVersioning(
10840     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10841     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10842   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10843   ParsedTargetAttr NewParsed = NewTA->parse();
10844   // Sort order doesn't matter, it just needs to be consistent.
10845   llvm::sort(NewParsed.Features);
10846 
10847   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10848   // to change, this is a simple redeclaration.
10849   if (!NewTA->isDefaultVersion() &&
10850       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10851     return false;
10852 
10853   // Otherwise, this decl causes MultiVersioning.
10854   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10855                                        MultiVersionKind::Target)) {
10856     NewFD->setInvalidDecl();
10857     return true;
10858   }
10859 
10860   if (CheckMultiVersionValue(S, NewFD)) {
10861     NewFD->setInvalidDecl();
10862     return true;
10863   }
10864 
10865   // If this is 'default', permit the forward declaration.
10866   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10867     Redeclaration = true;
10868     OldDecl = OldFD;
10869     OldFD->setIsMultiVersion();
10870     NewFD->setIsMultiVersion();
10871     return false;
10872   }
10873 
10874   if (CheckMultiVersionValue(S, OldFD)) {
10875     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10876     NewFD->setInvalidDecl();
10877     return true;
10878   }
10879 
10880   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10881 
10882   if (OldParsed == NewParsed) {
10883     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10884     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10885     NewFD->setInvalidDecl();
10886     return true;
10887   }
10888 
10889   for (const auto *FD : OldFD->redecls()) {
10890     const auto *CurTA = FD->getAttr<TargetAttr>();
10891     // We allow forward declarations before ANY multiversioning attributes, but
10892     // nothing after the fact.
10893     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10894         (!CurTA || CurTA->isInherited())) {
10895       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10896           << 0;
10897       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10898       NewFD->setInvalidDecl();
10899       return true;
10900     }
10901   }
10902 
10903   OldFD->setIsMultiVersion();
10904   NewFD->setIsMultiVersion();
10905   Redeclaration = false;
10906   OldDecl = nullptr;
10907   Previous.clear();
10908   return false;
10909 }
10910 
10911 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10912                                         MultiVersionKind New) {
10913   if (Old == New || Old == MultiVersionKind::None ||
10914       New == MultiVersionKind::None)
10915     return true;
10916 
10917   return (Old == MultiVersionKind::CPUDispatch &&
10918           New == MultiVersionKind::CPUSpecific) ||
10919          (Old == MultiVersionKind::CPUSpecific &&
10920           New == MultiVersionKind::CPUDispatch);
10921 }
10922 
10923 /// Check the validity of a new function declaration being added to an existing
10924 /// multiversioned declaration collection.
10925 static bool CheckMultiVersionAdditionalDecl(
10926     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10927     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10928     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10929     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10930     LookupResult &Previous) {
10931 
10932   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10933   // Disallow mixing of multiversioning types.
10934   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10935     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10936     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10937     NewFD->setInvalidDecl();
10938     return true;
10939   }
10940 
10941   ParsedTargetAttr NewParsed;
10942   if (NewTA) {
10943     NewParsed = NewTA->parse();
10944     llvm::sort(NewParsed.Features);
10945   }
10946 
10947   bool UseMemberUsingDeclRules =
10948       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10949 
10950   bool MayNeedOverloadableChecks =
10951       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10952 
10953   // Next, check ALL non-overloads to see if this is a redeclaration of a
10954   // previous member of the MultiVersion set.
10955   for (NamedDecl *ND : Previous) {
10956     FunctionDecl *CurFD = ND->getAsFunction();
10957     if (!CurFD)
10958       continue;
10959     if (MayNeedOverloadableChecks &&
10960         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10961       continue;
10962 
10963     switch (NewMVKind) {
10964     case MultiVersionKind::None:
10965       assert(OldMVKind == MultiVersionKind::TargetClones &&
10966              "Only target_clones can be omitted in subsequent declarations");
10967       break;
10968     case MultiVersionKind::Target: {
10969       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10970       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10971         NewFD->setIsMultiVersion();
10972         Redeclaration = true;
10973         OldDecl = ND;
10974         return false;
10975       }
10976 
10977       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10978       if (CurParsed == NewParsed) {
10979         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10980         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10981         NewFD->setInvalidDecl();
10982         return true;
10983       }
10984       break;
10985     }
10986     case MultiVersionKind::TargetClones: {
10987       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10988       Redeclaration = true;
10989       OldDecl = CurFD;
10990       NewFD->setIsMultiVersion();
10991 
10992       if (CurClones && NewClones &&
10993           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10994            !std::equal(CurClones->featuresStrs_begin(),
10995                        CurClones->featuresStrs_end(),
10996                        NewClones->featuresStrs_begin()))) {
10997         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10998         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10999         NewFD->setInvalidDecl();
11000         return true;
11001       }
11002 
11003       return false;
11004     }
11005     case MultiVersionKind::CPUSpecific:
11006     case MultiVersionKind::CPUDispatch: {
11007       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11008       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11009       // Handle CPUDispatch/CPUSpecific versions.
11010       // Only 1 CPUDispatch function is allowed, this will make it go through
11011       // the redeclaration errors.
11012       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11013           CurFD->hasAttr<CPUDispatchAttr>()) {
11014         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11015             std::equal(
11016                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11017                 NewCPUDisp->cpus_begin(),
11018                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11019                   return Cur->getName() == New->getName();
11020                 })) {
11021           NewFD->setIsMultiVersion();
11022           Redeclaration = true;
11023           OldDecl = ND;
11024           return false;
11025         }
11026 
11027         // If the declarations don't match, this is an error condition.
11028         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11029         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11030         NewFD->setInvalidDecl();
11031         return true;
11032       }
11033       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11034         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11035             std::equal(
11036                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11037                 NewCPUSpec->cpus_begin(),
11038                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11039                   return Cur->getName() == New->getName();
11040                 })) {
11041           NewFD->setIsMultiVersion();
11042           Redeclaration = true;
11043           OldDecl = ND;
11044           return false;
11045         }
11046 
11047         // Only 1 version of CPUSpecific is allowed for each CPU.
11048         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11049           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11050             if (CurII == NewII) {
11051               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11052                   << NewII;
11053               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11054               NewFD->setInvalidDecl();
11055               return true;
11056             }
11057           }
11058         }
11059       }
11060       break;
11061     }
11062     }
11063   }
11064 
11065   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11066   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11067   // handled in the attribute adding step.
11068   if (NewMVKind == MultiVersionKind::Target &&
11069       CheckMultiVersionValue(S, NewFD)) {
11070     NewFD->setInvalidDecl();
11071     return true;
11072   }
11073 
11074   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11075                                        !OldFD->isMultiVersion(), NewMVKind)) {
11076     NewFD->setInvalidDecl();
11077     return true;
11078   }
11079 
11080   // Permit forward declarations in the case where these two are compatible.
11081   if (!OldFD->isMultiVersion()) {
11082     OldFD->setIsMultiVersion();
11083     NewFD->setIsMultiVersion();
11084     Redeclaration = true;
11085     OldDecl = OldFD;
11086     return false;
11087   }
11088 
11089   NewFD->setIsMultiVersion();
11090   Redeclaration = false;
11091   OldDecl = nullptr;
11092   Previous.clear();
11093   return false;
11094 }
11095 
11096 /// Check the validity of a mulitversion function declaration.
11097 /// Also sets the multiversion'ness' of the function itself.
11098 ///
11099 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11100 ///
11101 /// Returns true if there was an error, false otherwise.
11102 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11103                                       bool &Redeclaration, NamedDecl *&OldDecl,
11104                                       LookupResult &Previous) {
11105   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11106   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11107   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11108   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11109   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11110 
11111   // Main isn't allowed to become a multiversion function, however it IS
11112   // permitted to have 'main' be marked with the 'target' optimization hint.
11113   if (NewFD->isMain()) {
11114     if (MVKind != MultiVersionKind::None &&
11115         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11116       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11117       NewFD->setInvalidDecl();
11118       return true;
11119     }
11120     return false;
11121   }
11122 
11123   if (!OldDecl || !OldDecl->getAsFunction() ||
11124       OldDecl->getDeclContext()->getRedeclContext() !=
11125           NewFD->getDeclContext()->getRedeclContext()) {
11126     // If there's no previous declaration, AND this isn't attempting to cause
11127     // multiversioning, this isn't an error condition.
11128     if (MVKind == MultiVersionKind::None)
11129       return false;
11130     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11131   }
11132 
11133   FunctionDecl *OldFD = OldDecl->getAsFunction();
11134 
11135   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11136     return false;
11137 
11138   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11139   // for target_clones.
11140   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11141       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11142     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11143         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11144     NewFD->setInvalidDecl();
11145     return true;
11146   }
11147 
11148   if (!OldFD->isMultiVersion()) {
11149     switch (MVKind) {
11150     case MultiVersionKind::Target:
11151       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11152                                               Redeclaration, OldDecl, Previous);
11153     case MultiVersionKind::TargetClones:
11154       if (OldFD->isUsed(false)) {
11155         NewFD->setInvalidDecl();
11156         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11157       }
11158       OldFD->setIsMultiVersion();
11159       break;
11160     case MultiVersionKind::CPUDispatch:
11161     case MultiVersionKind::CPUSpecific:
11162     case MultiVersionKind::None:
11163       break;
11164     }
11165   }
11166 
11167   // At this point, we have a multiversion function decl (in OldFD) AND an
11168   // appropriate attribute in the current function decl.  Resolve that these are
11169   // still compatible with previous declarations.
11170   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11171                                          NewCPUDisp, NewCPUSpec, NewClones,
11172                                          Redeclaration, OldDecl, Previous);
11173 }
11174 
11175 /// Perform semantic checking of a new function declaration.
11176 ///
11177 /// Performs semantic analysis of the new function declaration
11178 /// NewFD. This routine performs all semantic checking that does not
11179 /// require the actual declarator involved in the declaration, and is
11180 /// used both for the declaration of functions as they are parsed
11181 /// (called via ActOnDeclarator) and for the declaration of functions
11182 /// that have been instantiated via C++ template instantiation (called
11183 /// via InstantiateDecl).
11184 ///
11185 /// \param IsMemberSpecialization whether this new function declaration is
11186 /// a member specialization (that replaces any definition provided by the
11187 /// previous declaration).
11188 ///
11189 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11190 ///
11191 /// \returns true if the function declaration is a redeclaration.
11192 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11193                                     LookupResult &Previous,
11194                                     bool IsMemberSpecialization,
11195                                     bool DeclIsDefn) {
11196   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11197          "Variably modified return types are not handled here");
11198 
11199   // Determine whether the type of this function should be merged with
11200   // a previous visible declaration. This never happens for functions in C++,
11201   // and always happens in C if the previous declaration was visible.
11202   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11203                                !Previous.isShadowed();
11204 
11205   bool Redeclaration = false;
11206   NamedDecl *OldDecl = nullptr;
11207   bool MayNeedOverloadableChecks = false;
11208 
11209   // Merge or overload the declaration with an existing declaration of
11210   // the same name, if appropriate.
11211   if (!Previous.empty()) {
11212     // Determine whether NewFD is an overload of PrevDecl or
11213     // a declaration that requires merging. If it's an overload,
11214     // there's no more work to do here; we'll just add the new
11215     // function to the scope.
11216     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11217       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11218       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11219         Redeclaration = true;
11220         OldDecl = Candidate;
11221       }
11222     } else {
11223       MayNeedOverloadableChecks = true;
11224       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11225                             /*NewIsUsingDecl*/ false)) {
11226       case Ovl_Match:
11227         Redeclaration = true;
11228         break;
11229 
11230       case Ovl_NonFunction:
11231         Redeclaration = true;
11232         break;
11233 
11234       case Ovl_Overload:
11235         Redeclaration = false;
11236         break;
11237       }
11238     }
11239   }
11240 
11241   // Check for a previous extern "C" declaration with this name.
11242   if (!Redeclaration &&
11243       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11244     if (!Previous.empty()) {
11245       // This is an extern "C" declaration with the same name as a previous
11246       // declaration, and thus redeclares that entity...
11247       Redeclaration = true;
11248       OldDecl = Previous.getFoundDecl();
11249       MergeTypeWithPrevious = false;
11250 
11251       // ... except in the presence of __attribute__((overloadable)).
11252       if (OldDecl->hasAttr<OverloadableAttr>() ||
11253           NewFD->hasAttr<OverloadableAttr>()) {
11254         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11255           MayNeedOverloadableChecks = true;
11256           Redeclaration = false;
11257           OldDecl = nullptr;
11258         }
11259       }
11260     }
11261   }
11262 
11263   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11264     return Redeclaration;
11265 
11266   // PPC MMA non-pointer types are not allowed as function return types.
11267   if (Context.getTargetInfo().getTriple().isPPC64() &&
11268       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11269     NewFD->setInvalidDecl();
11270   }
11271 
11272   // C++11 [dcl.constexpr]p8:
11273   //   A constexpr specifier for a non-static member function that is not
11274   //   a constructor declares that member function to be const.
11275   //
11276   // This needs to be delayed until we know whether this is an out-of-line
11277   // definition of a static member function.
11278   //
11279   // This rule is not present in C++1y, so we produce a backwards
11280   // compatibility warning whenever it happens in C++11.
11281   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11282   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11283       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11284       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11285     CXXMethodDecl *OldMD = nullptr;
11286     if (OldDecl)
11287       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11288     if (!OldMD || !OldMD->isStatic()) {
11289       const FunctionProtoType *FPT =
11290         MD->getType()->castAs<FunctionProtoType>();
11291       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11292       EPI.TypeQuals.addConst();
11293       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11294                                           FPT->getParamTypes(), EPI));
11295 
11296       // Warn that we did this, if we're not performing template instantiation.
11297       // In that case, we'll have warned already when the template was defined.
11298       if (!inTemplateInstantiation()) {
11299         SourceLocation AddConstLoc;
11300         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11301                 .IgnoreParens().getAs<FunctionTypeLoc>())
11302           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11303 
11304         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11305           << FixItHint::CreateInsertion(AddConstLoc, " const");
11306       }
11307     }
11308   }
11309 
11310   if (Redeclaration) {
11311     // NewFD and OldDecl represent declarations that need to be
11312     // merged.
11313     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11314                           DeclIsDefn)) {
11315       NewFD->setInvalidDecl();
11316       return Redeclaration;
11317     }
11318 
11319     Previous.clear();
11320     Previous.addDecl(OldDecl);
11321 
11322     if (FunctionTemplateDecl *OldTemplateDecl =
11323             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11324       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11325       FunctionTemplateDecl *NewTemplateDecl
11326         = NewFD->getDescribedFunctionTemplate();
11327       assert(NewTemplateDecl && "Template/non-template mismatch");
11328 
11329       // The call to MergeFunctionDecl above may have created some state in
11330       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11331       // can add it as a redeclaration.
11332       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11333 
11334       NewFD->setPreviousDeclaration(OldFD);
11335       if (NewFD->isCXXClassMember()) {
11336         NewFD->setAccess(OldTemplateDecl->getAccess());
11337         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11338       }
11339 
11340       // If this is an explicit specialization of a member that is a function
11341       // template, mark it as a member specialization.
11342       if (IsMemberSpecialization &&
11343           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11344         NewTemplateDecl->setMemberSpecialization();
11345         assert(OldTemplateDecl->isMemberSpecialization());
11346         // Explicit specializations of a member template do not inherit deleted
11347         // status from the parent member template that they are specializing.
11348         if (OldFD->isDeleted()) {
11349           // FIXME: This assert will not hold in the presence of modules.
11350           assert(OldFD->getCanonicalDecl() == OldFD);
11351           // FIXME: We need an update record for this AST mutation.
11352           OldFD->setDeletedAsWritten(false);
11353         }
11354       }
11355 
11356     } else {
11357       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11358         auto *OldFD = cast<FunctionDecl>(OldDecl);
11359         // This needs to happen first so that 'inline' propagates.
11360         NewFD->setPreviousDeclaration(OldFD);
11361         if (NewFD->isCXXClassMember())
11362           NewFD->setAccess(OldFD->getAccess());
11363       }
11364     }
11365   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11366              !NewFD->getAttr<OverloadableAttr>()) {
11367     assert((Previous.empty() ||
11368             llvm::any_of(Previous,
11369                          [](const NamedDecl *ND) {
11370                            return ND->hasAttr<OverloadableAttr>();
11371                          })) &&
11372            "Non-redecls shouldn't happen without overloadable present");
11373 
11374     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11375       const auto *FD = dyn_cast<FunctionDecl>(ND);
11376       return FD && !FD->hasAttr<OverloadableAttr>();
11377     });
11378 
11379     if (OtherUnmarkedIter != Previous.end()) {
11380       Diag(NewFD->getLocation(),
11381            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11382       Diag((*OtherUnmarkedIter)->getLocation(),
11383            diag::note_attribute_overloadable_prev_overload)
11384           << false;
11385 
11386       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11387     }
11388   }
11389 
11390   if (LangOpts.OpenMP)
11391     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11392 
11393   // Semantic checking for this function declaration (in isolation).
11394 
11395   if (getLangOpts().CPlusPlus) {
11396     // C++-specific checks.
11397     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11398       CheckConstructor(Constructor);
11399     } else if (CXXDestructorDecl *Destructor =
11400                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11401       CXXRecordDecl *Record = Destructor->getParent();
11402       QualType ClassType = Context.getTypeDeclType(Record);
11403 
11404       // FIXME: Shouldn't we be able to perform this check even when the class
11405       // type is dependent? Both gcc and edg can handle that.
11406       if (!ClassType->isDependentType()) {
11407         DeclarationName Name
11408           = Context.DeclarationNames.getCXXDestructorName(
11409                                         Context.getCanonicalType(ClassType));
11410         if (NewFD->getDeclName() != Name) {
11411           Diag(NewFD->getLocation(), diag::err_destructor_name);
11412           NewFD->setInvalidDecl();
11413           return Redeclaration;
11414         }
11415       }
11416     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11417       if (auto *TD = Guide->getDescribedFunctionTemplate())
11418         CheckDeductionGuideTemplate(TD);
11419 
11420       // A deduction guide is not on the list of entities that can be
11421       // explicitly specialized.
11422       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11423         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11424             << /*explicit specialization*/ 1;
11425     }
11426 
11427     // Find any virtual functions that this function overrides.
11428     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11429       if (!Method->isFunctionTemplateSpecialization() &&
11430           !Method->getDescribedFunctionTemplate() &&
11431           Method->isCanonicalDecl()) {
11432         AddOverriddenMethods(Method->getParent(), Method);
11433       }
11434       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11435         // C++2a [class.virtual]p6
11436         // A virtual method shall not have a requires-clause.
11437         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11438              diag::err_constrained_virtual_method);
11439 
11440       if (Method->isStatic())
11441         checkThisInStaticMemberFunctionType(Method);
11442     }
11443 
11444     // C++20: dcl.decl.general p4:
11445     // The optional requires-clause ([temp.pre]) in an init-declarator or
11446     // member-declarator shall be present only if the declarator declares a
11447     // templated function ([dcl.fct]).
11448     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11449       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11450         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11451     }
11452 
11453     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11454       ActOnConversionDeclarator(Conversion);
11455 
11456     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11457     if (NewFD->isOverloadedOperator() &&
11458         CheckOverloadedOperatorDeclaration(NewFD)) {
11459       NewFD->setInvalidDecl();
11460       return Redeclaration;
11461     }
11462 
11463     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11464     if (NewFD->getLiteralIdentifier() &&
11465         CheckLiteralOperatorDeclaration(NewFD)) {
11466       NewFD->setInvalidDecl();
11467       return Redeclaration;
11468     }
11469 
11470     // In C++, check default arguments now that we have merged decls. Unless
11471     // the lexical context is the class, because in this case this is done
11472     // during delayed parsing anyway.
11473     if (!CurContext->isRecord())
11474       CheckCXXDefaultArguments(NewFD);
11475 
11476     // If this function is declared as being extern "C", then check to see if
11477     // the function returns a UDT (class, struct, or union type) that is not C
11478     // compatible, and if it does, warn the user.
11479     // But, issue any diagnostic on the first declaration only.
11480     if (Previous.empty() && NewFD->isExternC()) {
11481       QualType R = NewFD->getReturnType();
11482       if (R->isIncompleteType() && !R->isVoidType())
11483         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11484             << NewFD << R;
11485       else if (!R.isPODType(Context) && !R->isVoidType() &&
11486                !R->isObjCObjectPointerType())
11487         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11488     }
11489 
11490     // C++1z [dcl.fct]p6:
11491     //   [...] whether the function has a non-throwing exception-specification
11492     //   [is] part of the function type
11493     //
11494     // This results in an ABI break between C++14 and C++17 for functions whose
11495     // declared type includes an exception-specification in a parameter or
11496     // return type. (Exception specifications on the function itself are OK in
11497     // most cases, and exception specifications are not permitted in most other
11498     // contexts where they could make it into a mangling.)
11499     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11500       auto HasNoexcept = [&](QualType T) -> bool {
11501         // Strip off declarator chunks that could be between us and a function
11502         // type. We don't need to look far, exception specifications are very
11503         // restricted prior to C++17.
11504         if (auto *RT = T->getAs<ReferenceType>())
11505           T = RT->getPointeeType();
11506         else if (T->isAnyPointerType())
11507           T = T->getPointeeType();
11508         else if (auto *MPT = T->getAs<MemberPointerType>())
11509           T = MPT->getPointeeType();
11510         if (auto *FPT = T->getAs<FunctionProtoType>())
11511           if (FPT->isNothrow())
11512             return true;
11513         return false;
11514       };
11515 
11516       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11517       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11518       for (QualType T : FPT->param_types())
11519         AnyNoexcept |= HasNoexcept(T);
11520       if (AnyNoexcept)
11521         Diag(NewFD->getLocation(),
11522              diag::warn_cxx17_compat_exception_spec_in_signature)
11523             << NewFD;
11524     }
11525 
11526     if (!Redeclaration && LangOpts.CUDA)
11527       checkCUDATargetOverload(NewFD, Previous);
11528   }
11529   return Redeclaration;
11530 }
11531 
11532 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11533   // C++11 [basic.start.main]p3:
11534   //   A program that [...] declares main to be inline, static or
11535   //   constexpr is ill-formed.
11536   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11537   //   appear in a declaration of main.
11538   // static main is not an error under C99, but we should warn about it.
11539   // We accept _Noreturn main as an extension.
11540   if (FD->getStorageClass() == SC_Static)
11541     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11542          ? diag::err_static_main : diag::warn_static_main)
11543       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11544   if (FD->isInlineSpecified())
11545     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11546       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11547   if (DS.isNoreturnSpecified()) {
11548     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11549     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11550     Diag(NoreturnLoc, diag::ext_noreturn_main);
11551     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11552       << FixItHint::CreateRemoval(NoreturnRange);
11553   }
11554   if (FD->isConstexpr()) {
11555     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11556         << FD->isConsteval()
11557         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11558     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11559   }
11560 
11561   if (getLangOpts().OpenCL) {
11562     Diag(FD->getLocation(), diag::err_opencl_no_main)
11563         << FD->hasAttr<OpenCLKernelAttr>();
11564     FD->setInvalidDecl();
11565     return;
11566   }
11567 
11568   // Functions named main in hlsl are default entries, but don't have specific
11569   // signatures they are required to conform to.
11570   if (getLangOpts().HLSL)
11571     return;
11572 
11573   QualType T = FD->getType();
11574   assert(T->isFunctionType() && "function decl is not of function type");
11575   const FunctionType* FT = T->castAs<FunctionType>();
11576 
11577   // Set default calling convention for main()
11578   if (FT->getCallConv() != CC_C) {
11579     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11580     FD->setType(QualType(FT, 0));
11581     T = Context.getCanonicalType(FD->getType());
11582   }
11583 
11584   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11585     // In C with GNU extensions we allow main() to have non-integer return
11586     // type, but we should warn about the extension, and we disable the
11587     // implicit-return-zero rule.
11588 
11589     // GCC in C mode accepts qualified 'int'.
11590     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11591       FD->setHasImplicitReturnZero(true);
11592     else {
11593       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11594       SourceRange RTRange = FD->getReturnTypeSourceRange();
11595       if (RTRange.isValid())
11596         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11597             << FixItHint::CreateReplacement(RTRange, "int");
11598     }
11599   } else {
11600     // In C and C++, main magically returns 0 if you fall off the end;
11601     // set the flag which tells us that.
11602     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11603 
11604     // All the standards say that main() should return 'int'.
11605     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11606       FD->setHasImplicitReturnZero(true);
11607     else {
11608       // Otherwise, this is just a flat-out error.
11609       SourceRange RTRange = FD->getReturnTypeSourceRange();
11610       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11611           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11612                                 : FixItHint());
11613       FD->setInvalidDecl(true);
11614     }
11615   }
11616 
11617   // Treat protoless main() as nullary.
11618   if (isa<FunctionNoProtoType>(FT)) return;
11619 
11620   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11621   unsigned nparams = FTP->getNumParams();
11622   assert(FD->getNumParams() == nparams);
11623 
11624   bool HasExtraParameters = (nparams > 3);
11625 
11626   if (FTP->isVariadic()) {
11627     Diag(FD->getLocation(), diag::ext_variadic_main);
11628     // FIXME: if we had information about the location of the ellipsis, we
11629     // could add a FixIt hint to remove it as a parameter.
11630   }
11631 
11632   // Darwin passes an undocumented fourth argument of type char**.  If
11633   // other platforms start sprouting these, the logic below will start
11634   // getting shifty.
11635   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11636     HasExtraParameters = false;
11637 
11638   if (HasExtraParameters) {
11639     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11640     FD->setInvalidDecl(true);
11641     nparams = 3;
11642   }
11643 
11644   // FIXME: a lot of the following diagnostics would be improved
11645   // if we had some location information about types.
11646 
11647   QualType CharPP =
11648     Context.getPointerType(Context.getPointerType(Context.CharTy));
11649   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11650 
11651   for (unsigned i = 0; i < nparams; ++i) {
11652     QualType AT = FTP->getParamType(i);
11653 
11654     bool mismatch = true;
11655 
11656     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11657       mismatch = false;
11658     else if (Expected[i] == CharPP) {
11659       // As an extension, the following forms are okay:
11660       //   char const **
11661       //   char const * const *
11662       //   char * const *
11663 
11664       QualifierCollector qs;
11665       const PointerType* PT;
11666       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11667           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11668           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11669                               Context.CharTy)) {
11670         qs.removeConst();
11671         mismatch = !qs.empty();
11672       }
11673     }
11674 
11675     if (mismatch) {
11676       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11677       // TODO: suggest replacing given type with expected type
11678       FD->setInvalidDecl(true);
11679     }
11680   }
11681 
11682   if (nparams == 1 && !FD->isInvalidDecl()) {
11683     Diag(FD->getLocation(), diag::warn_main_one_arg);
11684   }
11685 
11686   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11687     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11688     FD->setInvalidDecl();
11689   }
11690 }
11691 
11692 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11693 
11694   // Default calling convention for main and wmain is __cdecl
11695   if (FD->getName() == "main" || FD->getName() == "wmain")
11696     return false;
11697 
11698   // Default calling convention for MinGW is __cdecl
11699   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11700   if (T.isWindowsGNUEnvironment())
11701     return false;
11702 
11703   // Default calling convention for WinMain, wWinMain and DllMain
11704   // is __stdcall on 32 bit Windows
11705   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11706     return true;
11707 
11708   return false;
11709 }
11710 
11711 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11712   QualType T = FD->getType();
11713   assert(T->isFunctionType() && "function decl is not of function type");
11714   const FunctionType *FT = T->castAs<FunctionType>();
11715 
11716   // Set an implicit return of 'zero' if the function can return some integral,
11717   // enumeration, pointer or nullptr type.
11718   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11719       FT->getReturnType()->isAnyPointerType() ||
11720       FT->getReturnType()->isNullPtrType())
11721     // DllMain is exempt because a return value of zero means it failed.
11722     if (FD->getName() != "DllMain")
11723       FD->setHasImplicitReturnZero(true);
11724 
11725   // Explicity specified calling conventions are applied to MSVC entry points
11726   if (!hasExplicitCallingConv(T)) {
11727     if (isDefaultStdCall(FD, *this)) {
11728       if (FT->getCallConv() != CC_X86StdCall) {
11729         FT = Context.adjustFunctionType(
11730             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11731         FD->setType(QualType(FT, 0));
11732       }
11733     } else if (FT->getCallConv() != CC_C) {
11734       FT = Context.adjustFunctionType(FT,
11735                                       FT->getExtInfo().withCallingConv(CC_C));
11736       FD->setType(QualType(FT, 0));
11737     }
11738   }
11739 
11740   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11741     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11742     FD->setInvalidDecl();
11743   }
11744 }
11745 
11746 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11747   // FIXME: Need strict checking.  In C89, we need to check for
11748   // any assignment, increment, decrement, function-calls, or
11749   // commas outside of a sizeof.  In C99, it's the same list,
11750   // except that the aforementioned are allowed in unevaluated
11751   // expressions.  Everything else falls under the
11752   // "may accept other forms of constant expressions" exception.
11753   //
11754   // Regular C++ code will not end up here (exceptions: language extensions,
11755   // OpenCL C++ etc), so the constant expression rules there don't matter.
11756   if (Init->isValueDependent()) {
11757     assert(Init->containsErrors() &&
11758            "Dependent code should only occur in error-recovery path.");
11759     return true;
11760   }
11761   const Expr *Culprit;
11762   if (Init->isConstantInitializer(Context, false, &Culprit))
11763     return false;
11764   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11765     << Culprit->getSourceRange();
11766   return true;
11767 }
11768 
11769 namespace {
11770   // Visits an initialization expression to see if OrigDecl is evaluated in
11771   // its own initialization and throws a warning if it does.
11772   class SelfReferenceChecker
11773       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11774     Sema &S;
11775     Decl *OrigDecl;
11776     bool isRecordType;
11777     bool isPODType;
11778     bool isReferenceType;
11779 
11780     bool isInitList;
11781     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11782 
11783   public:
11784     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11785 
11786     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11787                                                     S(S), OrigDecl(OrigDecl) {
11788       isPODType = false;
11789       isRecordType = false;
11790       isReferenceType = false;
11791       isInitList = false;
11792       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11793         isPODType = VD->getType().isPODType(S.Context);
11794         isRecordType = VD->getType()->isRecordType();
11795         isReferenceType = VD->getType()->isReferenceType();
11796       }
11797     }
11798 
11799     // For most expressions, just call the visitor.  For initializer lists,
11800     // track the index of the field being initialized since fields are
11801     // initialized in order allowing use of previously initialized fields.
11802     void CheckExpr(Expr *E) {
11803       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11804       if (!InitList) {
11805         Visit(E);
11806         return;
11807       }
11808 
11809       // Track and increment the index here.
11810       isInitList = true;
11811       InitFieldIndex.push_back(0);
11812       for (auto Child : InitList->children()) {
11813         CheckExpr(cast<Expr>(Child));
11814         ++InitFieldIndex.back();
11815       }
11816       InitFieldIndex.pop_back();
11817     }
11818 
11819     // Returns true if MemberExpr is checked and no further checking is needed.
11820     // Returns false if additional checking is required.
11821     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11822       llvm::SmallVector<FieldDecl*, 4> Fields;
11823       Expr *Base = E;
11824       bool ReferenceField = false;
11825 
11826       // Get the field members used.
11827       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11828         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11829         if (!FD)
11830           return false;
11831         Fields.push_back(FD);
11832         if (FD->getType()->isReferenceType())
11833           ReferenceField = true;
11834         Base = ME->getBase()->IgnoreParenImpCasts();
11835       }
11836 
11837       // Keep checking only if the base Decl is the same.
11838       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11839       if (!DRE || DRE->getDecl() != OrigDecl)
11840         return false;
11841 
11842       // A reference field can be bound to an unininitialized field.
11843       if (CheckReference && !ReferenceField)
11844         return true;
11845 
11846       // Convert FieldDecls to their index number.
11847       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11848       for (const FieldDecl *I : llvm::reverse(Fields))
11849         UsedFieldIndex.push_back(I->getFieldIndex());
11850 
11851       // See if a warning is needed by checking the first difference in index
11852       // numbers.  If field being used has index less than the field being
11853       // initialized, then the use is safe.
11854       for (auto UsedIter = UsedFieldIndex.begin(),
11855                 UsedEnd = UsedFieldIndex.end(),
11856                 OrigIter = InitFieldIndex.begin(),
11857                 OrigEnd = InitFieldIndex.end();
11858            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11859         if (*UsedIter < *OrigIter)
11860           return true;
11861         if (*UsedIter > *OrigIter)
11862           break;
11863       }
11864 
11865       // TODO: Add a different warning which will print the field names.
11866       HandleDeclRefExpr(DRE);
11867       return true;
11868     }
11869 
11870     // For most expressions, the cast is directly above the DeclRefExpr.
11871     // For conditional operators, the cast can be outside the conditional
11872     // operator if both expressions are DeclRefExpr's.
11873     void HandleValue(Expr *E) {
11874       E = E->IgnoreParens();
11875       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11876         HandleDeclRefExpr(DRE);
11877         return;
11878       }
11879 
11880       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11881         Visit(CO->getCond());
11882         HandleValue(CO->getTrueExpr());
11883         HandleValue(CO->getFalseExpr());
11884         return;
11885       }
11886 
11887       if (BinaryConditionalOperator *BCO =
11888               dyn_cast<BinaryConditionalOperator>(E)) {
11889         Visit(BCO->getCond());
11890         HandleValue(BCO->getFalseExpr());
11891         return;
11892       }
11893 
11894       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11895         HandleValue(OVE->getSourceExpr());
11896         return;
11897       }
11898 
11899       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11900         if (BO->getOpcode() == BO_Comma) {
11901           Visit(BO->getLHS());
11902           HandleValue(BO->getRHS());
11903           return;
11904         }
11905       }
11906 
11907       if (isa<MemberExpr>(E)) {
11908         if (isInitList) {
11909           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11910                                       false /*CheckReference*/))
11911             return;
11912         }
11913 
11914         Expr *Base = E->IgnoreParenImpCasts();
11915         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11916           // Check for static member variables and don't warn on them.
11917           if (!isa<FieldDecl>(ME->getMemberDecl()))
11918             return;
11919           Base = ME->getBase()->IgnoreParenImpCasts();
11920         }
11921         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11922           HandleDeclRefExpr(DRE);
11923         return;
11924       }
11925 
11926       Visit(E);
11927     }
11928 
11929     // Reference types not handled in HandleValue are handled here since all
11930     // uses of references are bad, not just r-value uses.
11931     void VisitDeclRefExpr(DeclRefExpr *E) {
11932       if (isReferenceType)
11933         HandleDeclRefExpr(E);
11934     }
11935 
11936     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11937       if (E->getCastKind() == CK_LValueToRValue) {
11938         HandleValue(E->getSubExpr());
11939         return;
11940       }
11941 
11942       Inherited::VisitImplicitCastExpr(E);
11943     }
11944 
11945     void VisitMemberExpr(MemberExpr *E) {
11946       if (isInitList) {
11947         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11948           return;
11949       }
11950 
11951       // Don't warn on arrays since they can be treated as pointers.
11952       if (E->getType()->canDecayToPointerType()) return;
11953 
11954       // Warn when a non-static method call is followed by non-static member
11955       // field accesses, which is followed by a DeclRefExpr.
11956       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11957       bool Warn = (MD && !MD->isStatic());
11958       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11959       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11960         if (!isa<FieldDecl>(ME->getMemberDecl()))
11961           Warn = false;
11962         Base = ME->getBase()->IgnoreParenImpCasts();
11963       }
11964 
11965       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11966         if (Warn)
11967           HandleDeclRefExpr(DRE);
11968         return;
11969       }
11970 
11971       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11972       // Visit that expression.
11973       Visit(Base);
11974     }
11975 
11976     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11977       Expr *Callee = E->getCallee();
11978 
11979       if (isa<UnresolvedLookupExpr>(Callee))
11980         return Inherited::VisitCXXOperatorCallExpr(E);
11981 
11982       Visit(Callee);
11983       for (auto Arg: E->arguments())
11984         HandleValue(Arg->IgnoreParenImpCasts());
11985     }
11986 
11987     void VisitUnaryOperator(UnaryOperator *E) {
11988       // For POD record types, addresses of its own members are well-defined.
11989       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11990           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11991         if (!isPODType)
11992           HandleValue(E->getSubExpr());
11993         return;
11994       }
11995 
11996       if (E->isIncrementDecrementOp()) {
11997         HandleValue(E->getSubExpr());
11998         return;
11999       }
12000 
12001       Inherited::VisitUnaryOperator(E);
12002     }
12003 
12004     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12005 
12006     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12007       if (E->getConstructor()->isCopyConstructor()) {
12008         Expr *ArgExpr = E->getArg(0);
12009         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12010           if (ILE->getNumInits() == 1)
12011             ArgExpr = ILE->getInit(0);
12012         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12013           if (ICE->getCastKind() == CK_NoOp)
12014             ArgExpr = ICE->getSubExpr();
12015         HandleValue(ArgExpr);
12016         return;
12017       }
12018       Inherited::VisitCXXConstructExpr(E);
12019     }
12020 
12021     void VisitCallExpr(CallExpr *E) {
12022       // Treat std::move as a use.
12023       if (E->isCallToStdMove()) {
12024         HandleValue(E->getArg(0));
12025         return;
12026       }
12027 
12028       Inherited::VisitCallExpr(E);
12029     }
12030 
12031     void VisitBinaryOperator(BinaryOperator *E) {
12032       if (E->isCompoundAssignmentOp()) {
12033         HandleValue(E->getLHS());
12034         Visit(E->getRHS());
12035         return;
12036       }
12037 
12038       Inherited::VisitBinaryOperator(E);
12039     }
12040 
12041     // A custom visitor for BinaryConditionalOperator is needed because the
12042     // regular visitor would check the condition and true expression separately
12043     // but both point to the same place giving duplicate diagnostics.
12044     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12045       Visit(E->getCond());
12046       Visit(E->getFalseExpr());
12047     }
12048 
12049     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12050       Decl* ReferenceDecl = DRE->getDecl();
12051       if (OrigDecl != ReferenceDecl) return;
12052       unsigned diag;
12053       if (isReferenceType) {
12054         diag = diag::warn_uninit_self_reference_in_reference_init;
12055       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12056         diag = diag::warn_static_self_reference_in_init;
12057       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12058                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12059                  DRE->getDecl()->getType()->isRecordType()) {
12060         diag = diag::warn_uninit_self_reference_in_init;
12061       } else {
12062         // Local variables will be handled by the CFG analysis.
12063         return;
12064       }
12065 
12066       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12067                             S.PDiag(diag)
12068                                 << DRE->getDecl() << OrigDecl->getLocation()
12069                                 << DRE->getSourceRange());
12070     }
12071   };
12072 
12073   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12074   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12075                                  bool DirectInit) {
12076     // Parameters arguments are occassionially constructed with itself,
12077     // for instance, in recursive functions.  Skip them.
12078     if (isa<ParmVarDecl>(OrigDecl))
12079       return;
12080 
12081     E = E->IgnoreParens();
12082 
12083     // Skip checking T a = a where T is not a record or reference type.
12084     // Doing so is a way to silence uninitialized warnings.
12085     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12086       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12087         if (ICE->getCastKind() == CK_LValueToRValue)
12088           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12089             if (DRE->getDecl() == OrigDecl)
12090               return;
12091 
12092     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12093   }
12094 } // end anonymous namespace
12095 
12096 namespace {
12097   // Simple wrapper to add the name of a variable or (if no variable is
12098   // available) a DeclarationName into a diagnostic.
12099   struct VarDeclOrName {
12100     VarDecl *VDecl;
12101     DeclarationName Name;
12102 
12103     friend const Sema::SemaDiagnosticBuilder &
12104     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12105       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12106     }
12107   };
12108 } // end anonymous namespace
12109 
12110 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12111                                             DeclarationName Name, QualType Type,
12112                                             TypeSourceInfo *TSI,
12113                                             SourceRange Range, bool DirectInit,
12114                                             Expr *Init) {
12115   bool IsInitCapture = !VDecl;
12116   assert((!VDecl || !VDecl->isInitCapture()) &&
12117          "init captures are expected to be deduced prior to initialization");
12118 
12119   VarDeclOrName VN{VDecl, Name};
12120 
12121   DeducedType *Deduced = Type->getContainedDeducedType();
12122   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12123 
12124   // C++11 [dcl.spec.auto]p3
12125   if (!Init) {
12126     assert(VDecl && "no init for init capture deduction?");
12127 
12128     // Except for class argument deduction, and then for an initializing
12129     // declaration only, i.e. no static at class scope or extern.
12130     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12131         VDecl->hasExternalStorage() ||
12132         VDecl->isStaticDataMember()) {
12133       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12134         << VDecl->getDeclName() << Type;
12135       return QualType();
12136     }
12137   }
12138 
12139   ArrayRef<Expr*> DeduceInits;
12140   if (Init)
12141     DeduceInits = Init;
12142 
12143   if (DirectInit) {
12144     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12145       DeduceInits = PL->exprs();
12146   }
12147 
12148   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12149     assert(VDecl && "non-auto type for init capture deduction?");
12150     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12151     InitializationKind Kind = InitializationKind::CreateForInit(
12152         VDecl->getLocation(), DirectInit, Init);
12153     // FIXME: Initialization should not be taking a mutable list of inits.
12154     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12155     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12156                                                        InitsCopy);
12157   }
12158 
12159   if (DirectInit) {
12160     if (auto *IL = dyn_cast<InitListExpr>(Init))
12161       DeduceInits = IL->inits();
12162   }
12163 
12164   // Deduction only works if we have exactly one source expression.
12165   if (DeduceInits.empty()) {
12166     // It isn't possible to write this directly, but it is possible to
12167     // end up in this situation with "auto x(some_pack...);"
12168     Diag(Init->getBeginLoc(), IsInitCapture
12169                                   ? diag::err_init_capture_no_expression
12170                                   : diag::err_auto_var_init_no_expression)
12171         << VN << Type << Range;
12172     return QualType();
12173   }
12174 
12175   if (DeduceInits.size() > 1) {
12176     Diag(DeduceInits[1]->getBeginLoc(),
12177          IsInitCapture ? diag::err_init_capture_multiple_expressions
12178                        : diag::err_auto_var_init_multiple_expressions)
12179         << VN << Type << Range;
12180     return QualType();
12181   }
12182 
12183   Expr *DeduceInit = DeduceInits[0];
12184   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12185     Diag(Init->getBeginLoc(), IsInitCapture
12186                                   ? diag::err_init_capture_paren_braces
12187                                   : diag::err_auto_var_init_paren_braces)
12188         << isa<InitListExpr>(Init) << VN << Type << Range;
12189     return QualType();
12190   }
12191 
12192   // Expressions default to 'id' when we're in a debugger.
12193   bool DefaultedAnyToId = false;
12194   if (getLangOpts().DebuggerCastResultToId &&
12195       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12196     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12197     if (Result.isInvalid()) {
12198       return QualType();
12199     }
12200     Init = Result.get();
12201     DefaultedAnyToId = true;
12202   }
12203 
12204   // C++ [dcl.decomp]p1:
12205   //   If the assignment-expression [...] has array type A and no ref-qualifier
12206   //   is present, e has type cv A
12207   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12208       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12209       DeduceInit->getType()->isConstantArrayType())
12210     return Context.getQualifiedType(DeduceInit->getType(),
12211                                     Type.getQualifiers());
12212 
12213   QualType DeducedType;
12214   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12215     if (!IsInitCapture)
12216       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12217     else if (isa<InitListExpr>(Init))
12218       Diag(Range.getBegin(),
12219            diag::err_init_capture_deduction_failure_from_init_list)
12220           << VN
12221           << (DeduceInit->getType().isNull() ? TSI->getType()
12222                                              : DeduceInit->getType())
12223           << DeduceInit->getSourceRange();
12224     else
12225       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12226           << VN << TSI->getType()
12227           << (DeduceInit->getType().isNull() ? TSI->getType()
12228                                              : DeduceInit->getType())
12229           << DeduceInit->getSourceRange();
12230   }
12231 
12232   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12233   // 'id' instead of a specific object type prevents most of our usual
12234   // checks.
12235   // We only want to warn outside of template instantiations, though:
12236   // inside a template, the 'id' could have come from a parameter.
12237   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12238       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12239     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12240     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12241   }
12242 
12243   return DeducedType;
12244 }
12245 
12246 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12247                                          Expr *Init) {
12248   assert(!Init || !Init->containsErrors());
12249   QualType DeducedType = deduceVarTypeFromInitializer(
12250       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12251       VDecl->getSourceRange(), DirectInit, Init);
12252   if (DeducedType.isNull()) {
12253     VDecl->setInvalidDecl();
12254     return true;
12255   }
12256 
12257   VDecl->setType(DeducedType);
12258   assert(VDecl->isLinkageValid());
12259 
12260   // In ARC, infer lifetime.
12261   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12262     VDecl->setInvalidDecl();
12263 
12264   if (getLangOpts().OpenCL)
12265     deduceOpenCLAddressSpace(VDecl);
12266 
12267   // If this is a redeclaration, check that the type we just deduced matches
12268   // the previously declared type.
12269   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12270     // We never need to merge the type, because we cannot form an incomplete
12271     // array of auto, nor deduce such a type.
12272     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12273   }
12274 
12275   // Check the deduced type is valid for a variable declaration.
12276   CheckVariableDeclarationType(VDecl);
12277   return VDecl->isInvalidDecl();
12278 }
12279 
12280 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12281                                               SourceLocation Loc) {
12282   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12283     Init = EWC->getSubExpr();
12284 
12285   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12286     Init = CE->getSubExpr();
12287 
12288   QualType InitType = Init->getType();
12289   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12290           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12291          "shouldn't be called if type doesn't have a non-trivial C struct");
12292   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12293     for (auto I : ILE->inits()) {
12294       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12295           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12296         continue;
12297       SourceLocation SL = I->getExprLoc();
12298       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12299     }
12300     return;
12301   }
12302 
12303   if (isa<ImplicitValueInitExpr>(Init)) {
12304     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12305       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12306                             NTCUK_Init);
12307   } else {
12308     // Assume all other explicit initializers involving copying some existing
12309     // object.
12310     // TODO: ignore any explicit initializers where we can guarantee
12311     // copy-elision.
12312     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12313       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12314   }
12315 }
12316 
12317 namespace {
12318 
12319 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12320   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12321   // in the source code or implicitly by the compiler if it is in a union
12322   // defined in a system header and has non-trivial ObjC ownership
12323   // qualifications. We don't want those fields to participate in determining
12324   // whether the containing union is non-trivial.
12325   return FD->hasAttr<UnavailableAttr>();
12326 }
12327 
12328 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12329     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12330                                     void> {
12331   using Super =
12332       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12333                                     void>;
12334 
12335   DiagNonTrivalCUnionDefaultInitializeVisitor(
12336       QualType OrigTy, SourceLocation OrigLoc,
12337       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12338       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12339 
12340   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12341                      const FieldDecl *FD, bool InNonTrivialUnion) {
12342     if (const auto *AT = S.Context.getAsArrayType(QT))
12343       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12344                                      InNonTrivialUnion);
12345     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12346   }
12347 
12348   void visitARCStrong(QualType QT, const FieldDecl *FD,
12349                       bool InNonTrivialUnion) {
12350     if (InNonTrivialUnion)
12351       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12352           << 1 << 0 << QT << FD->getName();
12353   }
12354 
12355   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12356     if (InNonTrivialUnion)
12357       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12358           << 1 << 0 << QT << FD->getName();
12359   }
12360 
12361   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12362     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12363     if (RD->isUnion()) {
12364       if (OrigLoc.isValid()) {
12365         bool IsUnion = false;
12366         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12367           IsUnion = OrigRD->isUnion();
12368         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12369             << 0 << OrigTy << IsUnion << UseContext;
12370         // Reset OrigLoc so that this diagnostic is emitted only once.
12371         OrigLoc = SourceLocation();
12372       }
12373       InNonTrivialUnion = true;
12374     }
12375 
12376     if (InNonTrivialUnion)
12377       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12378           << 0 << 0 << QT.getUnqualifiedType() << "";
12379 
12380     for (const FieldDecl *FD : RD->fields())
12381       if (!shouldIgnoreForRecordTriviality(FD))
12382         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12383   }
12384 
12385   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12386 
12387   // The non-trivial C union type or the struct/union type that contains a
12388   // non-trivial C union.
12389   QualType OrigTy;
12390   SourceLocation OrigLoc;
12391   Sema::NonTrivialCUnionContext UseContext;
12392   Sema &S;
12393 };
12394 
12395 struct DiagNonTrivalCUnionDestructedTypeVisitor
12396     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12397   using Super =
12398       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12399 
12400   DiagNonTrivalCUnionDestructedTypeVisitor(
12401       QualType OrigTy, SourceLocation OrigLoc,
12402       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12403       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12404 
12405   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12406                      const FieldDecl *FD, bool InNonTrivialUnion) {
12407     if (const auto *AT = S.Context.getAsArrayType(QT))
12408       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12409                                      InNonTrivialUnion);
12410     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12411   }
12412 
12413   void visitARCStrong(QualType QT, const FieldDecl *FD,
12414                       bool InNonTrivialUnion) {
12415     if (InNonTrivialUnion)
12416       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12417           << 1 << 1 << QT << FD->getName();
12418   }
12419 
12420   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12421     if (InNonTrivialUnion)
12422       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12423           << 1 << 1 << QT << FD->getName();
12424   }
12425 
12426   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12427     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12428     if (RD->isUnion()) {
12429       if (OrigLoc.isValid()) {
12430         bool IsUnion = false;
12431         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12432           IsUnion = OrigRD->isUnion();
12433         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12434             << 1 << OrigTy << IsUnion << UseContext;
12435         // Reset OrigLoc so that this diagnostic is emitted only once.
12436         OrigLoc = SourceLocation();
12437       }
12438       InNonTrivialUnion = true;
12439     }
12440 
12441     if (InNonTrivialUnion)
12442       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12443           << 0 << 1 << QT.getUnqualifiedType() << "";
12444 
12445     for (const FieldDecl *FD : RD->fields())
12446       if (!shouldIgnoreForRecordTriviality(FD))
12447         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12448   }
12449 
12450   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12451   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12452                           bool InNonTrivialUnion) {}
12453 
12454   // The non-trivial C union type or the struct/union type that contains a
12455   // non-trivial C union.
12456   QualType OrigTy;
12457   SourceLocation OrigLoc;
12458   Sema::NonTrivialCUnionContext UseContext;
12459   Sema &S;
12460 };
12461 
12462 struct DiagNonTrivalCUnionCopyVisitor
12463     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12464   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12465 
12466   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12467                                  Sema::NonTrivialCUnionContext UseContext,
12468                                  Sema &S)
12469       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12470 
12471   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12472                      const FieldDecl *FD, bool InNonTrivialUnion) {
12473     if (const auto *AT = S.Context.getAsArrayType(QT))
12474       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12475                                      InNonTrivialUnion);
12476     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12477   }
12478 
12479   void visitARCStrong(QualType QT, const FieldDecl *FD,
12480                       bool InNonTrivialUnion) {
12481     if (InNonTrivialUnion)
12482       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12483           << 1 << 2 << QT << FD->getName();
12484   }
12485 
12486   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12487     if (InNonTrivialUnion)
12488       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12489           << 1 << 2 << QT << FD->getName();
12490   }
12491 
12492   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12493     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12494     if (RD->isUnion()) {
12495       if (OrigLoc.isValid()) {
12496         bool IsUnion = false;
12497         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12498           IsUnion = OrigRD->isUnion();
12499         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12500             << 2 << OrigTy << IsUnion << UseContext;
12501         // Reset OrigLoc so that this diagnostic is emitted only once.
12502         OrigLoc = SourceLocation();
12503       }
12504       InNonTrivialUnion = true;
12505     }
12506 
12507     if (InNonTrivialUnion)
12508       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12509           << 0 << 2 << QT.getUnqualifiedType() << "";
12510 
12511     for (const FieldDecl *FD : RD->fields())
12512       if (!shouldIgnoreForRecordTriviality(FD))
12513         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12514   }
12515 
12516   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12517                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12518   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12519   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12520                             bool InNonTrivialUnion) {}
12521 
12522   // The non-trivial C union type or the struct/union type that contains a
12523   // non-trivial C union.
12524   QualType OrigTy;
12525   SourceLocation OrigLoc;
12526   Sema::NonTrivialCUnionContext UseContext;
12527   Sema &S;
12528 };
12529 
12530 } // namespace
12531 
12532 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12533                                  NonTrivialCUnionContext UseContext,
12534                                  unsigned NonTrivialKind) {
12535   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12536           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12537           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12538          "shouldn't be called if type doesn't have a non-trivial C union");
12539 
12540   if ((NonTrivialKind & NTCUK_Init) &&
12541       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12542     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12543         .visit(QT, nullptr, false);
12544   if ((NonTrivialKind & NTCUK_Destruct) &&
12545       QT.hasNonTrivialToPrimitiveDestructCUnion())
12546     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12547         .visit(QT, nullptr, false);
12548   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12549     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12550         .visit(QT, nullptr, false);
12551 }
12552 
12553 /// AddInitializerToDecl - Adds the initializer Init to the
12554 /// declaration dcl. If DirectInit is true, this is C++ direct
12555 /// initialization rather than copy initialization.
12556 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12557   // If there is no declaration, there was an error parsing it.  Just ignore
12558   // the initializer.
12559   if (!RealDecl || RealDecl->isInvalidDecl()) {
12560     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12561     return;
12562   }
12563 
12564   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12565     // Pure-specifiers are handled in ActOnPureSpecifier.
12566     Diag(Method->getLocation(), diag::err_member_function_initialization)
12567       << Method->getDeclName() << Init->getSourceRange();
12568     Method->setInvalidDecl();
12569     return;
12570   }
12571 
12572   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12573   if (!VDecl) {
12574     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12575     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12576     RealDecl->setInvalidDecl();
12577     return;
12578   }
12579 
12580   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12581   if (VDecl->getType()->isUndeducedType()) {
12582     // Attempt typo correction early so that the type of the init expression can
12583     // be deduced based on the chosen correction if the original init contains a
12584     // TypoExpr.
12585     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12586     if (!Res.isUsable()) {
12587       // There are unresolved typos in Init, just drop them.
12588       // FIXME: improve the recovery strategy to preserve the Init.
12589       RealDecl->setInvalidDecl();
12590       return;
12591     }
12592     if (Res.get()->containsErrors()) {
12593       // Invalidate the decl as we don't know the type for recovery-expr yet.
12594       RealDecl->setInvalidDecl();
12595       VDecl->setInit(Res.get());
12596       return;
12597     }
12598     Init = Res.get();
12599 
12600     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12601       return;
12602   }
12603 
12604   // dllimport cannot be used on variable definitions.
12605   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12606     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12607     VDecl->setInvalidDecl();
12608     return;
12609   }
12610 
12611   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12612     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12613     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12614     VDecl->setInvalidDecl();
12615     return;
12616   }
12617 
12618   if (!VDecl->getType()->isDependentType()) {
12619     // A definition must end up with a complete type, which means it must be
12620     // complete with the restriction that an array type might be completed by
12621     // the initializer; note that later code assumes this restriction.
12622     QualType BaseDeclType = VDecl->getType();
12623     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12624       BaseDeclType = Array->getElementType();
12625     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12626                             diag::err_typecheck_decl_incomplete_type)) {
12627       RealDecl->setInvalidDecl();
12628       return;
12629     }
12630 
12631     // The variable can not have an abstract class type.
12632     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12633                                diag::err_abstract_type_in_decl,
12634                                AbstractVariableType))
12635       VDecl->setInvalidDecl();
12636   }
12637 
12638   // If adding the initializer will turn this declaration into a definition,
12639   // and we already have a definition for this variable, diagnose or otherwise
12640   // handle the situation.
12641   if (VarDecl *Def = VDecl->getDefinition())
12642     if (Def != VDecl &&
12643         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12644         !VDecl->isThisDeclarationADemotedDefinition() &&
12645         checkVarDeclRedefinition(Def, VDecl))
12646       return;
12647 
12648   if (getLangOpts().CPlusPlus) {
12649     // C++ [class.static.data]p4
12650     //   If a static data member is of const integral or const
12651     //   enumeration type, its declaration in the class definition can
12652     //   specify a constant-initializer which shall be an integral
12653     //   constant expression (5.19). In that case, the member can appear
12654     //   in integral constant expressions. The member shall still be
12655     //   defined in a namespace scope if it is used in the program and the
12656     //   namespace scope definition shall not contain an initializer.
12657     //
12658     // We already performed a redefinition check above, but for static
12659     // data members we also need to check whether there was an in-class
12660     // declaration with an initializer.
12661     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12662       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12663           << VDecl->getDeclName();
12664       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12665            diag::note_previous_initializer)
12666           << 0;
12667       return;
12668     }
12669 
12670     if (VDecl->hasLocalStorage())
12671       setFunctionHasBranchProtectedScope();
12672 
12673     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12674       VDecl->setInvalidDecl();
12675       return;
12676     }
12677   }
12678 
12679   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12680   // a kernel function cannot be initialized."
12681   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12682     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12683     VDecl->setInvalidDecl();
12684     return;
12685   }
12686 
12687   // The LoaderUninitialized attribute acts as a definition (of undef).
12688   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12689     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12690     VDecl->setInvalidDecl();
12691     return;
12692   }
12693 
12694   // Get the decls type and save a reference for later, since
12695   // CheckInitializerTypes may change it.
12696   QualType DclT = VDecl->getType(), SavT = DclT;
12697 
12698   // Expressions default to 'id' when we're in a debugger
12699   // and we are assigning it to a variable of Objective-C pointer type.
12700   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12701       Init->getType() == Context.UnknownAnyTy) {
12702     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12703     if (Result.isInvalid()) {
12704       VDecl->setInvalidDecl();
12705       return;
12706     }
12707     Init = Result.get();
12708   }
12709 
12710   // Perform the initialization.
12711   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12712   if (!VDecl->isInvalidDecl()) {
12713     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12714     InitializationKind Kind = InitializationKind::CreateForInit(
12715         VDecl->getLocation(), DirectInit, Init);
12716 
12717     MultiExprArg Args = Init;
12718     if (CXXDirectInit)
12719       Args = MultiExprArg(CXXDirectInit->getExprs(),
12720                           CXXDirectInit->getNumExprs());
12721 
12722     // Try to correct any TypoExprs in the initialization arguments.
12723     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12724       ExprResult Res = CorrectDelayedTyposInExpr(
12725           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12726           [this, Entity, Kind](Expr *E) {
12727             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12728             return Init.Failed() ? ExprError() : E;
12729           });
12730       if (Res.isInvalid()) {
12731         VDecl->setInvalidDecl();
12732       } else if (Res.get() != Args[Idx]) {
12733         Args[Idx] = Res.get();
12734       }
12735     }
12736     if (VDecl->isInvalidDecl())
12737       return;
12738 
12739     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12740                                    /*TopLevelOfInitList=*/false,
12741                                    /*TreatUnavailableAsInvalid=*/false);
12742     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12743     if (Result.isInvalid()) {
12744       // If the provided initializer fails to initialize the var decl,
12745       // we attach a recovery expr for better recovery.
12746       auto RecoveryExpr =
12747           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12748       if (RecoveryExpr.get())
12749         VDecl->setInit(RecoveryExpr.get());
12750       return;
12751     }
12752 
12753     Init = Result.getAs<Expr>();
12754   }
12755 
12756   // Check for self-references within variable initializers.
12757   // Variables declared within a function/method body (except for references)
12758   // are handled by a dataflow analysis.
12759   // This is undefined behavior in C++, but valid in C.
12760   if (getLangOpts().CPlusPlus)
12761     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12762         VDecl->getType()->isReferenceType())
12763       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12764 
12765   // If the type changed, it means we had an incomplete type that was
12766   // completed by the initializer. For example:
12767   //   int ary[] = { 1, 3, 5 };
12768   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12769   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12770     VDecl->setType(DclT);
12771 
12772   if (!VDecl->isInvalidDecl()) {
12773     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12774 
12775     if (VDecl->hasAttr<BlocksAttr>())
12776       checkRetainCycles(VDecl, Init);
12777 
12778     // It is safe to assign a weak reference into a strong variable.
12779     // Although this code can still have problems:
12780     //   id x = self.weakProp;
12781     //   id y = self.weakProp;
12782     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12783     // paths through the function. This should be revisited if
12784     // -Wrepeated-use-of-weak is made flow-sensitive.
12785     if (FunctionScopeInfo *FSI = getCurFunction())
12786       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12787            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12788           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12789                            Init->getBeginLoc()))
12790         FSI->markSafeWeakUse(Init);
12791   }
12792 
12793   // The initialization is usually a full-expression.
12794   //
12795   // FIXME: If this is a braced initialization of an aggregate, it is not
12796   // an expression, and each individual field initializer is a separate
12797   // full-expression. For instance, in:
12798   //
12799   //   struct Temp { ~Temp(); };
12800   //   struct S { S(Temp); };
12801   //   struct T { S a, b; } t = { Temp(), Temp() }
12802   //
12803   // we should destroy the first Temp before constructing the second.
12804   ExprResult Result =
12805       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12806                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12807   if (Result.isInvalid()) {
12808     VDecl->setInvalidDecl();
12809     return;
12810   }
12811   Init = Result.get();
12812 
12813   // Attach the initializer to the decl.
12814   VDecl->setInit(Init);
12815 
12816   if (VDecl->isLocalVarDecl()) {
12817     // Don't check the initializer if the declaration is malformed.
12818     if (VDecl->isInvalidDecl()) {
12819       // do nothing
12820 
12821     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12822     // This is true even in C++ for OpenCL.
12823     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12824       CheckForConstantInitializer(Init, DclT);
12825 
12826     // Otherwise, C++ does not restrict the initializer.
12827     } else if (getLangOpts().CPlusPlus) {
12828       // do nothing
12829 
12830     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12831     // static storage duration shall be constant expressions or string literals.
12832     } else if (VDecl->getStorageClass() == SC_Static) {
12833       CheckForConstantInitializer(Init, DclT);
12834 
12835     // C89 is stricter than C99 for aggregate initializers.
12836     // C89 6.5.7p3: All the expressions [...] in an initializer list
12837     // for an object that has aggregate or union type shall be
12838     // constant expressions.
12839     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12840                isa<InitListExpr>(Init)) {
12841       const Expr *Culprit;
12842       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12843         Diag(Culprit->getExprLoc(),
12844              diag::ext_aggregate_init_not_constant)
12845           << Culprit->getSourceRange();
12846       }
12847     }
12848 
12849     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12850       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12851         if (VDecl->hasLocalStorage())
12852           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12853   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12854              VDecl->getLexicalDeclContext()->isRecord()) {
12855     // This is an in-class initialization for a static data member, e.g.,
12856     //
12857     // struct S {
12858     //   static const int value = 17;
12859     // };
12860 
12861     // C++ [class.mem]p4:
12862     //   A member-declarator can contain a constant-initializer only
12863     //   if it declares a static member (9.4) of const integral or
12864     //   const enumeration type, see 9.4.2.
12865     //
12866     // C++11 [class.static.data]p3:
12867     //   If a non-volatile non-inline const static data member is of integral
12868     //   or enumeration type, its declaration in the class definition can
12869     //   specify a brace-or-equal-initializer in which every initializer-clause
12870     //   that is an assignment-expression is a constant expression. A static
12871     //   data member of literal type can be declared in the class definition
12872     //   with the constexpr specifier; if so, its declaration shall specify a
12873     //   brace-or-equal-initializer in which every initializer-clause that is
12874     //   an assignment-expression is a constant expression.
12875 
12876     // Do nothing on dependent types.
12877     if (DclT->isDependentType()) {
12878 
12879     // Allow any 'static constexpr' members, whether or not they are of literal
12880     // type. We separately check that every constexpr variable is of literal
12881     // type.
12882     } else if (VDecl->isConstexpr()) {
12883 
12884     // Require constness.
12885     } else if (!DclT.isConstQualified()) {
12886       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12887         << Init->getSourceRange();
12888       VDecl->setInvalidDecl();
12889 
12890     // We allow integer constant expressions in all cases.
12891     } else if (DclT->isIntegralOrEnumerationType()) {
12892       // Check whether the expression is a constant expression.
12893       SourceLocation Loc;
12894       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12895         // In C++11, a non-constexpr const static data member with an
12896         // in-class initializer cannot be volatile.
12897         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12898       else if (Init->isValueDependent())
12899         ; // Nothing to check.
12900       else if (Init->isIntegerConstantExpr(Context, &Loc))
12901         ; // Ok, it's an ICE!
12902       else if (Init->getType()->isScopedEnumeralType() &&
12903                Init->isCXX11ConstantExpr(Context))
12904         ; // Ok, it is a scoped-enum constant expression.
12905       else if (Init->isEvaluatable(Context)) {
12906         // If we can constant fold the initializer through heroics, accept it,
12907         // but report this as a use of an extension for -pedantic.
12908         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12909           << Init->getSourceRange();
12910       } else {
12911         // Otherwise, this is some crazy unknown case.  Report the issue at the
12912         // location provided by the isIntegerConstantExpr failed check.
12913         Diag(Loc, diag::err_in_class_initializer_non_constant)
12914           << Init->getSourceRange();
12915         VDecl->setInvalidDecl();
12916       }
12917 
12918     // We allow foldable floating-point constants as an extension.
12919     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12920       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12921       // it anyway and provide a fixit to add the 'constexpr'.
12922       if (getLangOpts().CPlusPlus11) {
12923         Diag(VDecl->getLocation(),
12924              diag::ext_in_class_initializer_float_type_cxx11)
12925             << DclT << Init->getSourceRange();
12926         Diag(VDecl->getBeginLoc(),
12927              diag::note_in_class_initializer_float_type_cxx11)
12928             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12929       } else {
12930         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12931           << DclT << Init->getSourceRange();
12932 
12933         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12934           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12935             << Init->getSourceRange();
12936           VDecl->setInvalidDecl();
12937         }
12938       }
12939 
12940     // Suggest adding 'constexpr' in C++11 for literal types.
12941     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12942       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12943           << DclT << Init->getSourceRange()
12944           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12945       VDecl->setConstexpr(true);
12946 
12947     } else {
12948       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12949         << DclT << Init->getSourceRange();
12950       VDecl->setInvalidDecl();
12951     }
12952   } else if (VDecl->isFileVarDecl()) {
12953     // In C, extern is typically used to avoid tentative definitions when
12954     // declaring variables in headers, but adding an intializer makes it a
12955     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12956     // In C++, extern is often used to give implictly static const variables
12957     // external linkage, so don't warn in that case. If selectany is present,
12958     // this might be header code intended for C and C++ inclusion, so apply the
12959     // C++ rules.
12960     if (VDecl->getStorageClass() == SC_Extern &&
12961         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12962          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12963         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12964         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12965       Diag(VDecl->getLocation(), diag::warn_extern_init);
12966 
12967     // In Microsoft C++ mode, a const variable defined in namespace scope has
12968     // external linkage by default if the variable is declared with
12969     // __declspec(dllexport).
12970     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12971         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12972         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12973       VDecl->setStorageClass(SC_Extern);
12974 
12975     // C99 6.7.8p4. All file scoped initializers need to be constant.
12976     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12977       CheckForConstantInitializer(Init, DclT);
12978   }
12979 
12980   QualType InitType = Init->getType();
12981   if (!InitType.isNull() &&
12982       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12983        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12984     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12985 
12986   // We will represent direct-initialization similarly to copy-initialization:
12987   //    int x(1);  -as-> int x = 1;
12988   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12989   //
12990   // Clients that want to distinguish between the two forms, can check for
12991   // direct initializer using VarDecl::getInitStyle().
12992   // A major benefit is that clients that don't particularly care about which
12993   // exactly form was it (like the CodeGen) can handle both cases without
12994   // special case code.
12995 
12996   // C++ 8.5p11:
12997   // The form of initialization (using parentheses or '=') is generally
12998   // insignificant, but does matter when the entity being initialized has a
12999   // class type.
13000   if (CXXDirectInit) {
13001     assert(DirectInit && "Call-style initializer must be direct init.");
13002     VDecl->setInitStyle(VarDecl::CallInit);
13003   } else if (DirectInit) {
13004     // This must be list-initialization. No other way is direct-initialization.
13005     VDecl->setInitStyle(VarDecl::ListInit);
13006   }
13007 
13008   if (LangOpts.OpenMP &&
13009       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13010       VDecl->isFileVarDecl())
13011     DeclsToCheckForDeferredDiags.insert(VDecl);
13012   CheckCompleteVariableDeclaration(VDecl);
13013 }
13014 
13015 /// ActOnInitializerError - Given that there was an error parsing an
13016 /// initializer for the given declaration, try to at least re-establish
13017 /// invariants such as whether a variable's type is either dependent or
13018 /// complete.
13019 void Sema::ActOnInitializerError(Decl *D) {
13020   // Our main concern here is re-establishing invariants like "a
13021   // variable's type is either dependent or complete".
13022   if (!D || D->isInvalidDecl()) return;
13023 
13024   VarDecl *VD = dyn_cast<VarDecl>(D);
13025   if (!VD) return;
13026 
13027   // Bindings are not usable if we can't make sense of the initializer.
13028   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13029     for (auto *BD : DD->bindings())
13030       BD->setInvalidDecl();
13031 
13032   // Auto types are meaningless if we can't make sense of the initializer.
13033   if (VD->getType()->isUndeducedType()) {
13034     D->setInvalidDecl();
13035     return;
13036   }
13037 
13038   QualType Ty = VD->getType();
13039   if (Ty->isDependentType()) return;
13040 
13041   // Require a complete type.
13042   if (RequireCompleteType(VD->getLocation(),
13043                           Context.getBaseElementType(Ty),
13044                           diag::err_typecheck_decl_incomplete_type)) {
13045     VD->setInvalidDecl();
13046     return;
13047   }
13048 
13049   // Require a non-abstract type.
13050   if (RequireNonAbstractType(VD->getLocation(), Ty,
13051                              diag::err_abstract_type_in_decl,
13052                              AbstractVariableType)) {
13053     VD->setInvalidDecl();
13054     return;
13055   }
13056 
13057   // Don't bother complaining about constructors or destructors,
13058   // though.
13059 }
13060 
13061 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13062   // If there is no declaration, there was an error parsing it. Just ignore it.
13063   if (!RealDecl)
13064     return;
13065 
13066   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13067     QualType Type = Var->getType();
13068 
13069     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13070     if (isa<DecompositionDecl>(RealDecl)) {
13071       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13072       Var->setInvalidDecl();
13073       return;
13074     }
13075 
13076     if (Type->isUndeducedType() &&
13077         DeduceVariableDeclarationType(Var, false, nullptr))
13078       return;
13079 
13080     // C++11 [class.static.data]p3: A static data member can be declared with
13081     // the constexpr specifier; if so, its declaration shall specify
13082     // a brace-or-equal-initializer.
13083     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13084     // the definition of a variable [...] or the declaration of a static data
13085     // member.
13086     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13087         !Var->isThisDeclarationADemotedDefinition()) {
13088       if (Var->isStaticDataMember()) {
13089         // C++1z removes the relevant rule; the in-class declaration is always
13090         // a definition there.
13091         if (!getLangOpts().CPlusPlus17 &&
13092             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13093           Diag(Var->getLocation(),
13094                diag::err_constexpr_static_mem_var_requires_init)
13095               << Var;
13096           Var->setInvalidDecl();
13097           return;
13098         }
13099       } else {
13100         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13101         Var->setInvalidDecl();
13102         return;
13103       }
13104     }
13105 
13106     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13107     // be initialized.
13108     if (!Var->isInvalidDecl() &&
13109         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13110         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13111       bool HasConstExprDefaultConstructor = false;
13112       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13113         for (auto *Ctor : RD->ctors()) {
13114           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13115               Ctor->getMethodQualifiers().getAddressSpace() ==
13116                   LangAS::opencl_constant) {
13117             HasConstExprDefaultConstructor = true;
13118           }
13119         }
13120       }
13121       if (!HasConstExprDefaultConstructor) {
13122         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13123         Var->setInvalidDecl();
13124         return;
13125       }
13126     }
13127 
13128     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13129       if (Var->getStorageClass() == SC_Extern) {
13130         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13131             << Var;
13132         Var->setInvalidDecl();
13133         return;
13134       }
13135       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13136                               diag::err_typecheck_decl_incomplete_type)) {
13137         Var->setInvalidDecl();
13138         return;
13139       }
13140       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13141         if (!RD->hasTrivialDefaultConstructor()) {
13142           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13143           Var->setInvalidDecl();
13144           return;
13145         }
13146       }
13147       // The declaration is unitialized, no need for further checks.
13148       return;
13149     }
13150 
13151     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13152     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13153         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13154       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13155                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13156 
13157 
13158     switch (DefKind) {
13159     case VarDecl::Definition:
13160       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13161         break;
13162 
13163       // We have an out-of-line definition of a static data member
13164       // that has an in-class initializer, so we type-check this like
13165       // a declaration.
13166       //
13167       LLVM_FALLTHROUGH;
13168 
13169     case VarDecl::DeclarationOnly:
13170       // It's only a declaration.
13171 
13172       // Block scope. C99 6.7p7: If an identifier for an object is
13173       // declared with no linkage (C99 6.2.2p6), the type for the
13174       // object shall be complete.
13175       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13176           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13177           RequireCompleteType(Var->getLocation(), Type,
13178                               diag::err_typecheck_decl_incomplete_type))
13179         Var->setInvalidDecl();
13180 
13181       // Make sure that the type is not abstract.
13182       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13183           RequireNonAbstractType(Var->getLocation(), Type,
13184                                  diag::err_abstract_type_in_decl,
13185                                  AbstractVariableType))
13186         Var->setInvalidDecl();
13187       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13188           Var->getStorageClass() == SC_PrivateExtern) {
13189         Diag(Var->getLocation(), diag::warn_private_extern);
13190         Diag(Var->getLocation(), diag::note_private_extern);
13191       }
13192 
13193       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13194           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13195         ExternalDeclarations.push_back(Var);
13196 
13197       return;
13198 
13199     case VarDecl::TentativeDefinition:
13200       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13201       // object that has file scope without an initializer, and without a
13202       // storage-class specifier or with the storage-class specifier "static",
13203       // constitutes a tentative definition. Note: A tentative definition with
13204       // external linkage is valid (C99 6.2.2p5).
13205       if (!Var->isInvalidDecl()) {
13206         if (const IncompleteArrayType *ArrayT
13207                                     = Context.getAsIncompleteArrayType(Type)) {
13208           if (RequireCompleteSizedType(
13209                   Var->getLocation(), ArrayT->getElementType(),
13210                   diag::err_array_incomplete_or_sizeless_type))
13211             Var->setInvalidDecl();
13212         } else if (Var->getStorageClass() == SC_Static) {
13213           // C99 6.9.2p3: If the declaration of an identifier for an object is
13214           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13215           // declared type shall not be an incomplete type.
13216           // NOTE: code such as the following
13217           //     static struct s;
13218           //     struct s { int a; };
13219           // is accepted by gcc. Hence here we issue a warning instead of
13220           // an error and we do not invalidate the static declaration.
13221           // NOTE: to avoid multiple warnings, only check the first declaration.
13222           if (Var->isFirstDecl())
13223             RequireCompleteType(Var->getLocation(), Type,
13224                                 diag::ext_typecheck_decl_incomplete_type);
13225         }
13226       }
13227 
13228       // Record the tentative definition; we're done.
13229       if (!Var->isInvalidDecl())
13230         TentativeDefinitions.push_back(Var);
13231       return;
13232     }
13233 
13234     // Provide a specific diagnostic for uninitialized variable
13235     // definitions with incomplete array type.
13236     if (Type->isIncompleteArrayType()) {
13237       Diag(Var->getLocation(),
13238            diag::err_typecheck_incomplete_array_needs_initializer);
13239       Var->setInvalidDecl();
13240       return;
13241     }
13242 
13243     // Provide a specific diagnostic for uninitialized variable
13244     // definitions with reference type.
13245     if (Type->isReferenceType()) {
13246       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13247           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13248       return;
13249     }
13250 
13251     // Do not attempt to type-check the default initializer for a
13252     // variable with dependent type.
13253     if (Type->isDependentType())
13254       return;
13255 
13256     if (Var->isInvalidDecl())
13257       return;
13258 
13259     if (!Var->hasAttr<AliasAttr>()) {
13260       if (RequireCompleteType(Var->getLocation(),
13261                               Context.getBaseElementType(Type),
13262                               diag::err_typecheck_decl_incomplete_type)) {
13263         Var->setInvalidDecl();
13264         return;
13265       }
13266     } else {
13267       return;
13268     }
13269 
13270     // The variable can not have an abstract class type.
13271     if (RequireNonAbstractType(Var->getLocation(), Type,
13272                                diag::err_abstract_type_in_decl,
13273                                AbstractVariableType)) {
13274       Var->setInvalidDecl();
13275       return;
13276     }
13277 
13278     // Check for jumps past the implicit initializer.  C++0x
13279     // clarifies that this applies to a "variable with automatic
13280     // storage duration", not a "local variable".
13281     // C++11 [stmt.dcl]p3
13282     //   A program that jumps from a point where a variable with automatic
13283     //   storage duration is not in scope to a point where it is in scope is
13284     //   ill-formed unless the variable has scalar type, class type with a
13285     //   trivial default constructor and a trivial destructor, a cv-qualified
13286     //   version of one of these types, or an array of one of the preceding
13287     //   types and is declared without an initializer.
13288     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13289       if (const RecordType *Record
13290             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13291         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13292         // Mark the function (if we're in one) for further checking even if the
13293         // looser rules of C++11 do not require such checks, so that we can
13294         // diagnose incompatibilities with C++98.
13295         if (!CXXRecord->isPOD())
13296           setFunctionHasBranchProtectedScope();
13297       }
13298     }
13299     // In OpenCL, we can't initialize objects in the __local address space,
13300     // even implicitly, so don't synthesize an implicit initializer.
13301     if (getLangOpts().OpenCL &&
13302         Var->getType().getAddressSpace() == LangAS::opencl_local)
13303       return;
13304     // C++03 [dcl.init]p9:
13305     //   If no initializer is specified for an object, and the
13306     //   object is of (possibly cv-qualified) non-POD class type (or
13307     //   array thereof), the object shall be default-initialized; if
13308     //   the object is of const-qualified type, the underlying class
13309     //   type shall have a user-declared default
13310     //   constructor. Otherwise, if no initializer is specified for
13311     //   a non- static object, the object and its subobjects, if
13312     //   any, have an indeterminate initial value); if the object
13313     //   or any of its subobjects are of const-qualified type, the
13314     //   program is ill-formed.
13315     // C++0x [dcl.init]p11:
13316     //   If no initializer is specified for an object, the object is
13317     //   default-initialized; [...].
13318     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13319     InitializationKind Kind
13320       = InitializationKind::CreateDefault(Var->getLocation());
13321 
13322     InitializationSequence InitSeq(*this, Entity, Kind, None);
13323     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13324 
13325     if (Init.get()) {
13326       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13327       // This is important for template substitution.
13328       Var->setInitStyle(VarDecl::CallInit);
13329     } else if (Init.isInvalid()) {
13330       // If default-init fails, attach a recovery-expr initializer to track
13331       // that initialization was attempted and failed.
13332       auto RecoveryExpr =
13333           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13334       if (RecoveryExpr.get())
13335         Var->setInit(RecoveryExpr.get());
13336     }
13337 
13338     CheckCompleteVariableDeclaration(Var);
13339   }
13340 }
13341 
13342 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13343   // If there is no declaration, there was an error parsing it. Ignore it.
13344   if (!D)
13345     return;
13346 
13347   VarDecl *VD = dyn_cast<VarDecl>(D);
13348   if (!VD) {
13349     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13350     D->setInvalidDecl();
13351     return;
13352   }
13353 
13354   VD->setCXXForRangeDecl(true);
13355 
13356   // for-range-declaration cannot be given a storage class specifier.
13357   int Error = -1;
13358   switch (VD->getStorageClass()) {
13359   case SC_None:
13360     break;
13361   case SC_Extern:
13362     Error = 0;
13363     break;
13364   case SC_Static:
13365     Error = 1;
13366     break;
13367   case SC_PrivateExtern:
13368     Error = 2;
13369     break;
13370   case SC_Auto:
13371     Error = 3;
13372     break;
13373   case SC_Register:
13374     Error = 4;
13375     break;
13376   }
13377 
13378   // for-range-declaration cannot be given a storage class specifier con't.
13379   switch (VD->getTSCSpec()) {
13380   case TSCS_thread_local:
13381     Error = 6;
13382     break;
13383   case TSCS___thread:
13384   case TSCS__Thread_local:
13385   case TSCS_unspecified:
13386     break;
13387   }
13388 
13389   if (Error != -1) {
13390     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13391         << VD << Error;
13392     D->setInvalidDecl();
13393   }
13394 }
13395 
13396 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13397                                             IdentifierInfo *Ident,
13398                                             ParsedAttributes &Attrs) {
13399   // C++1y [stmt.iter]p1:
13400   //   A range-based for statement of the form
13401   //      for ( for-range-identifier : for-range-initializer ) statement
13402   //   is equivalent to
13403   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13404   DeclSpec DS(Attrs.getPool().getFactory());
13405 
13406   const char *PrevSpec;
13407   unsigned DiagID;
13408   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13409                      getPrintingPolicy());
13410 
13411   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13412   D.SetIdentifier(Ident, IdentLoc);
13413   D.takeAttributes(Attrs);
13414 
13415   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13416                 IdentLoc);
13417   Decl *Var = ActOnDeclarator(S, D);
13418   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13419   FinalizeDeclaration(Var);
13420   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13421                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13422                                                       : IdentLoc);
13423 }
13424 
13425 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13426   if (var->isInvalidDecl()) return;
13427 
13428   MaybeAddCUDAConstantAttr(var);
13429 
13430   if (getLangOpts().OpenCL) {
13431     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13432     // initialiser
13433     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13434         !var->hasInit()) {
13435       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13436           << 1 /*Init*/;
13437       var->setInvalidDecl();
13438       return;
13439     }
13440   }
13441 
13442   // In Objective-C, don't allow jumps past the implicit initialization of a
13443   // local retaining variable.
13444   if (getLangOpts().ObjC &&
13445       var->hasLocalStorage()) {
13446     switch (var->getType().getObjCLifetime()) {
13447     case Qualifiers::OCL_None:
13448     case Qualifiers::OCL_ExplicitNone:
13449     case Qualifiers::OCL_Autoreleasing:
13450       break;
13451 
13452     case Qualifiers::OCL_Weak:
13453     case Qualifiers::OCL_Strong:
13454       setFunctionHasBranchProtectedScope();
13455       break;
13456     }
13457   }
13458 
13459   if (var->hasLocalStorage() &&
13460       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13461     setFunctionHasBranchProtectedScope();
13462 
13463   // Warn about externally-visible variables being defined without a
13464   // prior declaration.  We only want to do this for global
13465   // declarations, but we also specifically need to avoid doing it for
13466   // class members because the linkage of an anonymous class can
13467   // change if it's later given a typedef name.
13468   if (var->isThisDeclarationADefinition() &&
13469       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13470       var->isExternallyVisible() && var->hasLinkage() &&
13471       !var->isInline() && !var->getDescribedVarTemplate() &&
13472       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13473       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13474       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13475                                   var->getLocation())) {
13476     // Find a previous declaration that's not a definition.
13477     VarDecl *prev = var->getPreviousDecl();
13478     while (prev && prev->isThisDeclarationADefinition())
13479       prev = prev->getPreviousDecl();
13480 
13481     if (!prev) {
13482       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13483       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13484           << /* variable */ 0;
13485     }
13486   }
13487 
13488   // Cache the result of checking for constant initialization.
13489   Optional<bool> CacheHasConstInit;
13490   const Expr *CacheCulprit = nullptr;
13491   auto checkConstInit = [&]() mutable {
13492     if (!CacheHasConstInit)
13493       CacheHasConstInit = var->getInit()->isConstantInitializer(
13494             Context, var->getType()->isReferenceType(), &CacheCulprit);
13495     return *CacheHasConstInit;
13496   };
13497 
13498   if (var->getTLSKind() == VarDecl::TLS_Static) {
13499     if (var->getType().isDestructedType()) {
13500       // GNU C++98 edits for __thread, [basic.start.term]p3:
13501       //   The type of an object with thread storage duration shall not
13502       //   have a non-trivial destructor.
13503       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13504       if (getLangOpts().CPlusPlus11)
13505         Diag(var->getLocation(), diag::note_use_thread_local);
13506     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13507       if (!checkConstInit()) {
13508         // GNU C++98 edits for __thread, [basic.start.init]p4:
13509         //   An object of thread storage duration shall not require dynamic
13510         //   initialization.
13511         // FIXME: Need strict checking here.
13512         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13513           << CacheCulprit->getSourceRange();
13514         if (getLangOpts().CPlusPlus11)
13515           Diag(var->getLocation(), diag::note_use_thread_local);
13516       }
13517     }
13518   }
13519 
13520 
13521   if (!var->getType()->isStructureType() && var->hasInit() &&
13522       isa<InitListExpr>(var->getInit())) {
13523     const auto *ILE = cast<InitListExpr>(var->getInit());
13524     unsigned NumInits = ILE->getNumInits();
13525     if (NumInits > 2)
13526       for (unsigned I = 0; I < NumInits; ++I) {
13527         const auto *Init = ILE->getInit(I);
13528         if (!Init)
13529           break;
13530         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13531         if (!SL)
13532           break;
13533 
13534         unsigned NumConcat = SL->getNumConcatenated();
13535         // Diagnose missing comma in string array initialization.
13536         // Do not warn when all the elements in the initializer are concatenated
13537         // together. Do not warn for macros too.
13538         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13539           bool OnlyOneMissingComma = true;
13540           for (unsigned J = I + 1; J < NumInits; ++J) {
13541             const auto *Init = ILE->getInit(J);
13542             if (!Init)
13543               break;
13544             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13545             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13546               OnlyOneMissingComma = false;
13547               break;
13548             }
13549           }
13550 
13551           if (OnlyOneMissingComma) {
13552             SmallVector<FixItHint, 1> Hints;
13553             for (unsigned i = 0; i < NumConcat - 1; ++i)
13554               Hints.push_back(FixItHint::CreateInsertion(
13555                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13556 
13557             Diag(SL->getStrTokenLoc(1),
13558                  diag::warn_concatenated_literal_array_init)
13559                 << Hints;
13560             Diag(SL->getBeginLoc(),
13561                  diag::note_concatenated_string_literal_silence);
13562           }
13563           // In any case, stop now.
13564           break;
13565         }
13566       }
13567   }
13568 
13569 
13570   QualType type = var->getType();
13571 
13572   if (var->hasAttr<BlocksAttr>())
13573     getCurFunction()->addByrefBlockVar(var);
13574 
13575   Expr *Init = var->getInit();
13576   bool GlobalStorage = var->hasGlobalStorage();
13577   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13578   QualType baseType = Context.getBaseElementType(type);
13579   bool HasConstInit = true;
13580 
13581   // Check whether the initializer is sufficiently constant.
13582   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13583       !Init->isValueDependent() &&
13584       (GlobalStorage || var->isConstexpr() ||
13585        var->mightBeUsableInConstantExpressions(Context))) {
13586     // If this variable might have a constant initializer or might be usable in
13587     // constant expressions, check whether or not it actually is now.  We can't
13588     // do this lazily, because the result might depend on things that change
13589     // later, such as which constexpr functions happen to be defined.
13590     SmallVector<PartialDiagnosticAt, 8> Notes;
13591     if (!getLangOpts().CPlusPlus11) {
13592       // Prior to C++11, in contexts where a constant initializer is required,
13593       // the set of valid constant initializers is described by syntactic rules
13594       // in [expr.const]p2-6.
13595       // FIXME: Stricter checking for these rules would be useful for constinit /
13596       // -Wglobal-constructors.
13597       HasConstInit = checkConstInit();
13598 
13599       // Compute and cache the constant value, and remember that we have a
13600       // constant initializer.
13601       if (HasConstInit) {
13602         (void)var->checkForConstantInitialization(Notes);
13603         Notes.clear();
13604       } else if (CacheCulprit) {
13605         Notes.emplace_back(CacheCulprit->getExprLoc(),
13606                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13607         Notes.back().second << CacheCulprit->getSourceRange();
13608       }
13609     } else {
13610       // Evaluate the initializer to see if it's a constant initializer.
13611       HasConstInit = var->checkForConstantInitialization(Notes);
13612     }
13613 
13614     if (HasConstInit) {
13615       // FIXME: Consider replacing the initializer with a ConstantExpr.
13616     } else if (var->isConstexpr()) {
13617       SourceLocation DiagLoc = var->getLocation();
13618       // If the note doesn't add any useful information other than a source
13619       // location, fold it into the primary diagnostic.
13620       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13621                                    diag::note_invalid_subexpr_in_const_expr) {
13622         DiagLoc = Notes[0].first;
13623         Notes.clear();
13624       }
13625       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13626           << var << Init->getSourceRange();
13627       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13628         Diag(Notes[I].first, Notes[I].second);
13629     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13630       auto *Attr = var->getAttr<ConstInitAttr>();
13631       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13632           << Init->getSourceRange();
13633       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13634           << Attr->getRange() << Attr->isConstinit();
13635       for (auto &it : Notes)
13636         Diag(it.first, it.second);
13637     } else if (IsGlobal &&
13638                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13639                                            var->getLocation())) {
13640       // Warn about globals which don't have a constant initializer.  Don't
13641       // warn about globals with a non-trivial destructor because we already
13642       // warned about them.
13643       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13644       if (!(RD && !RD->hasTrivialDestructor())) {
13645         // checkConstInit() here permits trivial default initialization even in
13646         // C++11 onwards, where such an initializer is not a constant initializer
13647         // but nonetheless doesn't require a global constructor.
13648         if (!checkConstInit())
13649           Diag(var->getLocation(), diag::warn_global_constructor)
13650               << Init->getSourceRange();
13651       }
13652     }
13653   }
13654 
13655   // Apply section attributes and pragmas to global variables.
13656   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13657       !inTemplateInstantiation()) {
13658     PragmaStack<StringLiteral *> *Stack = nullptr;
13659     int SectionFlags = ASTContext::PSF_Read;
13660     if (var->getType().isConstQualified()) {
13661       if (HasConstInit)
13662         Stack = &ConstSegStack;
13663       else {
13664         Stack = &BSSSegStack;
13665         SectionFlags |= ASTContext::PSF_Write;
13666       }
13667     } else if (var->hasInit() && HasConstInit) {
13668       Stack = &DataSegStack;
13669       SectionFlags |= ASTContext::PSF_Write;
13670     } else {
13671       Stack = &BSSSegStack;
13672       SectionFlags |= ASTContext::PSF_Write;
13673     }
13674     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13675       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13676         SectionFlags |= ASTContext::PSF_Implicit;
13677       UnifySection(SA->getName(), SectionFlags, var);
13678     } else if (Stack->CurrentValue) {
13679       SectionFlags |= ASTContext::PSF_Implicit;
13680       auto SectionName = Stack->CurrentValue->getString();
13681       var->addAttr(SectionAttr::CreateImplicit(
13682           Context, SectionName, Stack->CurrentPragmaLocation,
13683           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13684       if (UnifySection(SectionName, SectionFlags, var))
13685         var->dropAttr<SectionAttr>();
13686     }
13687 
13688     // Apply the init_seg attribute if this has an initializer.  If the
13689     // initializer turns out to not be dynamic, we'll end up ignoring this
13690     // attribute.
13691     if (CurInitSeg && var->getInit())
13692       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13693                                                CurInitSegLoc,
13694                                                AttributeCommonInfo::AS_Pragma));
13695   }
13696 
13697   // All the following checks are C++ only.
13698   if (!getLangOpts().CPlusPlus) {
13699     // If this variable must be emitted, add it as an initializer for the
13700     // current module.
13701     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13702       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13703     return;
13704   }
13705 
13706   // Require the destructor.
13707   if (!type->isDependentType())
13708     if (const RecordType *recordType = baseType->getAs<RecordType>())
13709       FinalizeVarWithDestructor(var, recordType);
13710 
13711   // If this variable must be emitted, add it as an initializer for the current
13712   // module.
13713   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13714     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13715 
13716   // Build the bindings if this is a structured binding declaration.
13717   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13718     CheckCompleteDecompositionDeclaration(DD);
13719 }
13720 
13721 /// Check if VD needs to be dllexport/dllimport due to being in a
13722 /// dllexport/import function.
13723 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13724   assert(VD->isStaticLocal());
13725 
13726   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13727 
13728   // Find outermost function when VD is in lambda function.
13729   while (FD && !getDLLAttr(FD) &&
13730          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13731          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13732     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13733   }
13734 
13735   if (!FD)
13736     return;
13737 
13738   // Static locals inherit dll attributes from their function.
13739   if (Attr *A = getDLLAttr(FD)) {
13740     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13741     NewAttr->setInherited(true);
13742     VD->addAttr(NewAttr);
13743   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13744     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13745     NewAttr->setInherited(true);
13746     VD->addAttr(NewAttr);
13747 
13748     // Export this function to enforce exporting this static variable even
13749     // if it is not used in this compilation unit.
13750     if (!FD->hasAttr<DLLExportAttr>())
13751       FD->addAttr(NewAttr);
13752 
13753   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13754     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13755     NewAttr->setInherited(true);
13756     VD->addAttr(NewAttr);
13757   }
13758 }
13759 
13760 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13761 /// any semantic actions necessary after any initializer has been attached.
13762 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13763   // Note that we are no longer parsing the initializer for this declaration.
13764   ParsingInitForAutoVars.erase(ThisDecl);
13765 
13766   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13767   if (!VD)
13768     return;
13769 
13770   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13771   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13772       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13773     if (PragmaClangBSSSection.Valid)
13774       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13775           Context, PragmaClangBSSSection.SectionName,
13776           PragmaClangBSSSection.PragmaLocation,
13777           AttributeCommonInfo::AS_Pragma));
13778     if (PragmaClangDataSection.Valid)
13779       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13780           Context, PragmaClangDataSection.SectionName,
13781           PragmaClangDataSection.PragmaLocation,
13782           AttributeCommonInfo::AS_Pragma));
13783     if (PragmaClangRodataSection.Valid)
13784       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13785           Context, PragmaClangRodataSection.SectionName,
13786           PragmaClangRodataSection.PragmaLocation,
13787           AttributeCommonInfo::AS_Pragma));
13788     if (PragmaClangRelroSection.Valid)
13789       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13790           Context, PragmaClangRelroSection.SectionName,
13791           PragmaClangRelroSection.PragmaLocation,
13792           AttributeCommonInfo::AS_Pragma));
13793   }
13794 
13795   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13796     for (auto *BD : DD->bindings()) {
13797       FinalizeDeclaration(BD);
13798     }
13799   }
13800 
13801   checkAttributesAfterMerging(*this, *VD);
13802 
13803   // Perform TLS alignment check here after attributes attached to the variable
13804   // which may affect the alignment have been processed. Only perform the check
13805   // if the target has a maximum TLS alignment (zero means no constraints).
13806   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13807     // Protect the check so that it's not performed on dependent types and
13808     // dependent alignments (we can't determine the alignment in that case).
13809     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13810       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13811       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13812         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13813           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13814           << (unsigned)MaxAlignChars.getQuantity();
13815       }
13816     }
13817   }
13818 
13819   if (VD->isStaticLocal())
13820     CheckStaticLocalForDllExport(VD);
13821 
13822   // Perform check for initializers of device-side global variables.
13823   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13824   // 7.5). We must also apply the same checks to all __shared__
13825   // variables whether they are local or not. CUDA also allows
13826   // constant initializers for __constant__ and __device__ variables.
13827   if (getLangOpts().CUDA)
13828     checkAllowedCUDAInitializer(VD);
13829 
13830   // Grab the dllimport or dllexport attribute off of the VarDecl.
13831   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13832 
13833   // Imported static data members cannot be defined out-of-line.
13834   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13835     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13836         VD->isThisDeclarationADefinition()) {
13837       // We allow definitions of dllimport class template static data members
13838       // with a warning.
13839       CXXRecordDecl *Context =
13840         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13841       bool IsClassTemplateMember =
13842           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13843           Context->getDescribedClassTemplate();
13844 
13845       Diag(VD->getLocation(),
13846            IsClassTemplateMember
13847                ? diag::warn_attribute_dllimport_static_field_definition
13848                : diag::err_attribute_dllimport_static_field_definition);
13849       Diag(IA->getLocation(), diag::note_attribute);
13850       if (!IsClassTemplateMember)
13851         VD->setInvalidDecl();
13852     }
13853   }
13854 
13855   // dllimport/dllexport variables cannot be thread local, their TLS index
13856   // isn't exported with the variable.
13857   if (DLLAttr && VD->getTLSKind()) {
13858     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13859     if (F && getDLLAttr(F)) {
13860       assert(VD->isStaticLocal());
13861       // But if this is a static local in a dlimport/dllexport function, the
13862       // function will never be inlined, which means the var would never be
13863       // imported, so having it marked import/export is safe.
13864     } else {
13865       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13866                                                                     << DLLAttr;
13867       VD->setInvalidDecl();
13868     }
13869   }
13870 
13871   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13872     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13873       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13874           << Attr;
13875       VD->dropAttr<UsedAttr>();
13876     }
13877   }
13878   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13879     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13880       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13881           << Attr;
13882       VD->dropAttr<RetainAttr>();
13883     }
13884   }
13885 
13886   const DeclContext *DC = VD->getDeclContext();
13887   // If there's a #pragma GCC visibility in scope, and this isn't a class
13888   // member, set the visibility of this variable.
13889   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13890     AddPushedVisibilityAttribute(VD);
13891 
13892   // FIXME: Warn on unused var template partial specializations.
13893   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13894     MarkUnusedFileScopedDecl(VD);
13895 
13896   // Now we have parsed the initializer and can update the table of magic
13897   // tag values.
13898   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13899       !VD->getType()->isIntegralOrEnumerationType())
13900     return;
13901 
13902   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13903     const Expr *MagicValueExpr = VD->getInit();
13904     if (!MagicValueExpr) {
13905       continue;
13906     }
13907     Optional<llvm::APSInt> MagicValueInt;
13908     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13909       Diag(I->getRange().getBegin(),
13910            diag::err_type_tag_for_datatype_not_ice)
13911         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13912       continue;
13913     }
13914     if (MagicValueInt->getActiveBits() > 64) {
13915       Diag(I->getRange().getBegin(),
13916            diag::err_type_tag_for_datatype_too_large)
13917         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13918       continue;
13919     }
13920     uint64_t MagicValue = MagicValueInt->getZExtValue();
13921     RegisterTypeTagForDatatype(I->getArgumentKind(),
13922                                MagicValue,
13923                                I->getMatchingCType(),
13924                                I->getLayoutCompatible(),
13925                                I->getMustBeNull());
13926   }
13927 }
13928 
13929 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13930   auto *VD = dyn_cast<VarDecl>(DD);
13931   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13932 }
13933 
13934 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13935                                                    ArrayRef<Decl *> Group) {
13936   SmallVector<Decl*, 8> Decls;
13937 
13938   if (DS.isTypeSpecOwned())
13939     Decls.push_back(DS.getRepAsDecl());
13940 
13941   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13942   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13943   bool DiagnosedMultipleDecomps = false;
13944   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13945   bool DiagnosedNonDeducedAuto = false;
13946 
13947   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13948     if (Decl *D = Group[i]) {
13949       // For declarators, there are some additional syntactic-ish checks we need
13950       // to perform.
13951       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13952         if (!FirstDeclaratorInGroup)
13953           FirstDeclaratorInGroup = DD;
13954         if (!FirstDecompDeclaratorInGroup)
13955           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13956         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13957             !hasDeducedAuto(DD))
13958           FirstNonDeducedAutoInGroup = DD;
13959 
13960         if (FirstDeclaratorInGroup != DD) {
13961           // A decomposition declaration cannot be combined with any other
13962           // declaration in the same group.
13963           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13964             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13965                  diag::err_decomp_decl_not_alone)
13966                 << FirstDeclaratorInGroup->getSourceRange()
13967                 << DD->getSourceRange();
13968             DiagnosedMultipleDecomps = true;
13969           }
13970 
13971           // A declarator that uses 'auto' in any way other than to declare a
13972           // variable with a deduced type cannot be combined with any other
13973           // declarator in the same group.
13974           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13975             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13976                  diag::err_auto_non_deduced_not_alone)
13977                 << FirstNonDeducedAutoInGroup->getType()
13978                        ->hasAutoForTrailingReturnType()
13979                 << FirstDeclaratorInGroup->getSourceRange()
13980                 << DD->getSourceRange();
13981             DiagnosedNonDeducedAuto = true;
13982           }
13983         }
13984       }
13985 
13986       Decls.push_back(D);
13987     }
13988   }
13989 
13990   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13991     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13992       handleTagNumbering(Tag, S);
13993       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13994           getLangOpts().CPlusPlus)
13995         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13996     }
13997   }
13998 
13999   return BuildDeclaratorGroup(Decls);
14000 }
14001 
14002 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14003 /// group, performing any necessary semantic checking.
14004 Sema::DeclGroupPtrTy
14005 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14006   // C++14 [dcl.spec.auto]p7: (DR1347)
14007   //   If the type that replaces the placeholder type is not the same in each
14008   //   deduction, the program is ill-formed.
14009   if (Group.size() > 1) {
14010     QualType Deduced;
14011     VarDecl *DeducedDecl = nullptr;
14012     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14013       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14014       if (!D || D->isInvalidDecl())
14015         break;
14016       DeducedType *DT = D->getType()->getContainedDeducedType();
14017       if (!DT || DT->getDeducedType().isNull())
14018         continue;
14019       if (Deduced.isNull()) {
14020         Deduced = DT->getDeducedType();
14021         DeducedDecl = D;
14022       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14023         auto *AT = dyn_cast<AutoType>(DT);
14024         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14025                         diag::err_auto_different_deductions)
14026                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14027                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14028                    << D->getDeclName();
14029         if (DeducedDecl->hasInit())
14030           Dia << DeducedDecl->getInit()->getSourceRange();
14031         if (D->getInit())
14032           Dia << D->getInit()->getSourceRange();
14033         D->setInvalidDecl();
14034         break;
14035       }
14036     }
14037   }
14038 
14039   ActOnDocumentableDecls(Group);
14040 
14041   return DeclGroupPtrTy::make(
14042       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14043 }
14044 
14045 void Sema::ActOnDocumentableDecl(Decl *D) {
14046   ActOnDocumentableDecls(D);
14047 }
14048 
14049 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14050   // Don't parse the comment if Doxygen diagnostics are ignored.
14051   if (Group.empty() || !Group[0])
14052     return;
14053 
14054   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14055                       Group[0]->getLocation()) &&
14056       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14057                       Group[0]->getLocation()))
14058     return;
14059 
14060   if (Group.size() >= 2) {
14061     // This is a decl group.  Normally it will contain only declarations
14062     // produced from declarator list.  But in case we have any definitions or
14063     // additional declaration references:
14064     //   'typedef struct S {} S;'
14065     //   'typedef struct S *S;'
14066     //   'struct S *pS;'
14067     // FinalizeDeclaratorGroup adds these as separate declarations.
14068     Decl *MaybeTagDecl = Group[0];
14069     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14070       Group = Group.slice(1);
14071     }
14072   }
14073 
14074   // FIMXE: We assume every Decl in the group is in the same file.
14075   // This is false when preprocessor constructs the group from decls in
14076   // different files (e. g. macros or #include).
14077   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14078 }
14079 
14080 /// Common checks for a parameter-declaration that should apply to both function
14081 /// parameters and non-type template parameters.
14082 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14083   // Check that there are no default arguments inside the type of this
14084   // parameter.
14085   if (getLangOpts().CPlusPlus)
14086     CheckExtraCXXDefaultArguments(D);
14087 
14088   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14089   if (D.getCXXScopeSpec().isSet()) {
14090     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14091       << D.getCXXScopeSpec().getRange();
14092   }
14093 
14094   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14095   // simple identifier except [...irrelevant cases...].
14096   switch (D.getName().getKind()) {
14097   case UnqualifiedIdKind::IK_Identifier:
14098     break;
14099 
14100   case UnqualifiedIdKind::IK_OperatorFunctionId:
14101   case UnqualifiedIdKind::IK_ConversionFunctionId:
14102   case UnqualifiedIdKind::IK_LiteralOperatorId:
14103   case UnqualifiedIdKind::IK_ConstructorName:
14104   case UnqualifiedIdKind::IK_DestructorName:
14105   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14106   case UnqualifiedIdKind::IK_DeductionGuideName:
14107     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14108       << GetNameForDeclarator(D).getName();
14109     break;
14110 
14111   case UnqualifiedIdKind::IK_TemplateId:
14112   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14113     // GetNameForDeclarator would not produce a useful name in this case.
14114     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14115     break;
14116   }
14117 }
14118 
14119 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14120 /// to introduce parameters into function prototype scope.
14121 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14122   const DeclSpec &DS = D.getDeclSpec();
14123 
14124   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14125 
14126   // C++03 [dcl.stc]p2 also permits 'auto'.
14127   StorageClass SC = SC_None;
14128   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14129     SC = SC_Register;
14130     // In C++11, the 'register' storage class specifier is deprecated.
14131     // In C++17, it is not allowed, but we tolerate it as an extension.
14132     if (getLangOpts().CPlusPlus11) {
14133       Diag(DS.getStorageClassSpecLoc(),
14134            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14135                                      : diag::warn_deprecated_register)
14136         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14137     }
14138   } else if (getLangOpts().CPlusPlus &&
14139              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14140     SC = SC_Auto;
14141   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14142     Diag(DS.getStorageClassSpecLoc(),
14143          diag::err_invalid_storage_class_in_func_decl);
14144     D.getMutableDeclSpec().ClearStorageClassSpecs();
14145   }
14146 
14147   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14148     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14149       << DeclSpec::getSpecifierName(TSCS);
14150   if (DS.isInlineSpecified())
14151     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14152         << getLangOpts().CPlusPlus17;
14153   if (DS.hasConstexprSpecifier())
14154     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14155         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14156 
14157   DiagnoseFunctionSpecifiers(DS);
14158 
14159   CheckFunctionOrTemplateParamDeclarator(S, D);
14160 
14161   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14162   QualType parmDeclType = TInfo->getType();
14163 
14164   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14165   IdentifierInfo *II = D.getIdentifier();
14166   if (II) {
14167     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14168                    ForVisibleRedeclaration);
14169     LookupName(R, S);
14170     if (R.isSingleResult()) {
14171       NamedDecl *PrevDecl = R.getFoundDecl();
14172       if (PrevDecl->isTemplateParameter()) {
14173         // Maybe we will complain about the shadowed template parameter.
14174         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14175         // Just pretend that we didn't see the previous declaration.
14176         PrevDecl = nullptr;
14177       } else if (S->isDeclScope(PrevDecl)) {
14178         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14179         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14180 
14181         // Recover by removing the name
14182         II = nullptr;
14183         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14184         D.setInvalidType(true);
14185       }
14186     }
14187   }
14188 
14189   // Temporarily put parameter variables in the translation unit, not
14190   // the enclosing context.  This prevents them from accidentally
14191   // looking like class members in C++.
14192   ParmVarDecl *New =
14193       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14194                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14195 
14196   if (D.isInvalidType())
14197     New->setInvalidDecl();
14198 
14199   assert(S->isFunctionPrototypeScope());
14200   assert(S->getFunctionPrototypeDepth() >= 1);
14201   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14202                     S->getNextFunctionPrototypeIndex());
14203 
14204   // Add the parameter declaration into this scope.
14205   S->AddDecl(New);
14206   if (II)
14207     IdResolver.AddDecl(New);
14208 
14209   ProcessDeclAttributes(S, New, D);
14210 
14211   if (D.getDeclSpec().isModulePrivateSpecified())
14212     Diag(New->getLocation(), diag::err_module_private_local)
14213         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14214         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14215 
14216   if (New->hasAttr<BlocksAttr>()) {
14217     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14218   }
14219 
14220   if (getLangOpts().OpenCL)
14221     deduceOpenCLAddressSpace(New);
14222 
14223   return New;
14224 }
14225 
14226 /// Synthesizes a variable for a parameter arising from a
14227 /// typedef.
14228 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14229                                               SourceLocation Loc,
14230                                               QualType T) {
14231   /* FIXME: setting StartLoc == Loc.
14232      Would it be worth to modify callers so as to provide proper source
14233      location for the unnamed parameters, embedding the parameter's type? */
14234   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14235                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14236                                            SC_None, nullptr);
14237   Param->setImplicit();
14238   return Param;
14239 }
14240 
14241 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14242   // Don't diagnose unused-parameter errors in template instantiations; we
14243   // will already have done so in the template itself.
14244   if (inTemplateInstantiation())
14245     return;
14246 
14247   for (const ParmVarDecl *Parameter : Parameters) {
14248     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14249         !Parameter->hasAttr<UnusedAttr>()) {
14250       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14251         << Parameter->getDeclName();
14252     }
14253   }
14254 }
14255 
14256 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14257     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14258   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14259     return;
14260 
14261   // Warn if the return value is pass-by-value and larger than the specified
14262   // threshold.
14263   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14264     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14265     if (Size > LangOpts.NumLargeByValueCopy)
14266       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14267   }
14268 
14269   // Warn if any parameter is pass-by-value and larger than the specified
14270   // threshold.
14271   for (const ParmVarDecl *Parameter : Parameters) {
14272     QualType T = Parameter->getType();
14273     if (T->isDependentType() || !T.isPODType(Context))
14274       continue;
14275     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14276     if (Size > LangOpts.NumLargeByValueCopy)
14277       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14278           << Parameter << Size;
14279   }
14280 }
14281 
14282 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14283                                   SourceLocation NameLoc, IdentifierInfo *Name,
14284                                   QualType T, TypeSourceInfo *TSInfo,
14285                                   StorageClass SC) {
14286   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14287   if (getLangOpts().ObjCAutoRefCount &&
14288       T.getObjCLifetime() == Qualifiers::OCL_None &&
14289       T->isObjCLifetimeType()) {
14290 
14291     Qualifiers::ObjCLifetime lifetime;
14292 
14293     // Special cases for arrays:
14294     //   - if it's const, use __unsafe_unretained
14295     //   - otherwise, it's an error
14296     if (T->isArrayType()) {
14297       if (!T.isConstQualified()) {
14298         if (DelayedDiagnostics.shouldDelayDiagnostics())
14299           DelayedDiagnostics.add(
14300               sema::DelayedDiagnostic::makeForbiddenType(
14301               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14302         else
14303           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14304               << TSInfo->getTypeLoc().getSourceRange();
14305       }
14306       lifetime = Qualifiers::OCL_ExplicitNone;
14307     } else {
14308       lifetime = T->getObjCARCImplicitLifetime();
14309     }
14310     T = Context.getLifetimeQualifiedType(T, lifetime);
14311   }
14312 
14313   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14314                                          Context.getAdjustedParameterType(T),
14315                                          TSInfo, SC, nullptr);
14316 
14317   // Make a note if we created a new pack in the scope of a lambda, so that
14318   // we know that references to that pack must also be expanded within the
14319   // lambda scope.
14320   if (New->isParameterPack())
14321     if (auto *LSI = getEnclosingLambda())
14322       LSI->LocalPacks.push_back(New);
14323 
14324   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14325       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14326     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14327                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14328 
14329   // Parameters can not be abstract class types.
14330   // For record types, this is done by the AbstractClassUsageDiagnoser once
14331   // the class has been completely parsed.
14332   if (!CurContext->isRecord() &&
14333       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14334                              AbstractParamType))
14335     New->setInvalidDecl();
14336 
14337   // Parameter declarators cannot be interface types. All ObjC objects are
14338   // passed by reference.
14339   if (T->isObjCObjectType()) {
14340     SourceLocation TypeEndLoc =
14341         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14342     Diag(NameLoc,
14343          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14344       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14345     T = Context.getObjCObjectPointerType(T);
14346     New->setType(T);
14347   }
14348 
14349   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14350   // duration shall not be qualified by an address-space qualifier."
14351   // Since all parameters have automatic store duration, they can not have
14352   // an address space.
14353   if (T.getAddressSpace() != LangAS::Default &&
14354       // OpenCL allows function arguments declared to be an array of a type
14355       // to be qualified with an address space.
14356       !(getLangOpts().OpenCL &&
14357         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14358     Diag(NameLoc, diag::err_arg_with_address_space);
14359     New->setInvalidDecl();
14360   }
14361 
14362   // PPC MMA non-pointer types are not allowed as function argument types.
14363   if (Context.getTargetInfo().getTriple().isPPC64() &&
14364       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14365     New->setInvalidDecl();
14366   }
14367 
14368   return New;
14369 }
14370 
14371 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14372                                            SourceLocation LocAfterDecls) {
14373   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14374 
14375   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14376   // in the declaration list shall have at least one declarator, those
14377   // declarators shall only declare identifiers from the identifier list, and
14378   // every identifier in the identifier list shall be declared.
14379   //
14380   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14381   // identifiers it names shall be declared in the declaration list."
14382   //
14383   // This is why we only diagnose in C99 and later. Note, the other conditions
14384   // listed are checked elsewhere.
14385   if (!FTI.hasPrototype) {
14386     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14387       --i;
14388       if (FTI.Params[i].Param == nullptr) {
14389         if (getLangOpts().C99) {
14390           SmallString<256> Code;
14391           llvm::raw_svector_ostream(Code)
14392               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14393           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14394               << FTI.Params[i].Ident
14395               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14396         }
14397 
14398         // Implicitly declare the argument as type 'int' for lack of a better
14399         // type.
14400         AttributeFactory attrs;
14401         DeclSpec DS(attrs);
14402         const char* PrevSpec; // unused
14403         unsigned DiagID; // unused
14404         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14405                            DiagID, Context.getPrintingPolicy());
14406         // Use the identifier location for the type source range.
14407         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14408         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14409         Declarator ParamD(DS, ParsedAttributesView::none(),
14410                           DeclaratorContext::KNRTypeList);
14411         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14412         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14413       }
14414     }
14415   }
14416 }
14417 
14418 Decl *
14419 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14420                               MultiTemplateParamsArg TemplateParameterLists,
14421                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14422   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14423   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14424   Scope *ParentScope = FnBodyScope->getParent();
14425 
14426   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14427   // we define a non-templated function definition, we will create a declaration
14428   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14429   // The base function declaration will have the equivalent of an `omp declare
14430   // variant` annotation which specifies the mangled definition as a
14431   // specialization function under the OpenMP context defined as part of the
14432   // `omp begin declare variant`.
14433   SmallVector<FunctionDecl *, 4> Bases;
14434   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14435     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14436         ParentScope, D, TemplateParameterLists, Bases);
14437 
14438   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14439   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14440   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14441 
14442   if (!Bases.empty())
14443     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14444 
14445   return Dcl;
14446 }
14447 
14448 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14449   Consumer.HandleInlineFunctionDefinition(D);
14450 }
14451 
14452 static bool
14453 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14454                                 const FunctionDecl *&PossiblePrototype) {
14455   // Don't warn about invalid declarations.
14456   if (FD->isInvalidDecl())
14457     return false;
14458 
14459   // Or declarations that aren't global.
14460   if (!FD->isGlobal())
14461     return false;
14462 
14463   // Don't warn about C++ member functions.
14464   if (isa<CXXMethodDecl>(FD))
14465     return false;
14466 
14467   // Don't warn about 'main'.
14468   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14469     if (IdentifierInfo *II = FD->getIdentifier())
14470       if (II->isStr("main") || II->isStr("efi_main"))
14471         return false;
14472 
14473   // Don't warn about inline functions.
14474   if (FD->isInlined())
14475     return false;
14476 
14477   // Don't warn about function templates.
14478   if (FD->getDescribedFunctionTemplate())
14479     return false;
14480 
14481   // Don't warn about function template specializations.
14482   if (FD->isFunctionTemplateSpecialization())
14483     return false;
14484 
14485   // Don't warn for OpenCL kernels.
14486   if (FD->hasAttr<OpenCLKernelAttr>())
14487     return false;
14488 
14489   // Don't warn on explicitly deleted functions.
14490   if (FD->isDeleted())
14491     return false;
14492 
14493   // Don't warn on implicitly local functions (such as having local-typed
14494   // parameters).
14495   if (!FD->isExternallyVisible())
14496     return false;
14497 
14498   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14499        Prev; Prev = Prev->getPreviousDecl()) {
14500     // Ignore any declarations that occur in function or method
14501     // scope, because they aren't visible from the header.
14502     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14503       continue;
14504 
14505     PossiblePrototype = Prev;
14506     return Prev->getType()->isFunctionNoProtoType();
14507   }
14508 
14509   return true;
14510 }
14511 
14512 void
14513 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14514                                    const FunctionDecl *EffectiveDefinition,
14515                                    SkipBodyInfo *SkipBody) {
14516   const FunctionDecl *Definition = EffectiveDefinition;
14517   if (!Definition &&
14518       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14519     return;
14520 
14521   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14522     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14523       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14524         // A merged copy of the same function, instantiated as a member of
14525         // the same class, is OK.
14526         if (declaresSameEntity(OrigFD, OrigDef) &&
14527             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14528                                cast<Decl>(FD->getLexicalDeclContext())))
14529           return;
14530       }
14531     }
14532   }
14533 
14534   if (canRedefineFunction(Definition, getLangOpts()))
14535     return;
14536 
14537   // Don't emit an error when this is redefinition of a typo-corrected
14538   // definition.
14539   if (TypoCorrectedFunctionDefinitions.count(Definition))
14540     return;
14541 
14542   // If we don't have a visible definition of the function, and it's inline or
14543   // a template, skip the new definition.
14544   if (SkipBody && !hasVisibleDefinition(Definition) &&
14545       (Definition->getFormalLinkage() == InternalLinkage ||
14546        Definition->isInlined() ||
14547        Definition->getDescribedFunctionTemplate() ||
14548        Definition->getNumTemplateParameterLists())) {
14549     SkipBody->ShouldSkip = true;
14550     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14551     if (auto *TD = Definition->getDescribedFunctionTemplate())
14552       makeMergedDefinitionVisible(TD);
14553     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14554     return;
14555   }
14556 
14557   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14558       Definition->getStorageClass() == SC_Extern)
14559     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14560         << FD << getLangOpts().CPlusPlus;
14561   else
14562     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14563 
14564   Diag(Definition->getLocation(), diag::note_previous_definition);
14565   FD->setInvalidDecl();
14566 }
14567 
14568 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14569                                    Sema &S) {
14570   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14571 
14572   LambdaScopeInfo *LSI = S.PushLambdaScope();
14573   LSI->CallOperator = CallOperator;
14574   LSI->Lambda = LambdaClass;
14575   LSI->ReturnType = CallOperator->getReturnType();
14576   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14577 
14578   if (LCD == LCD_None)
14579     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14580   else if (LCD == LCD_ByCopy)
14581     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14582   else if (LCD == LCD_ByRef)
14583     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14584   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14585 
14586   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14587   LSI->Mutable = !CallOperator->isConst();
14588 
14589   // Add the captures to the LSI so they can be noted as already
14590   // captured within tryCaptureVar.
14591   auto I = LambdaClass->field_begin();
14592   for (const auto &C : LambdaClass->captures()) {
14593     if (C.capturesVariable()) {
14594       VarDecl *VD = C.getCapturedVar();
14595       if (VD->isInitCapture())
14596         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14597       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14598       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14599           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14600           /*EllipsisLoc*/C.isPackExpansion()
14601                          ? C.getEllipsisLoc() : SourceLocation(),
14602           I->getType(), /*Invalid*/false);
14603 
14604     } else if (C.capturesThis()) {
14605       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14606                           C.getCaptureKind() == LCK_StarThis);
14607     } else {
14608       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14609                              I->getType());
14610     }
14611     ++I;
14612   }
14613 }
14614 
14615 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14616                                     SkipBodyInfo *SkipBody,
14617                                     FnBodyKind BodyKind) {
14618   if (!D) {
14619     // Parsing the function declaration failed in some way. Push on a fake scope
14620     // anyway so we can try to parse the function body.
14621     PushFunctionScope();
14622     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14623     return D;
14624   }
14625 
14626   FunctionDecl *FD = nullptr;
14627 
14628   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14629     FD = FunTmpl->getTemplatedDecl();
14630   else
14631     FD = cast<FunctionDecl>(D);
14632 
14633   // Do not push if it is a lambda because one is already pushed when building
14634   // the lambda in ActOnStartOfLambdaDefinition().
14635   if (!isLambdaCallOperator(FD))
14636     PushExpressionEvaluationContext(
14637         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14638                           : ExprEvalContexts.back().Context);
14639 
14640   // Check for defining attributes before the check for redefinition.
14641   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14642     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14643     FD->dropAttr<AliasAttr>();
14644     FD->setInvalidDecl();
14645   }
14646   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14647     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14648     FD->dropAttr<IFuncAttr>();
14649     FD->setInvalidDecl();
14650   }
14651 
14652   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14653     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14654         Ctor->isDefaultConstructor() &&
14655         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14656       // If this is an MS ABI dllexport default constructor, instantiate any
14657       // default arguments.
14658       InstantiateDefaultCtorDefaultArgs(Ctor);
14659     }
14660   }
14661 
14662   // See if this is a redefinition. If 'will have body' (or similar) is already
14663   // set, then these checks were already performed when it was set.
14664   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14665       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14666     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14667 
14668     // If we're skipping the body, we're done. Don't enter the scope.
14669     if (SkipBody && SkipBody->ShouldSkip)
14670       return D;
14671   }
14672 
14673   // Mark this function as "will have a body eventually".  This lets users to
14674   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14675   // this function.
14676   FD->setWillHaveBody();
14677 
14678   // If we are instantiating a generic lambda call operator, push
14679   // a LambdaScopeInfo onto the function stack.  But use the information
14680   // that's already been calculated (ActOnLambdaExpr) to prime the current
14681   // LambdaScopeInfo.
14682   // When the template operator is being specialized, the LambdaScopeInfo,
14683   // has to be properly restored so that tryCaptureVariable doesn't try
14684   // and capture any new variables. In addition when calculating potential
14685   // captures during transformation of nested lambdas, it is necessary to
14686   // have the LSI properly restored.
14687   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14688     assert(inTemplateInstantiation() &&
14689            "There should be an active template instantiation on the stack "
14690            "when instantiating a generic lambda!");
14691     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14692   } else {
14693     // Enter a new function scope
14694     PushFunctionScope();
14695   }
14696 
14697   // Builtin functions cannot be defined.
14698   if (unsigned BuiltinID = FD->getBuiltinID()) {
14699     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14700         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14701       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14702       FD->setInvalidDecl();
14703     }
14704   }
14705 
14706   // The return type of a function definition must be complete (C99 6.9.1p3),
14707   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14708   QualType ResultType = FD->getReturnType();
14709   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14710       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14711       RequireCompleteType(FD->getLocation(), ResultType,
14712                           diag::err_func_def_incomplete_result))
14713     FD->setInvalidDecl();
14714 
14715   if (FnBodyScope)
14716     PushDeclContext(FnBodyScope, FD);
14717 
14718   // Check the validity of our function parameters
14719   if (BodyKind != FnBodyKind::Delete)
14720     CheckParmsForFunctionDef(FD->parameters(),
14721                              /*CheckParameterNames=*/true);
14722 
14723   // Add non-parameter declarations already in the function to the current
14724   // scope.
14725   if (FnBodyScope) {
14726     for (Decl *NPD : FD->decls()) {
14727       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14728       if (!NonParmDecl)
14729         continue;
14730       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14731              "parameters should not be in newly created FD yet");
14732 
14733       // If the decl has a name, make it accessible in the current scope.
14734       if (NonParmDecl->getDeclName())
14735         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14736 
14737       // Similarly, dive into enums and fish their constants out, making them
14738       // accessible in this scope.
14739       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14740         for (auto *EI : ED->enumerators())
14741           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14742       }
14743     }
14744   }
14745 
14746   // Introduce our parameters into the function scope
14747   for (auto Param : FD->parameters()) {
14748     Param->setOwningFunction(FD);
14749 
14750     // If this has an identifier, add it to the scope stack.
14751     if (Param->getIdentifier() && FnBodyScope) {
14752       CheckShadow(FnBodyScope, Param);
14753 
14754       PushOnScopeChains(Param, FnBodyScope);
14755     }
14756   }
14757 
14758   // Ensure that the function's exception specification is instantiated.
14759   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14760     ResolveExceptionSpec(D->getLocation(), FPT);
14761 
14762   // dllimport cannot be applied to non-inline function definitions.
14763   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14764       !FD->isTemplateInstantiation()) {
14765     assert(!FD->hasAttr<DLLExportAttr>());
14766     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14767     FD->setInvalidDecl();
14768     return D;
14769   }
14770   // We want to attach documentation to original Decl (which might be
14771   // a function template).
14772   ActOnDocumentableDecl(D);
14773   if (getCurLexicalContext()->isObjCContainer() &&
14774       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14775       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14776     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14777 
14778   return D;
14779 }
14780 
14781 /// Given the set of return statements within a function body,
14782 /// compute the variables that are subject to the named return value
14783 /// optimization.
14784 ///
14785 /// Each of the variables that is subject to the named return value
14786 /// optimization will be marked as NRVO variables in the AST, and any
14787 /// return statement that has a marked NRVO variable as its NRVO candidate can
14788 /// use the named return value optimization.
14789 ///
14790 /// This function applies a very simplistic algorithm for NRVO: if every return
14791 /// statement in the scope of a variable has the same NRVO candidate, that
14792 /// candidate is an NRVO variable.
14793 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14794   ReturnStmt **Returns = Scope->Returns.data();
14795 
14796   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14797     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14798       if (!NRVOCandidate->isNRVOVariable())
14799         Returns[I]->setNRVOCandidate(nullptr);
14800     }
14801   }
14802 }
14803 
14804 bool Sema::canDelayFunctionBody(const Declarator &D) {
14805   // We can't delay parsing the body of a constexpr function template (yet).
14806   if (D.getDeclSpec().hasConstexprSpecifier())
14807     return false;
14808 
14809   // We can't delay parsing the body of a function template with a deduced
14810   // return type (yet).
14811   if (D.getDeclSpec().hasAutoTypeSpec()) {
14812     // If the placeholder introduces a non-deduced trailing return type,
14813     // we can still delay parsing it.
14814     if (D.getNumTypeObjects()) {
14815       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14816       if (Outer.Kind == DeclaratorChunk::Function &&
14817           Outer.Fun.hasTrailingReturnType()) {
14818         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14819         return Ty.isNull() || !Ty->isUndeducedType();
14820       }
14821     }
14822     return false;
14823   }
14824 
14825   return true;
14826 }
14827 
14828 bool Sema::canSkipFunctionBody(Decl *D) {
14829   // We cannot skip the body of a function (or function template) which is
14830   // constexpr, since we may need to evaluate its body in order to parse the
14831   // rest of the file.
14832   // We cannot skip the body of a function with an undeduced return type,
14833   // because any callers of that function need to know the type.
14834   if (const FunctionDecl *FD = D->getAsFunction()) {
14835     if (FD->isConstexpr())
14836       return false;
14837     // We can't simply call Type::isUndeducedType here, because inside template
14838     // auto can be deduced to a dependent type, which is not considered
14839     // "undeduced".
14840     if (FD->getReturnType()->getContainedDeducedType())
14841       return false;
14842   }
14843   return Consumer.shouldSkipFunctionBody(D);
14844 }
14845 
14846 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14847   if (!Decl)
14848     return nullptr;
14849   if (FunctionDecl *FD = Decl->getAsFunction())
14850     FD->setHasSkippedBody();
14851   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14852     MD->setHasSkippedBody();
14853   return Decl;
14854 }
14855 
14856 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14857   return ActOnFinishFunctionBody(D, BodyArg, false);
14858 }
14859 
14860 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14861 /// body.
14862 class ExitFunctionBodyRAII {
14863 public:
14864   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14865   ~ExitFunctionBodyRAII() {
14866     if (!IsLambda)
14867       S.PopExpressionEvaluationContext();
14868   }
14869 
14870 private:
14871   Sema &S;
14872   bool IsLambda = false;
14873 };
14874 
14875 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14876   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14877 
14878   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14879     if (EscapeInfo.count(BD))
14880       return EscapeInfo[BD];
14881 
14882     bool R = false;
14883     const BlockDecl *CurBD = BD;
14884 
14885     do {
14886       R = !CurBD->doesNotEscape();
14887       if (R)
14888         break;
14889       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14890     } while (CurBD);
14891 
14892     return EscapeInfo[BD] = R;
14893   };
14894 
14895   // If the location where 'self' is implicitly retained is inside a escaping
14896   // block, emit a diagnostic.
14897   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14898        S.ImplicitlyRetainedSelfLocs)
14899     if (IsOrNestedInEscapingBlock(P.second))
14900       S.Diag(P.first, diag::warn_implicitly_retains_self)
14901           << FixItHint::CreateInsertion(P.first, "self->");
14902 }
14903 
14904 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14905                                     bool IsInstantiation) {
14906   FunctionScopeInfo *FSI = getCurFunction();
14907   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14908 
14909   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14910     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14911 
14912   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14913   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14914 
14915   if (getLangOpts().Coroutines && FSI->isCoroutine())
14916     CheckCompletedCoroutineBody(FD, Body);
14917 
14918   {
14919     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14920     // one is already popped when finishing the lambda in BuildLambdaExpr().
14921     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14922     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14923 
14924     if (FD) {
14925       FD->setBody(Body);
14926       FD->setWillHaveBody(false);
14927 
14928       if (getLangOpts().CPlusPlus14) {
14929         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14930             FD->getReturnType()->isUndeducedType()) {
14931           // For a function with a deduced result type to return void,
14932           // the result type as written must be 'auto' or 'decltype(auto)',
14933           // possibly cv-qualified or constrained, but not ref-qualified.
14934           if (!FD->getReturnType()->getAs<AutoType>()) {
14935             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14936                 << FD->getReturnType();
14937             FD->setInvalidDecl();
14938           } else {
14939             // Falling off the end of the function is the same as 'return;'.
14940             Expr *Dummy = nullptr;
14941             if (DeduceFunctionTypeFromReturnExpr(
14942                     FD, dcl->getLocation(), Dummy,
14943                     FD->getReturnType()->getAs<AutoType>()))
14944               FD->setInvalidDecl();
14945           }
14946         }
14947       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14948         // In C++11, we don't use 'auto' deduction rules for lambda call
14949         // operators because we don't support return type deduction.
14950         auto *LSI = getCurLambda();
14951         if (LSI->HasImplicitReturnType) {
14952           deduceClosureReturnType(*LSI);
14953 
14954           // C++11 [expr.prim.lambda]p4:
14955           //   [...] if there are no return statements in the compound-statement
14956           //   [the deduced type is] the type void
14957           QualType RetType =
14958               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14959 
14960           // Update the return type to the deduced type.
14961           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14962           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14963                                               Proto->getExtProtoInfo()));
14964         }
14965       }
14966 
14967       // If the function implicitly returns zero (like 'main') or is naked,
14968       // don't complain about missing return statements.
14969       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14970         WP.disableCheckFallThrough();
14971 
14972       // MSVC permits the use of pure specifier (=0) on function definition,
14973       // defined at class scope, warn about this non-standard construct.
14974       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14975         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14976 
14977       if (!FD->isInvalidDecl()) {
14978         // Don't diagnose unused parameters of defaulted, deleted or naked
14979         // functions.
14980         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14981             !FD->hasAttr<NakedAttr>())
14982           DiagnoseUnusedParameters(FD->parameters());
14983         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14984                                                FD->getReturnType(), FD);
14985 
14986         // If this is a structor, we need a vtable.
14987         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14988           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14989         else if (CXXDestructorDecl *Destructor =
14990                      dyn_cast<CXXDestructorDecl>(FD))
14991           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14992 
14993         // Try to apply the named return value optimization. We have to check
14994         // if we can do this here because lambdas keep return statements around
14995         // to deduce an implicit return type.
14996         if (FD->getReturnType()->isRecordType() &&
14997             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14998           computeNRVO(Body, FSI);
14999       }
15000 
15001       // GNU warning -Wmissing-prototypes:
15002       //   Warn if a global function is defined without a previous
15003       //   prototype declaration. This warning is issued even if the
15004       //   definition itself provides a prototype. The aim is to detect
15005       //   global functions that fail to be declared in header files.
15006       const FunctionDecl *PossiblePrototype = nullptr;
15007       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15008         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15009 
15010         if (PossiblePrototype) {
15011           // We found a declaration that is not a prototype,
15012           // but that could be a zero-parameter prototype
15013           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15014             TypeLoc TL = TI->getTypeLoc();
15015             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15016               Diag(PossiblePrototype->getLocation(),
15017                    diag::note_declaration_not_a_prototype)
15018                   << (FD->getNumParams() != 0)
15019                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15020                                                     FTL.getRParenLoc(), "void")
15021                                               : FixItHint{});
15022           }
15023         } else {
15024           // Returns true if the token beginning at this Loc is `const`.
15025           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15026                                   const LangOptions &LangOpts) {
15027             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15028             if (LocInfo.first.isInvalid())
15029               return false;
15030 
15031             bool Invalid = false;
15032             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15033             if (Invalid)
15034               return false;
15035 
15036             if (LocInfo.second > Buffer.size())
15037               return false;
15038 
15039             const char *LexStart = Buffer.data() + LocInfo.second;
15040             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15041 
15042             return StartTok.consume_front("const") &&
15043                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15044                     StartTok.startswith("/*") || StartTok.startswith("//"));
15045           };
15046 
15047           auto findBeginLoc = [&]() {
15048             // If the return type has `const` qualifier, we want to insert
15049             // `static` before `const` (and not before the typename).
15050             if ((FD->getReturnType()->isAnyPointerType() &&
15051                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15052                 FD->getReturnType().isConstQualified()) {
15053               // But only do this if we can determine where the `const` is.
15054 
15055               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15056                                getLangOpts()))
15057 
15058                 return FD->getBeginLoc();
15059             }
15060             return FD->getTypeSpecStartLoc();
15061           };
15062           Diag(FD->getTypeSpecStartLoc(),
15063                diag::note_static_for_internal_linkage)
15064               << /* function */ 1
15065               << (FD->getStorageClass() == SC_None
15066                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15067                       : FixItHint{});
15068         }
15069       }
15070 
15071       // If the function being defined does not have a prototype, then we may
15072       // need to diagnose it as changing behavior in C2x because we now know
15073       // whether the function accepts arguments or not. This only handles the
15074       // case where the definition has no prototype but does have parameters
15075       // and either there is no previous potential prototype, or the previous
15076       // potential prototype also has no actual prototype. This handles cases
15077       // like:
15078       //   void f(); void f(a) int a; {}
15079       //   void g(a) int a; {}
15080       // See MergeFunctionDecl() for other cases of the behavior change
15081       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15082       // type without a prototype.
15083       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15084           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15085                                   !PossiblePrototype->isImplicit()))) {
15086         // The function definition has parameters, so this will change behavior
15087         // in C2x. If there is a possible prototype, it comes before the
15088         // function definition.
15089         // FIXME: The declaration may have already been diagnosed as being
15090         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15091         // there's no way to test for the "changes behavior" condition in
15092         // SemaType.cpp when forming the declaration's function type. So, we do
15093         // this awkward dance instead.
15094         //
15095         // If we have a possible prototype and it declares a function with a
15096         // prototype, we don't want to diagnose it; if we have a possible
15097         // prototype and it has no prototype, it may have already been
15098         // diagnosed in SemaType.cpp as deprecated depending on whether
15099         // -Wstrict-prototypes is enabled. If we already warned about it being
15100         // deprecated, add a note that it also changes behavior. If we didn't
15101         // warn about it being deprecated (because the diagnostic is not
15102         // enabled), warn now that it is deprecated and changes behavior.
15103 
15104         // This K&R C function definition definitely changes behavior in C2x,
15105         // so diagnose it.
15106         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15107             << /*definition*/ 1 << /* not supported in C2x */ 0;
15108 
15109         // If we have a possible prototype for the function which is a user-
15110         // visible declaration, we already tested that it has no prototype.
15111         // This will change behavior in C2x. This gets a warning rather than a
15112         // note because it's the same behavior-changing problem as with the
15113         // definition.
15114         if (PossiblePrototype)
15115           Diag(PossiblePrototype->getLocation(),
15116                diag::warn_non_prototype_changes_behavior)
15117               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15118               << /*definition*/ 1;
15119       }
15120 
15121       // Warn on CPUDispatch with an actual body.
15122       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15123         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15124           if (!CmpndBody->body_empty())
15125             Diag(CmpndBody->body_front()->getBeginLoc(),
15126                  diag::warn_dispatch_body_ignored);
15127 
15128       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15129         const CXXMethodDecl *KeyFunction;
15130         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15131             MD->isVirtual() &&
15132             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15133             MD == KeyFunction->getCanonicalDecl()) {
15134           // Update the key-function state if necessary for this ABI.
15135           if (FD->isInlined() &&
15136               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15137             Context.setNonKeyFunction(MD);
15138 
15139             // If the newly-chosen key function is already defined, then we
15140             // need to mark the vtable as used retroactively.
15141             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15142             const FunctionDecl *Definition;
15143             if (KeyFunction && KeyFunction->isDefined(Definition))
15144               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15145           } else {
15146             // We just defined they key function; mark the vtable as used.
15147             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15148           }
15149         }
15150       }
15151 
15152       assert(
15153           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15154           "Function parsing confused");
15155     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15156       assert(MD == getCurMethodDecl() && "Method parsing confused");
15157       MD->setBody(Body);
15158       if (!MD->isInvalidDecl()) {
15159         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15160                                                MD->getReturnType(), MD);
15161 
15162         if (Body)
15163           computeNRVO(Body, FSI);
15164       }
15165       if (FSI->ObjCShouldCallSuper) {
15166         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15167             << MD->getSelector().getAsString();
15168         FSI->ObjCShouldCallSuper = false;
15169       }
15170       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15171         const ObjCMethodDecl *InitMethod = nullptr;
15172         bool isDesignated =
15173             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15174         assert(isDesignated && InitMethod);
15175         (void)isDesignated;
15176 
15177         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15178           auto IFace = MD->getClassInterface();
15179           if (!IFace)
15180             return false;
15181           auto SuperD = IFace->getSuperClass();
15182           if (!SuperD)
15183             return false;
15184           return SuperD->getIdentifier() ==
15185                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15186         };
15187         // Don't issue this warning for unavailable inits or direct subclasses
15188         // of NSObject.
15189         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15190           Diag(MD->getLocation(),
15191                diag::warn_objc_designated_init_missing_super_call);
15192           Diag(InitMethod->getLocation(),
15193                diag::note_objc_designated_init_marked_here);
15194         }
15195         FSI->ObjCWarnForNoDesignatedInitChain = false;
15196       }
15197       if (FSI->ObjCWarnForNoInitDelegation) {
15198         // Don't issue this warning for unavaialable inits.
15199         if (!MD->isUnavailable())
15200           Diag(MD->getLocation(),
15201                diag::warn_objc_secondary_init_missing_init_call);
15202         FSI->ObjCWarnForNoInitDelegation = false;
15203       }
15204 
15205       diagnoseImplicitlyRetainedSelf(*this);
15206     } else {
15207       // Parsing the function declaration failed in some way. Pop the fake scope
15208       // we pushed on.
15209       PopFunctionScopeInfo(ActivePolicy, dcl);
15210       return nullptr;
15211     }
15212 
15213     if (Body && FSI->HasPotentialAvailabilityViolations)
15214       DiagnoseUnguardedAvailabilityViolations(dcl);
15215 
15216     assert(!FSI->ObjCShouldCallSuper &&
15217            "This should only be set for ObjC methods, which should have been "
15218            "handled in the block above.");
15219 
15220     // Verify and clean out per-function state.
15221     if (Body && (!FD || !FD->isDefaulted())) {
15222       // C++ constructors that have function-try-blocks can't have return
15223       // statements in the handlers of that block. (C++ [except.handle]p14)
15224       // Verify this.
15225       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15226         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15227 
15228       // Verify that gotos and switch cases don't jump into scopes illegally.
15229       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15230         DiagnoseInvalidJumps(Body);
15231 
15232       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15233         if (!Destructor->getParent()->isDependentType())
15234           CheckDestructor(Destructor);
15235 
15236         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15237                                                Destructor->getParent());
15238       }
15239 
15240       // If any errors have occurred, clear out any temporaries that may have
15241       // been leftover. This ensures that these temporaries won't be picked up
15242       // for deletion in some later function.
15243       if (hasUncompilableErrorOccurred() ||
15244           getDiagnostics().getSuppressAllDiagnostics()) {
15245         DiscardCleanupsInEvaluationContext();
15246       }
15247       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15248         // Since the body is valid, issue any analysis-based warnings that are
15249         // enabled.
15250         ActivePolicy = &WP;
15251       }
15252 
15253       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15254           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15255         FD->setInvalidDecl();
15256 
15257       if (FD && FD->hasAttr<NakedAttr>()) {
15258         for (const Stmt *S : Body->children()) {
15259           // Allow local register variables without initializer as they don't
15260           // require prologue.
15261           bool RegisterVariables = false;
15262           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15263             for (const auto *Decl : DS->decls()) {
15264               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15265                 RegisterVariables =
15266                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15267                 if (!RegisterVariables)
15268                   break;
15269               }
15270             }
15271           }
15272           if (RegisterVariables)
15273             continue;
15274           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15275             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15276             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15277             FD->setInvalidDecl();
15278             break;
15279           }
15280         }
15281       }
15282 
15283       assert(ExprCleanupObjects.size() ==
15284                  ExprEvalContexts.back().NumCleanupObjects &&
15285              "Leftover temporaries in function");
15286       assert(!Cleanup.exprNeedsCleanups() &&
15287              "Unaccounted cleanups in function");
15288       assert(MaybeODRUseExprs.empty() &&
15289              "Leftover expressions for odr-use checking");
15290     }
15291   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15292     // the declaration context below. Otherwise, we're unable to transform
15293     // 'this' expressions when transforming immediate context functions.
15294 
15295   if (!IsInstantiation)
15296     PopDeclContext();
15297 
15298   PopFunctionScopeInfo(ActivePolicy, dcl);
15299   // If any errors have occurred, clear out any temporaries that may have
15300   // been leftover. This ensures that these temporaries won't be picked up for
15301   // deletion in some later function.
15302   if (hasUncompilableErrorOccurred()) {
15303     DiscardCleanupsInEvaluationContext();
15304   }
15305 
15306   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15307                                   !LangOpts.OMPTargetTriples.empty())) ||
15308              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15309     auto ES = getEmissionStatus(FD);
15310     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15311         ES == Sema::FunctionEmissionStatus::Unknown)
15312       DeclsToCheckForDeferredDiags.insert(FD);
15313   }
15314 
15315   if (FD && !FD->isDeleted())
15316     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15317 
15318   return dcl;
15319 }
15320 
15321 /// When we finish delayed parsing of an attribute, we must attach it to the
15322 /// relevant Decl.
15323 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15324                                        ParsedAttributes &Attrs) {
15325   // Always attach attributes to the underlying decl.
15326   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15327     D = TD->getTemplatedDecl();
15328   ProcessDeclAttributeList(S, D, Attrs);
15329 
15330   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15331     if (Method->isStatic())
15332       checkThisInStaticMemberFunctionAttributes(Method);
15333 }
15334 
15335 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15336 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15337 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15338                                           IdentifierInfo &II, Scope *S) {
15339   // It is not valid to implicitly define a function in C2x.
15340   assert(LangOpts.implicitFunctionsAllowed() &&
15341          "Implicit function declarations aren't allowed in this language mode");
15342 
15343   // Find the scope in which the identifier is injected and the corresponding
15344   // DeclContext.
15345   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15346   // In that case, we inject the declaration into the translation unit scope
15347   // instead.
15348   Scope *BlockScope = S;
15349   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15350     BlockScope = BlockScope->getParent();
15351 
15352   Scope *ContextScope = BlockScope;
15353   while (!ContextScope->getEntity())
15354     ContextScope = ContextScope->getParent();
15355   ContextRAII SavedContext(*this, ContextScope->getEntity());
15356 
15357   // Before we produce a declaration for an implicitly defined
15358   // function, see whether there was a locally-scoped declaration of
15359   // this name as a function or variable. If so, use that
15360   // (non-visible) declaration, and complain about it.
15361   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15362   if (ExternCPrev) {
15363     // We still need to inject the function into the enclosing block scope so
15364     // that later (non-call) uses can see it.
15365     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15366 
15367     // C89 footnote 38:
15368     //   If in fact it is not defined as having type "function returning int",
15369     //   the behavior is undefined.
15370     if (!isa<FunctionDecl>(ExternCPrev) ||
15371         !Context.typesAreCompatible(
15372             cast<FunctionDecl>(ExternCPrev)->getType(),
15373             Context.getFunctionNoProtoType(Context.IntTy))) {
15374       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15375           << ExternCPrev << !getLangOpts().C99;
15376       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15377       return ExternCPrev;
15378     }
15379   }
15380 
15381   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15382   unsigned diag_id;
15383   if (II.getName().startswith("__builtin_"))
15384     diag_id = diag::warn_builtin_unknown;
15385   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15386   else if (getLangOpts().C99)
15387     diag_id = diag::ext_implicit_function_decl_c99;
15388   else
15389     diag_id = diag::warn_implicit_function_decl;
15390 
15391   TypoCorrection Corrected;
15392   // Because typo correction is expensive, only do it if the implicit
15393   // function declaration is going to be treated as an error.
15394   //
15395   // Perform the corection before issuing the main diagnostic, as some consumers
15396   // use typo-correction callbacks to enhance the main diagnostic.
15397   if (S && !ExternCPrev &&
15398       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15399     DeclFilterCCC<FunctionDecl> CCC{};
15400     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15401                             S, nullptr, CCC, CTK_NonError);
15402   }
15403 
15404   Diag(Loc, diag_id) << &II;
15405   if (Corrected) {
15406     // If the correction is going to suggest an implicitly defined function,
15407     // skip the correction as not being a particularly good idea.
15408     bool Diagnose = true;
15409     if (const auto *D = Corrected.getCorrectionDecl())
15410       Diagnose = !D->isImplicit();
15411     if (Diagnose)
15412       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15413                    /*ErrorRecovery*/ false);
15414   }
15415 
15416   // If we found a prior declaration of this function, don't bother building
15417   // another one. We've already pushed that one into scope, so there's nothing
15418   // more to do.
15419   if (ExternCPrev)
15420     return ExternCPrev;
15421 
15422   // Set a Declarator for the implicit definition: int foo();
15423   const char *Dummy;
15424   AttributeFactory attrFactory;
15425   DeclSpec DS(attrFactory);
15426   unsigned DiagID;
15427   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15428                                   Context.getPrintingPolicy());
15429   (void)Error; // Silence warning.
15430   assert(!Error && "Error setting up implicit decl!");
15431   SourceLocation NoLoc;
15432   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15433   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15434                                              /*IsAmbiguous=*/false,
15435                                              /*LParenLoc=*/NoLoc,
15436                                              /*Params=*/nullptr,
15437                                              /*NumParams=*/0,
15438                                              /*EllipsisLoc=*/NoLoc,
15439                                              /*RParenLoc=*/NoLoc,
15440                                              /*RefQualifierIsLvalueRef=*/true,
15441                                              /*RefQualifierLoc=*/NoLoc,
15442                                              /*MutableLoc=*/NoLoc, EST_None,
15443                                              /*ESpecRange=*/SourceRange(),
15444                                              /*Exceptions=*/nullptr,
15445                                              /*ExceptionRanges=*/nullptr,
15446                                              /*NumExceptions=*/0,
15447                                              /*NoexceptExpr=*/nullptr,
15448                                              /*ExceptionSpecTokens=*/nullptr,
15449                                              /*DeclsInPrototype=*/None, Loc,
15450                                              Loc, D),
15451                 std::move(DS.getAttributes()), SourceLocation());
15452   D.SetIdentifier(&II, Loc);
15453 
15454   // Insert this function into the enclosing block scope.
15455   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15456   FD->setImplicit();
15457 
15458   AddKnownFunctionAttributes(FD);
15459 
15460   return FD;
15461 }
15462 
15463 /// If this function is a C++ replaceable global allocation function
15464 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15465 /// adds any function attributes that we know a priori based on the standard.
15466 ///
15467 /// We need to check for duplicate attributes both here and where user-written
15468 /// attributes are applied to declarations.
15469 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15470     FunctionDecl *FD) {
15471   if (FD->isInvalidDecl())
15472     return;
15473 
15474   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15475       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15476     return;
15477 
15478   Optional<unsigned> AlignmentParam;
15479   bool IsNothrow = false;
15480   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15481     return;
15482 
15483   // C++2a [basic.stc.dynamic.allocation]p4:
15484   //   An allocation function that has a non-throwing exception specification
15485   //   indicates failure by returning a null pointer value. Any other allocation
15486   //   function never returns a null pointer value and indicates failure only by
15487   //   throwing an exception [...]
15488   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15489     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15490 
15491   // C++2a [basic.stc.dynamic.allocation]p2:
15492   //   An allocation function attempts to allocate the requested amount of
15493   //   storage. [...] If the request succeeds, the value returned by a
15494   //   replaceable allocation function is a [...] pointer value p0 different
15495   //   from any previously returned value p1 [...]
15496   //
15497   // However, this particular information is being added in codegen,
15498   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15499 
15500   // C++2a [basic.stc.dynamic.allocation]p2:
15501   //   An allocation function attempts to allocate the requested amount of
15502   //   storage. If it is successful, it returns the address of the start of a
15503   //   block of storage whose length in bytes is at least as large as the
15504   //   requested size.
15505   if (!FD->hasAttr<AllocSizeAttr>()) {
15506     FD->addAttr(AllocSizeAttr::CreateImplicit(
15507         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15508         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15509   }
15510 
15511   // C++2a [basic.stc.dynamic.allocation]p3:
15512   //   For an allocation function [...], the pointer returned on a successful
15513   //   call shall represent the address of storage that is aligned as follows:
15514   //   (3.1) If the allocation function takes an argument of type
15515   //         std​::​align_­val_­t, the storage will have the alignment
15516   //         specified by the value of this argument.
15517   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15518     FD->addAttr(AllocAlignAttr::CreateImplicit(
15519         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15520   }
15521 
15522   // FIXME:
15523   // C++2a [basic.stc.dynamic.allocation]p3:
15524   //   For an allocation function [...], the pointer returned on a successful
15525   //   call shall represent the address of storage that is aligned as follows:
15526   //   (3.2) Otherwise, if the allocation function is named operator new[],
15527   //         the storage is aligned for any object that does not have
15528   //         new-extended alignment ([basic.align]) and is no larger than the
15529   //         requested size.
15530   //   (3.3) Otherwise, the storage is aligned for any object that does not
15531   //         have new-extended alignment and is of the requested size.
15532 }
15533 
15534 /// Adds any function attributes that we know a priori based on
15535 /// the declaration of this function.
15536 ///
15537 /// These attributes can apply both to implicitly-declared builtins
15538 /// (like __builtin___printf_chk) or to library-declared functions
15539 /// like NSLog or printf.
15540 ///
15541 /// We need to check for duplicate attributes both here and where user-written
15542 /// attributes are applied to declarations.
15543 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15544   if (FD->isInvalidDecl())
15545     return;
15546 
15547   // If this is a built-in function, map its builtin attributes to
15548   // actual attributes.
15549   if (unsigned BuiltinID = FD->getBuiltinID()) {
15550     // Handle printf-formatting attributes.
15551     unsigned FormatIdx;
15552     bool HasVAListArg;
15553     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15554       if (!FD->hasAttr<FormatAttr>()) {
15555         const char *fmt = "printf";
15556         unsigned int NumParams = FD->getNumParams();
15557         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15558             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15559           fmt = "NSString";
15560         FD->addAttr(FormatAttr::CreateImplicit(Context,
15561                                                &Context.Idents.get(fmt),
15562                                                FormatIdx+1,
15563                                                HasVAListArg ? 0 : FormatIdx+2,
15564                                                FD->getLocation()));
15565       }
15566     }
15567     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15568                                              HasVAListArg)) {
15569      if (!FD->hasAttr<FormatAttr>())
15570        FD->addAttr(FormatAttr::CreateImplicit(Context,
15571                                               &Context.Idents.get("scanf"),
15572                                               FormatIdx+1,
15573                                               HasVAListArg ? 0 : FormatIdx+2,
15574                                               FD->getLocation()));
15575     }
15576 
15577     // Handle automatically recognized callbacks.
15578     SmallVector<int, 4> Encoding;
15579     if (!FD->hasAttr<CallbackAttr>() &&
15580         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15581       FD->addAttr(CallbackAttr::CreateImplicit(
15582           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15583 
15584     // Mark const if we don't care about errno and that is the only thing
15585     // preventing the function from being const. This allows IRgen to use LLVM
15586     // intrinsics for such functions.
15587     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15588         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15589       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15590 
15591     // We make "fma" on GNU or Windows const because we know it does not set
15592     // errno in those environments even though it could set errno based on the
15593     // C standard.
15594     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15595     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15596         !FD->hasAttr<ConstAttr>()) {
15597       switch (BuiltinID) {
15598       case Builtin::BI__builtin_fma:
15599       case Builtin::BI__builtin_fmaf:
15600       case Builtin::BI__builtin_fmal:
15601       case Builtin::BIfma:
15602       case Builtin::BIfmaf:
15603       case Builtin::BIfmal:
15604         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15605         break;
15606       default:
15607         break;
15608       }
15609     }
15610 
15611     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15612         !FD->hasAttr<ReturnsTwiceAttr>())
15613       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15614                                          FD->getLocation()));
15615     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15616       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15617     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15618       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15619     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15620       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15621     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15622         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15623       // Add the appropriate attribute, depending on the CUDA compilation mode
15624       // and which target the builtin belongs to. For example, during host
15625       // compilation, aux builtins are __device__, while the rest are __host__.
15626       if (getLangOpts().CUDAIsDevice !=
15627           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15628         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15629       else
15630         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15631     }
15632 
15633     // Add known guaranteed alignment for allocation functions.
15634     switch (BuiltinID) {
15635     case Builtin::BImemalign:
15636     case Builtin::BIaligned_alloc:
15637       if (!FD->hasAttr<AllocAlignAttr>())
15638         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15639                                                    FD->getLocation()));
15640       break;
15641     default:
15642       break;
15643     }
15644 
15645     // Add allocsize attribute for allocation functions.
15646     switch (BuiltinID) {
15647     case Builtin::BIcalloc:
15648       FD->addAttr(AllocSizeAttr::CreateImplicit(
15649           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15650       break;
15651     case Builtin::BImemalign:
15652     case Builtin::BIaligned_alloc:
15653     case Builtin::BIrealloc:
15654       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15655                                                 ParamIdx(), FD->getLocation()));
15656       break;
15657     case Builtin::BImalloc:
15658       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15659                                                 ParamIdx(), FD->getLocation()));
15660       break;
15661     default:
15662       break;
15663     }
15664   }
15665 
15666   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15667 
15668   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15669   // throw, add an implicit nothrow attribute to any extern "C" function we come
15670   // across.
15671   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15672       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15673     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15674     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15675       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15676   }
15677 
15678   IdentifierInfo *Name = FD->getIdentifier();
15679   if (!Name)
15680     return;
15681   if ((!getLangOpts().CPlusPlus &&
15682        FD->getDeclContext()->isTranslationUnit()) ||
15683       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15684        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15685        LinkageSpecDecl::lang_c)) {
15686     // Okay: this could be a libc/libm/Objective-C function we know
15687     // about.
15688   } else
15689     return;
15690 
15691   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15692     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15693     // target-specific builtins, perhaps?
15694     if (!FD->hasAttr<FormatAttr>())
15695       FD->addAttr(FormatAttr::CreateImplicit(Context,
15696                                              &Context.Idents.get("printf"), 2,
15697                                              Name->isStr("vasprintf") ? 0 : 3,
15698                                              FD->getLocation()));
15699   }
15700 
15701   if (Name->isStr("__CFStringMakeConstantString")) {
15702     // We already have a __builtin___CFStringMakeConstantString,
15703     // but builds that use -fno-constant-cfstrings don't go through that.
15704     if (!FD->hasAttr<FormatArgAttr>())
15705       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15706                                                 FD->getLocation()));
15707   }
15708 }
15709 
15710 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15711                                     TypeSourceInfo *TInfo) {
15712   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15713   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15714 
15715   if (!TInfo) {
15716     assert(D.isInvalidType() && "no declarator info for valid type");
15717     TInfo = Context.getTrivialTypeSourceInfo(T);
15718   }
15719 
15720   // Scope manipulation handled by caller.
15721   TypedefDecl *NewTD =
15722       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15723                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15724 
15725   // Bail out immediately if we have an invalid declaration.
15726   if (D.isInvalidType()) {
15727     NewTD->setInvalidDecl();
15728     return NewTD;
15729   }
15730 
15731   if (D.getDeclSpec().isModulePrivateSpecified()) {
15732     if (CurContext->isFunctionOrMethod())
15733       Diag(NewTD->getLocation(), diag::err_module_private_local)
15734           << 2 << NewTD
15735           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15736           << FixItHint::CreateRemoval(
15737                  D.getDeclSpec().getModulePrivateSpecLoc());
15738     else
15739       NewTD->setModulePrivate();
15740   }
15741 
15742   // C++ [dcl.typedef]p8:
15743   //   If the typedef declaration defines an unnamed class (or
15744   //   enum), the first typedef-name declared by the declaration
15745   //   to be that class type (or enum type) is used to denote the
15746   //   class type (or enum type) for linkage purposes only.
15747   // We need to check whether the type was declared in the declaration.
15748   switch (D.getDeclSpec().getTypeSpecType()) {
15749   case TST_enum:
15750   case TST_struct:
15751   case TST_interface:
15752   case TST_union:
15753   case TST_class: {
15754     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15755     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15756     break;
15757   }
15758 
15759   default:
15760     break;
15761   }
15762 
15763   return NewTD;
15764 }
15765 
15766 /// Check that this is a valid underlying type for an enum declaration.
15767 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15768   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15769   QualType T = TI->getType();
15770 
15771   if (T->isDependentType())
15772     return false;
15773 
15774   // This doesn't use 'isIntegralType' despite the error message mentioning
15775   // integral type because isIntegralType would also allow enum types in C.
15776   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15777     if (BT->isInteger())
15778       return false;
15779 
15780   if (T->isBitIntType())
15781     return false;
15782 
15783   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15784 }
15785 
15786 /// Check whether this is a valid redeclaration of a previous enumeration.
15787 /// \return true if the redeclaration was invalid.
15788 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15789                                   QualType EnumUnderlyingTy, bool IsFixed,
15790                                   const EnumDecl *Prev) {
15791   if (IsScoped != Prev->isScoped()) {
15792     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15793       << Prev->isScoped();
15794     Diag(Prev->getLocation(), diag::note_previous_declaration);
15795     return true;
15796   }
15797 
15798   if (IsFixed && Prev->isFixed()) {
15799     if (!EnumUnderlyingTy->isDependentType() &&
15800         !Prev->getIntegerType()->isDependentType() &&
15801         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15802                                         Prev->getIntegerType())) {
15803       // TODO: Highlight the underlying type of the redeclaration.
15804       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15805         << EnumUnderlyingTy << Prev->getIntegerType();
15806       Diag(Prev->getLocation(), diag::note_previous_declaration)
15807           << Prev->getIntegerTypeRange();
15808       return true;
15809     }
15810   } else if (IsFixed != Prev->isFixed()) {
15811     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15812       << Prev->isFixed();
15813     Diag(Prev->getLocation(), diag::note_previous_declaration);
15814     return true;
15815   }
15816 
15817   return false;
15818 }
15819 
15820 /// Get diagnostic %select index for tag kind for
15821 /// redeclaration diagnostic message.
15822 /// WARNING: Indexes apply to particular diagnostics only!
15823 ///
15824 /// \returns diagnostic %select index.
15825 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15826   switch (Tag) {
15827   case TTK_Struct: return 0;
15828   case TTK_Interface: return 1;
15829   case TTK_Class:  return 2;
15830   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15831   }
15832 }
15833 
15834 /// Determine if tag kind is a class-key compatible with
15835 /// class for redeclaration (class, struct, or __interface).
15836 ///
15837 /// \returns true iff the tag kind is compatible.
15838 static bool isClassCompatTagKind(TagTypeKind Tag)
15839 {
15840   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15841 }
15842 
15843 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15844                                              TagTypeKind TTK) {
15845   if (isa<TypedefDecl>(PrevDecl))
15846     return NTK_Typedef;
15847   else if (isa<TypeAliasDecl>(PrevDecl))
15848     return NTK_TypeAlias;
15849   else if (isa<ClassTemplateDecl>(PrevDecl))
15850     return NTK_Template;
15851   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15852     return NTK_TypeAliasTemplate;
15853   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15854     return NTK_TemplateTemplateArgument;
15855   switch (TTK) {
15856   case TTK_Struct:
15857   case TTK_Interface:
15858   case TTK_Class:
15859     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15860   case TTK_Union:
15861     return NTK_NonUnion;
15862   case TTK_Enum:
15863     return NTK_NonEnum;
15864   }
15865   llvm_unreachable("invalid TTK");
15866 }
15867 
15868 /// Determine whether a tag with a given kind is acceptable
15869 /// as a redeclaration of the given tag declaration.
15870 ///
15871 /// \returns true if the new tag kind is acceptable, false otherwise.
15872 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15873                                         TagTypeKind NewTag, bool isDefinition,
15874                                         SourceLocation NewTagLoc,
15875                                         const IdentifierInfo *Name) {
15876   // C++ [dcl.type.elab]p3:
15877   //   The class-key or enum keyword present in the
15878   //   elaborated-type-specifier shall agree in kind with the
15879   //   declaration to which the name in the elaborated-type-specifier
15880   //   refers. This rule also applies to the form of
15881   //   elaborated-type-specifier that declares a class-name or
15882   //   friend class since it can be construed as referring to the
15883   //   definition of the class. Thus, in any
15884   //   elaborated-type-specifier, the enum keyword shall be used to
15885   //   refer to an enumeration (7.2), the union class-key shall be
15886   //   used to refer to a union (clause 9), and either the class or
15887   //   struct class-key shall be used to refer to a class (clause 9)
15888   //   declared using the class or struct class-key.
15889   TagTypeKind OldTag = Previous->getTagKind();
15890   if (OldTag != NewTag &&
15891       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15892     return false;
15893 
15894   // Tags are compatible, but we might still want to warn on mismatched tags.
15895   // Non-class tags can't be mismatched at this point.
15896   if (!isClassCompatTagKind(NewTag))
15897     return true;
15898 
15899   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15900   // by our warning analysis. We don't want to warn about mismatches with (eg)
15901   // declarations in system headers that are designed to be specialized, but if
15902   // a user asks us to warn, we should warn if their code contains mismatched
15903   // declarations.
15904   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15905     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15906                                       Loc);
15907   };
15908   if (IsIgnoredLoc(NewTagLoc))
15909     return true;
15910 
15911   auto IsIgnored = [&](const TagDecl *Tag) {
15912     return IsIgnoredLoc(Tag->getLocation());
15913   };
15914   while (IsIgnored(Previous)) {
15915     Previous = Previous->getPreviousDecl();
15916     if (!Previous)
15917       return true;
15918     OldTag = Previous->getTagKind();
15919   }
15920 
15921   bool isTemplate = false;
15922   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15923     isTemplate = Record->getDescribedClassTemplate();
15924 
15925   if (inTemplateInstantiation()) {
15926     if (OldTag != NewTag) {
15927       // In a template instantiation, do not offer fix-its for tag mismatches
15928       // since they usually mess up the template instead of fixing the problem.
15929       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15930         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15931         << getRedeclDiagFromTagKind(OldTag);
15932       // FIXME: Note previous location?
15933     }
15934     return true;
15935   }
15936 
15937   if (isDefinition) {
15938     // On definitions, check all previous tags and issue a fix-it for each
15939     // one that doesn't match the current tag.
15940     if (Previous->getDefinition()) {
15941       // Don't suggest fix-its for redefinitions.
15942       return true;
15943     }
15944 
15945     bool previousMismatch = false;
15946     for (const TagDecl *I : Previous->redecls()) {
15947       if (I->getTagKind() != NewTag) {
15948         // Ignore previous declarations for which the warning was disabled.
15949         if (IsIgnored(I))
15950           continue;
15951 
15952         if (!previousMismatch) {
15953           previousMismatch = true;
15954           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15955             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15956             << getRedeclDiagFromTagKind(I->getTagKind());
15957         }
15958         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15959           << getRedeclDiagFromTagKind(NewTag)
15960           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15961                TypeWithKeyword::getTagTypeKindName(NewTag));
15962       }
15963     }
15964     return true;
15965   }
15966 
15967   // Identify the prevailing tag kind: this is the kind of the definition (if
15968   // there is a non-ignored definition), or otherwise the kind of the prior
15969   // (non-ignored) declaration.
15970   const TagDecl *PrevDef = Previous->getDefinition();
15971   if (PrevDef && IsIgnored(PrevDef))
15972     PrevDef = nullptr;
15973   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15974   if (Redecl->getTagKind() != NewTag) {
15975     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15976       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15977       << getRedeclDiagFromTagKind(OldTag);
15978     Diag(Redecl->getLocation(), diag::note_previous_use);
15979 
15980     // If there is a previous definition, suggest a fix-it.
15981     if (PrevDef) {
15982       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15983         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15984         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15985              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15986     }
15987   }
15988 
15989   return true;
15990 }
15991 
15992 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15993 /// from an outer enclosing namespace or file scope inside a friend declaration.
15994 /// This should provide the commented out code in the following snippet:
15995 ///   namespace N {
15996 ///     struct X;
15997 ///     namespace M {
15998 ///       struct Y { friend struct /*N::*/ X; };
15999 ///     }
16000 ///   }
16001 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16002                                          SourceLocation NameLoc) {
16003   // While the decl is in a namespace, do repeated lookup of that name and see
16004   // if we get the same namespace back.  If we do not, continue until
16005   // translation unit scope, at which point we have a fully qualified NNS.
16006   SmallVector<IdentifierInfo *, 4> Namespaces;
16007   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16008   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16009     // This tag should be declared in a namespace, which can only be enclosed by
16010     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16011     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16012     if (!Namespace || Namespace->isAnonymousNamespace())
16013       return FixItHint();
16014     IdentifierInfo *II = Namespace->getIdentifier();
16015     Namespaces.push_back(II);
16016     NamedDecl *Lookup = SemaRef.LookupSingleName(
16017         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16018     if (Lookup == Namespace)
16019       break;
16020   }
16021 
16022   // Once we have all the namespaces, reverse them to go outermost first, and
16023   // build an NNS.
16024   SmallString<64> Insertion;
16025   llvm::raw_svector_ostream OS(Insertion);
16026   if (DC->isTranslationUnit())
16027     OS << "::";
16028   std::reverse(Namespaces.begin(), Namespaces.end());
16029   for (auto *II : Namespaces)
16030     OS << II->getName() << "::";
16031   return FixItHint::CreateInsertion(NameLoc, Insertion);
16032 }
16033 
16034 /// Determine whether a tag originally declared in context \p OldDC can
16035 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16036 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16037 /// using-declaration).
16038 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16039                                          DeclContext *NewDC) {
16040   OldDC = OldDC->getRedeclContext();
16041   NewDC = NewDC->getRedeclContext();
16042 
16043   if (OldDC->Equals(NewDC))
16044     return true;
16045 
16046   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16047   // encloses the other).
16048   if (S.getLangOpts().MSVCCompat &&
16049       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16050     return true;
16051 
16052   return false;
16053 }
16054 
16055 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16056 /// former case, Name will be non-null.  In the later case, Name will be null.
16057 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16058 /// reference/declaration/definition of a tag.
16059 ///
16060 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16061 /// trailing-type-specifier) other than one in an alias-declaration.
16062 ///
16063 /// \param SkipBody If non-null, will be set to indicate if the caller should
16064 /// skip the definition of this tag and treat it as if it were a declaration.
16065 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16066                      SourceLocation KWLoc, CXXScopeSpec &SS,
16067                      IdentifierInfo *Name, SourceLocation NameLoc,
16068                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16069                      SourceLocation ModulePrivateLoc,
16070                      MultiTemplateParamsArg TemplateParameterLists,
16071                      bool &OwnedDecl, bool &IsDependent,
16072                      SourceLocation ScopedEnumKWLoc,
16073                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16074                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16075                      SkipBodyInfo *SkipBody) {
16076   // If this is not a definition, it must have a name.
16077   IdentifierInfo *OrigName = Name;
16078   assert((Name != nullptr || TUK == TUK_Definition) &&
16079          "Nameless record must be a definition!");
16080   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16081 
16082   OwnedDecl = false;
16083   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16084   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16085 
16086   // FIXME: Check member specializations more carefully.
16087   bool isMemberSpecialization = false;
16088   bool Invalid = false;
16089 
16090   // We only need to do this matching if we have template parameters
16091   // or a scope specifier, which also conveniently avoids this work
16092   // for non-C++ cases.
16093   if (TemplateParameterLists.size() > 0 ||
16094       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16095     if (TemplateParameterList *TemplateParams =
16096             MatchTemplateParametersToScopeSpecifier(
16097                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16098                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16099       if (Kind == TTK_Enum) {
16100         Diag(KWLoc, diag::err_enum_template);
16101         return nullptr;
16102       }
16103 
16104       if (TemplateParams->size() > 0) {
16105         // This is a declaration or definition of a class template (which may
16106         // be a member of another template).
16107 
16108         if (Invalid)
16109           return nullptr;
16110 
16111         OwnedDecl = false;
16112         DeclResult Result = CheckClassTemplate(
16113             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16114             AS, ModulePrivateLoc,
16115             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16116             TemplateParameterLists.data(), SkipBody);
16117         return Result.get();
16118       } else {
16119         // The "template<>" header is extraneous.
16120         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16121           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16122         isMemberSpecialization = true;
16123       }
16124     }
16125 
16126     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16127         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16128       return nullptr;
16129   }
16130 
16131   // Figure out the underlying type if this a enum declaration. We need to do
16132   // this early, because it's needed to detect if this is an incompatible
16133   // redeclaration.
16134   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16135   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16136 
16137   if (Kind == TTK_Enum) {
16138     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16139       // No underlying type explicitly specified, or we failed to parse the
16140       // type, default to int.
16141       EnumUnderlying = Context.IntTy.getTypePtr();
16142     } else if (UnderlyingType.get()) {
16143       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16144       // integral type; any cv-qualification is ignored.
16145       TypeSourceInfo *TI = nullptr;
16146       GetTypeFromParser(UnderlyingType.get(), &TI);
16147       EnumUnderlying = TI;
16148 
16149       if (CheckEnumUnderlyingType(TI))
16150         // Recover by falling back to int.
16151         EnumUnderlying = Context.IntTy.getTypePtr();
16152 
16153       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16154                                           UPPC_FixedUnderlyingType))
16155         EnumUnderlying = Context.IntTy.getTypePtr();
16156 
16157     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16158       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16159       // of 'int'. However, if this is an unfixed forward declaration, don't set
16160       // the underlying type unless the user enables -fms-compatibility. This
16161       // makes unfixed forward declared enums incomplete and is more conforming.
16162       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16163         EnumUnderlying = Context.IntTy.getTypePtr();
16164     }
16165   }
16166 
16167   DeclContext *SearchDC = CurContext;
16168   DeclContext *DC = CurContext;
16169   bool isStdBadAlloc = false;
16170   bool isStdAlignValT = false;
16171 
16172   RedeclarationKind Redecl = forRedeclarationInCurContext();
16173   if (TUK == TUK_Friend || TUK == TUK_Reference)
16174     Redecl = NotForRedeclaration;
16175 
16176   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16177   /// implemented asks for structural equivalence checking, the returned decl
16178   /// here is passed back to the parser, allowing the tag body to be parsed.
16179   auto createTagFromNewDecl = [&]() -> TagDecl * {
16180     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16181     // If there is an identifier, use the location of the identifier as the
16182     // location of the decl, otherwise use the location of the struct/union
16183     // keyword.
16184     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16185     TagDecl *New = nullptr;
16186 
16187     if (Kind == TTK_Enum) {
16188       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16189                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16190       // If this is an undefined enum, bail.
16191       if (TUK != TUK_Definition && !Invalid)
16192         return nullptr;
16193       if (EnumUnderlying) {
16194         EnumDecl *ED = cast<EnumDecl>(New);
16195         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16196           ED->setIntegerTypeSourceInfo(TI);
16197         else
16198           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16199         ED->setPromotionType(ED->getIntegerType());
16200       }
16201     } else { // struct/union
16202       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16203                                nullptr);
16204     }
16205 
16206     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16207       // Add alignment attributes if necessary; these attributes are checked
16208       // when the ASTContext lays out the structure.
16209       //
16210       // It is important for implementing the correct semantics that this
16211       // happen here (in ActOnTag). The #pragma pack stack is
16212       // maintained as a result of parser callbacks which can occur at
16213       // many points during the parsing of a struct declaration (because
16214       // the #pragma tokens are effectively skipped over during the
16215       // parsing of the struct).
16216       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16217         AddAlignmentAttributesForRecord(RD);
16218         AddMsStructLayoutForRecord(RD);
16219       }
16220     }
16221     New->setLexicalDeclContext(CurContext);
16222     return New;
16223   };
16224 
16225   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16226   if (Name && SS.isNotEmpty()) {
16227     // We have a nested-name tag ('struct foo::bar').
16228 
16229     // Check for invalid 'foo::'.
16230     if (SS.isInvalid()) {
16231       Name = nullptr;
16232       goto CreateNewDecl;
16233     }
16234 
16235     // If this is a friend or a reference to a class in a dependent
16236     // context, don't try to make a decl for it.
16237     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16238       DC = computeDeclContext(SS, false);
16239       if (!DC) {
16240         IsDependent = true;
16241         return nullptr;
16242       }
16243     } else {
16244       DC = computeDeclContext(SS, true);
16245       if (!DC) {
16246         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16247           << SS.getRange();
16248         return nullptr;
16249       }
16250     }
16251 
16252     if (RequireCompleteDeclContext(SS, DC))
16253       return nullptr;
16254 
16255     SearchDC = DC;
16256     // Look-up name inside 'foo::'.
16257     LookupQualifiedName(Previous, DC);
16258 
16259     if (Previous.isAmbiguous())
16260       return nullptr;
16261 
16262     if (Previous.empty()) {
16263       // Name lookup did not find anything. However, if the
16264       // nested-name-specifier refers to the current instantiation,
16265       // and that current instantiation has any dependent base
16266       // classes, we might find something at instantiation time: treat
16267       // this as a dependent elaborated-type-specifier.
16268       // But this only makes any sense for reference-like lookups.
16269       if (Previous.wasNotFoundInCurrentInstantiation() &&
16270           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16271         IsDependent = true;
16272         return nullptr;
16273       }
16274 
16275       // A tag 'foo::bar' must already exist.
16276       Diag(NameLoc, diag::err_not_tag_in_scope)
16277         << Kind << Name << DC << SS.getRange();
16278       Name = nullptr;
16279       Invalid = true;
16280       goto CreateNewDecl;
16281     }
16282   } else if (Name) {
16283     // C++14 [class.mem]p14:
16284     //   If T is the name of a class, then each of the following shall have a
16285     //   name different from T:
16286     //    -- every member of class T that is itself a type
16287     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16288         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16289       return nullptr;
16290 
16291     // If this is a named struct, check to see if there was a previous forward
16292     // declaration or definition.
16293     // FIXME: We're looking into outer scopes here, even when we
16294     // shouldn't be. Doing so can result in ambiguities that we
16295     // shouldn't be diagnosing.
16296     LookupName(Previous, S);
16297 
16298     // When declaring or defining a tag, ignore ambiguities introduced
16299     // by types using'ed into this scope.
16300     if (Previous.isAmbiguous() &&
16301         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16302       LookupResult::Filter F = Previous.makeFilter();
16303       while (F.hasNext()) {
16304         NamedDecl *ND = F.next();
16305         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16306                 SearchDC->getRedeclContext()))
16307           F.erase();
16308       }
16309       F.done();
16310     }
16311 
16312     // C++11 [namespace.memdef]p3:
16313     //   If the name in a friend declaration is neither qualified nor
16314     //   a template-id and the declaration is a function or an
16315     //   elaborated-type-specifier, the lookup to determine whether
16316     //   the entity has been previously declared shall not consider
16317     //   any scopes outside the innermost enclosing namespace.
16318     //
16319     // MSVC doesn't implement the above rule for types, so a friend tag
16320     // declaration may be a redeclaration of a type declared in an enclosing
16321     // scope.  They do implement this rule for friend functions.
16322     //
16323     // Does it matter that this should be by scope instead of by
16324     // semantic context?
16325     if (!Previous.empty() && TUK == TUK_Friend) {
16326       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16327       LookupResult::Filter F = Previous.makeFilter();
16328       bool FriendSawTagOutsideEnclosingNamespace = false;
16329       while (F.hasNext()) {
16330         NamedDecl *ND = F.next();
16331         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16332         if (DC->isFileContext() &&
16333             !EnclosingNS->Encloses(ND->getDeclContext())) {
16334           if (getLangOpts().MSVCCompat)
16335             FriendSawTagOutsideEnclosingNamespace = true;
16336           else
16337             F.erase();
16338         }
16339       }
16340       F.done();
16341 
16342       // Diagnose this MSVC extension in the easy case where lookup would have
16343       // unambiguously found something outside the enclosing namespace.
16344       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16345         NamedDecl *ND = Previous.getFoundDecl();
16346         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16347             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16348       }
16349     }
16350 
16351     // Note:  there used to be some attempt at recovery here.
16352     if (Previous.isAmbiguous())
16353       return nullptr;
16354 
16355     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16356       // FIXME: This makes sure that we ignore the contexts associated
16357       // with C structs, unions, and enums when looking for a matching
16358       // tag declaration or definition. See the similar lookup tweak
16359       // in Sema::LookupName; is there a better way to deal with this?
16360       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16361         SearchDC = SearchDC->getParent();
16362     } else if (getLangOpts().CPlusPlus) {
16363       // Inside ObjCContainer want to keep it as a lexical decl context but go
16364       // past it (most often to TranslationUnit) to find the semantic decl
16365       // context.
16366       while (isa<ObjCContainerDecl>(SearchDC))
16367         SearchDC = SearchDC->getParent();
16368     }
16369   } else if (getLangOpts().CPlusPlus) {
16370     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16371     // TagDecl the same way as we skip it for named TagDecl.
16372     while (isa<ObjCContainerDecl>(SearchDC))
16373       SearchDC = SearchDC->getParent();
16374   }
16375 
16376   if (Previous.isSingleResult() &&
16377       Previous.getFoundDecl()->isTemplateParameter()) {
16378     // Maybe we will complain about the shadowed template parameter.
16379     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16380     // Just pretend that we didn't see the previous declaration.
16381     Previous.clear();
16382   }
16383 
16384   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16385       DC->Equals(getStdNamespace())) {
16386     if (Name->isStr("bad_alloc")) {
16387       // This is a declaration of or a reference to "std::bad_alloc".
16388       isStdBadAlloc = true;
16389 
16390       // If std::bad_alloc has been implicitly declared (but made invisible to
16391       // name lookup), fill in this implicit declaration as the previous
16392       // declaration, so that the declarations get chained appropriately.
16393       if (Previous.empty() && StdBadAlloc)
16394         Previous.addDecl(getStdBadAlloc());
16395     } else if (Name->isStr("align_val_t")) {
16396       isStdAlignValT = true;
16397       if (Previous.empty() && StdAlignValT)
16398         Previous.addDecl(getStdAlignValT());
16399     }
16400   }
16401 
16402   // If we didn't find a previous declaration, and this is a reference
16403   // (or friend reference), move to the correct scope.  In C++, we
16404   // also need to do a redeclaration lookup there, just in case
16405   // there's a shadow friend decl.
16406   if (Name && Previous.empty() &&
16407       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16408     if (Invalid) goto CreateNewDecl;
16409     assert(SS.isEmpty());
16410 
16411     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16412       // C++ [basic.scope.pdecl]p5:
16413       //   -- for an elaborated-type-specifier of the form
16414       //
16415       //          class-key identifier
16416       //
16417       //      if the elaborated-type-specifier is used in the
16418       //      decl-specifier-seq or parameter-declaration-clause of a
16419       //      function defined in namespace scope, the identifier is
16420       //      declared as a class-name in the namespace that contains
16421       //      the declaration; otherwise, except as a friend
16422       //      declaration, the identifier is declared in the smallest
16423       //      non-class, non-function-prototype scope that contains the
16424       //      declaration.
16425       //
16426       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16427       // C structs and unions.
16428       //
16429       // It is an error in C++ to declare (rather than define) an enum
16430       // type, including via an elaborated type specifier.  We'll
16431       // diagnose that later; for now, declare the enum in the same
16432       // scope as we would have picked for any other tag type.
16433       //
16434       // GNU C also supports this behavior as part of its incomplete
16435       // enum types extension, while GNU C++ does not.
16436       //
16437       // Find the context where we'll be declaring the tag.
16438       // FIXME: We would like to maintain the current DeclContext as the
16439       // lexical context,
16440       SearchDC = getTagInjectionContext(SearchDC);
16441 
16442       // Find the scope where we'll be declaring the tag.
16443       S = getTagInjectionScope(S, getLangOpts());
16444     } else {
16445       assert(TUK == TUK_Friend);
16446       // C++ [namespace.memdef]p3:
16447       //   If a friend declaration in a non-local class first declares a
16448       //   class or function, the friend class or function is a member of
16449       //   the innermost enclosing namespace.
16450       SearchDC = SearchDC->getEnclosingNamespaceContext();
16451     }
16452 
16453     // In C++, we need to do a redeclaration lookup to properly
16454     // diagnose some problems.
16455     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16456     // hidden declaration so that we don't get ambiguity errors when using a
16457     // type declared by an elaborated-type-specifier.  In C that is not correct
16458     // and we should instead merge compatible types found by lookup.
16459     if (getLangOpts().CPlusPlus) {
16460       // FIXME: This can perform qualified lookups into function contexts,
16461       // which are meaningless.
16462       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16463       LookupQualifiedName(Previous, SearchDC);
16464     } else {
16465       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16466       LookupName(Previous, S);
16467     }
16468   }
16469 
16470   // If we have a known previous declaration to use, then use it.
16471   if (Previous.empty() && SkipBody && SkipBody->Previous)
16472     Previous.addDecl(SkipBody->Previous);
16473 
16474   if (!Previous.empty()) {
16475     NamedDecl *PrevDecl = Previous.getFoundDecl();
16476     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16477 
16478     // It's okay to have a tag decl in the same scope as a typedef
16479     // which hides a tag decl in the same scope.  Finding this
16480     // with a redeclaration lookup can only actually happen in C++.
16481     //
16482     // This is also okay for elaborated-type-specifiers, which is
16483     // technically forbidden by the current standard but which is
16484     // okay according to the likely resolution of an open issue;
16485     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16486     if (getLangOpts().CPlusPlus) {
16487       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16488         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16489           TagDecl *Tag = TT->getDecl();
16490           if (Tag->getDeclName() == Name &&
16491               Tag->getDeclContext()->getRedeclContext()
16492                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16493             PrevDecl = Tag;
16494             Previous.clear();
16495             Previous.addDecl(Tag);
16496             Previous.resolveKind();
16497           }
16498         }
16499       }
16500     }
16501 
16502     // If this is a redeclaration of a using shadow declaration, it must
16503     // declare a tag in the same context. In MSVC mode, we allow a
16504     // redefinition if either context is within the other.
16505     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16506       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16507       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16508           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16509           !(OldTag && isAcceptableTagRedeclContext(
16510                           *this, OldTag->getDeclContext(), SearchDC))) {
16511         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16512         Diag(Shadow->getTargetDecl()->getLocation(),
16513              diag::note_using_decl_target);
16514         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16515             << 0;
16516         // Recover by ignoring the old declaration.
16517         Previous.clear();
16518         goto CreateNewDecl;
16519       }
16520     }
16521 
16522     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16523       // If this is a use of a previous tag, or if the tag is already declared
16524       // in the same scope (so that the definition/declaration completes or
16525       // rementions the tag), reuse the decl.
16526       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16527           isDeclInScope(DirectPrevDecl, SearchDC, S,
16528                         SS.isNotEmpty() || isMemberSpecialization)) {
16529         // Make sure that this wasn't declared as an enum and now used as a
16530         // struct or something similar.
16531         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16532                                           TUK == TUK_Definition, KWLoc,
16533                                           Name)) {
16534           bool SafeToContinue
16535             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16536                Kind != TTK_Enum);
16537           if (SafeToContinue)
16538             Diag(KWLoc, diag::err_use_with_wrong_tag)
16539               << Name
16540               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16541                                               PrevTagDecl->getKindName());
16542           else
16543             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16544           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16545 
16546           if (SafeToContinue)
16547             Kind = PrevTagDecl->getTagKind();
16548           else {
16549             // Recover by making this an anonymous redefinition.
16550             Name = nullptr;
16551             Previous.clear();
16552             Invalid = true;
16553           }
16554         }
16555 
16556         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16557           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16558           if (TUK == TUK_Reference || TUK == TUK_Friend)
16559             return PrevTagDecl;
16560 
16561           QualType EnumUnderlyingTy;
16562           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16563             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16564           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16565             EnumUnderlyingTy = QualType(T, 0);
16566 
16567           // All conflicts with previous declarations are recovered by
16568           // returning the previous declaration, unless this is a definition,
16569           // in which case we want the caller to bail out.
16570           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16571                                      ScopedEnum, EnumUnderlyingTy,
16572                                      IsFixed, PrevEnum))
16573             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16574         }
16575 
16576         // C++11 [class.mem]p1:
16577         //   A member shall not be declared twice in the member-specification,
16578         //   except that a nested class or member class template can be declared
16579         //   and then later defined.
16580         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16581             S->isDeclScope(PrevDecl)) {
16582           Diag(NameLoc, diag::ext_member_redeclared);
16583           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16584         }
16585 
16586         if (!Invalid) {
16587           // If this is a use, just return the declaration we found, unless
16588           // we have attributes.
16589           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16590             if (!Attrs.empty()) {
16591               // FIXME: Diagnose these attributes. For now, we create a new
16592               // declaration to hold them.
16593             } else if (TUK == TUK_Reference &&
16594                        (PrevTagDecl->getFriendObjectKind() ==
16595                             Decl::FOK_Undeclared ||
16596                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16597                        SS.isEmpty()) {
16598               // This declaration is a reference to an existing entity, but
16599               // has different visibility from that entity: it either makes
16600               // a friend visible or it makes a type visible in a new module.
16601               // In either case, create a new declaration. We only do this if
16602               // the declaration would have meant the same thing if no prior
16603               // declaration were found, that is, if it was found in the same
16604               // scope where we would have injected a declaration.
16605               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16606                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16607                 return PrevTagDecl;
16608               // This is in the injected scope, create a new declaration in
16609               // that scope.
16610               S = getTagInjectionScope(S, getLangOpts());
16611             } else {
16612               return PrevTagDecl;
16613             }
16614           }
16615 
16616           // Diagnose attempts to redefine a tag.
16617           if (TUK == TUK_Definition) {
16618             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16619               // If we're defining a specialization and the previous definition
16620               // is from an implicit instantiation, don't emit an error
16621               // here; we'll catch this in the general case below.
16622               bool IsExplicitSpecializationAfterInstantiation = false;
16623               if (isMemberSpecialization) {
16624                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16625                   IsExplicitSpecializationAfterInstantiation =
16626                     RD->getTemplateSpecializationKind() !=
16627                     TSK_ExplicitSpecialization;
16628                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16629                   IsExplicitSpecializationAfterInstantiation =
16630                     ED->getTemplateSpecializationKind() !=
16631                     TSK_ExplicitSpecialization;
16632               }
16633 
16634               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16635               // not keep more that one definition around (merge them). However,
16636               // ensure the decl passes the structural compatibility check in
16637               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16638               NamedDecl *Hidden = nullptr;
16639               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16640                 // There is a definition of this tag, but it is not visible. We
16641                 // explicitly make use of C++'s one definition rule here, and
16642                 // assume that this definition is identical to the hidden one
16643                 // we already have. Make the existing definition visible and
16644                 // use it in place of this one.
16645                 if (!getLangOpts().CPlusPlus) {
16646                   // Postpone making the old definition visible until after we
16647                   // complete parsing the new one and do the structural
16648                   // comparison.
16649                   SkipBody->CheckSameAsPrevious = true;
16650                   SkipBody->New = createTagFromNewDecl();
16651                   SkipBody->Previous = Def;
16652                   return Def;
16653                 } else {
16654                   SkipBody->ShouldSkip = true;
16655                   SkipBody->Previous = Def;
16656                   makeMergedDefinitionVisible(Hidden);
16657                   // Carry on and handle it like a normal definition. We'll
16658                   // skip starting the definitiion later.
16659                 }
16660               } else if (!IsExplicitSpecializationAfterInstantiation) {
16661                 // A redeclaration in function prototype scope in C isn't
16662                 // visible elsewhere, so merely issue a warning.
16663                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16664                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16665                 else
16666                   Diag(NameLoc, diag::err_redefinition) << Name;
16667                 notePreviousDefinition(Def,
16668                                        NameLoc.isValid() ? NameLoc : KWLoc);
16669                 // If this is a redefinition, recover by making this
16670                 // struct be anonymous, which will make any later
16671                 // references get the previous definition.
16672                 Name = nullptr;
16673                 Previous.clear();
16674                 Invalid = true;
16675               }
16676             } else {
16677               // If the type is currently being defined, complain
16678               // about a nested redefinition.
16679               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16680               if (TD->isBeingDefined()) {
16681                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16682                 Diag(PrevTagDecl->getLocation(),
16683                      diag::note_previous_definition);
16684                 Name = nullptr;
16685                 Previous.clear();
16686                 Invalid = true;
16687               }
16688             }
16689 
16690             // Okay, this is definition of a previously declared or referenced
16691             // tag. We're going to create a new Decl for it.
16692           }
16693 
16694           // Okay, we're going to make a redeclaration.  If this is some kind
16695           // of reference, make sure we build the redeclaration in the same DC
16696           // as the original, and ignore the current access specifier.
16697           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16698             SearchDC = PrevTagDecl->getDeclContext();
16699             AS = AS_none;
16700           }
16701         }
16702         // If we get here we have (another) forward declaration or we
16703         // have a definition.  Just create a new decl.
16704 
16705       } else {
16706         // If we get here, this is a definition of a new tag type in a nested
16707         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16708         // new decl/type.  We set PrevDecl to NULL so that the entities
16709         // have distinct types.
16710         Previous.clear();
16711       }
16712       // If we get here, we're going to create a new Decl. If PrevDecl
16713       // is non-NULL, it's a definition of the tag declared by
16714       // PrevDecl. If it's NULL, we have a new definition.
16715 
16716     // Otherwise, PrevDecl is not a tag, but was found with tag
16717     // lookup.  This is only actually possible in C++, where a few
16718     // things like templates still live in the tag namespace.
16719     } else {
16720       // Use a better diagnostic if an elaborated-type-specifier
16721       // found the wrong kind of type on the first
16722       // (non-redeclaration) lookup.
16723       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16724           !Previous.isForRedeclaration()) {
16725         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16726         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16727                                                        << Kind;
16728         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16729         Invalid = true;
16730 
16731       // Otherwise, only diagnose if the declaration is in scope.
16732       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16733                                 SS.isNotEmpty() || isMemberSpecialization)) {
16734         // do nothing
16735 
16736       // Diagnose implicit declarations introduced by elaborated types.
16737       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16738         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16739         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16740         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16741         Invalid = true;
16742 
16743       // Otherwise it's a declaration.  Call out a particularly common
16744       // case here.
16745       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16746         unsigned Kind = 0;
16747         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16748         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16749           << Name << Kind << TND->getUnderlyingType();
16750         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16751         Invalid = true;
16752 
16753       // Otherwise, diagnose.
16754       } else {
16755         // The tag name clashes with something else in the target scope,
16756         // issue an error and recover by making this tag be anonymous.
16757         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16758         notePreviousDefinition(PrevDecl, NameLoc);
16759         Name = nullptr;
16760         Invalid = true;
16761       }
16762 
16763       // The existing declaration isn't relevant to us; we're in a
16764       // new scope, so clear out the previous declaration.
16765       Previous.clear();
16766     }
16767   }
16768 
16769 CreateNewDecl:
16770 
16771   TagDecl *PrevDecl = nullptr;
16772   if (Previous.isSingleResult())
16773     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16774 
16775   // If there is an identifier, use the location of the identifier as the
16776   // location of the decl, otherwise use the location of the struct/union
16777   // keyword.
16778   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16779 
16780   // Otherwise, create a new declaration. If there is a previous
16781   // declaration of the same entity, the two will be linked via
16782   // PrevDecl.
16783   TagDecl *New;
16784 
16785   if (Kind == TTK_Enum) {
16786     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16787     // enum X { A, B, C } D;    D should chain to X.
16788     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16789                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16790                            ScopedEnumUsesClassTag, IsFixed);
16791 
16792     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16793       StdAlignValT = cast<EnumDecl>(New);
16794 
16795     // If this is an undefined enum, warn.
16796     if (TUK != TUK_Definition && !Invalid) {
16797       TagDecl *Def;
16798       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16799         // C++0x: 7.2p2: opaque-enum-declaration.
16800         // Conflicts are diagnosed above. Do nothing.
16801       }
16802       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16803         Diag(Loc, diag::ext_forward_ref_enum_def)
16804           << New;
16805         Diag(Def->getLocation(), diag::note_previous_definition);
16806       } else {
16807         unsigned DiagID = diag::ext_forward_ref_enum;
16808         if (getLangOpts().MSVCCompat)
16809           DiagID = diag::ext_ms_forward_ref_enum;
16810         else if (getLangOpts().CPlusPlus)
16811           DiagID = diag::err_forward_ref_enum;
16812         Diag(Loc, DiagID);
16813       }
16814     }
16815 
16816     if (EnumUnderlying) {
16817       EnumDecl *ED = cast<EnumDecl>(New);
16818       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16819         ED->setIntegerTypeSourceInfo(TI);
16820       else
16821         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16822       ED->setPromotionType(ED->getIntegerType());
16823       assert(ED->isComplete() && "enum with type should be complete");
16824     }
16825   } else {
16826     // struct/union/class
16827 
16828     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16829     // struct X { int A; } D;    D should chain to X.
16830     if (getLangOpts().CPlusPlus) {
16831       // FIXME: Look for a way to use RecordDecl for simple structs.
16832       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16833                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16834 
16835       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16836         StdBadAlloc = cast<CXXRecordDecl>(New);
16837     } else
16838       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16839                                cast_or_null<RecordDecl>(PrevDecl));
16840   }
16841 
16842   // C++11 [dcl.type]p3:
16843   //   A type-specifier-seq shall not define a class or enumeration [...].
16844   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16845       TUK == TUK_Definition) {
16846     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16847       << Context.getTagDeclType(New);
16848     Invalid = true;
16849   }
16850 
16851   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16852       DC->getDeclKind() == Decl::Enum) {
16853     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16854       << Context.getTagDeclType(New);
16855     Invalid = true;
16856   }
16857 
16858   // Maybe add qualifier info.
16859   if (SS.isNotEmpty()) {
16860     if (SS.isSet()) {
16861       // If this is either a declaration or a definition, check the
16862       // nested-name-specifier against the current context.
16863       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16864           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16865                                        isMemberSpecialization))
16866         Invalid = true;
16867 
16868       New->setQualifierInfo(SS.getWithLocInContext(Context));
16869       if (TemplateParameterLists.size() > 0) {
16870         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16871       }
16872     }
16873     else
16874       Invalid = true;
16875   }
16876 
16877   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16878     // Add alignment attributes if necessary; these attributes are checked when
16879     // the ASTContext lays out the structure.
16880     //
16881     // It is important for implementing the correct semantics that this
16882     // happen here (in ActOnTag). The #pragma pack stack is
16883     // maintained as a result of parser callbacks which can occur at
16884     // many points during the parsing of a struct declaration (because
16885     // the #pragma tokens are effectively skipped over during the
16886     // parsing of the struct).
16887     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16888       AddAlignmentAttributesForRecord(RD);
16889       AddMsStructLayoutForRecord(RD);
16890     }
16891   }
16892 
16893   if (ModulePrivateLoc.isValid()) {
16894     if (isMemberSpecialization)
16895       Diag(New->getLocation(), diag::err_module_private_specialization)
16896         << 2
16897         << FixItHint::CreateRemoval(ModulePrivateLoc);
16898     // __module_private__ does not apply to local classes. However, we only
16899     // diagnose this as an error when the declaration specifiers are
16900     // freestanding. Here, we just ignore the __module_private__.
16901     else if (!SearchDC->isFunctionOrMethod())
16902       New->setModulePrivate();
16903   }
16904 
16905   // If this is a specialization of a member class (of a class template),
16906   // check the specialization.
16907   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16908     Invalid = true;
16909 
16910   // If we're declaring or defining a tag in function prototype scope in C,
16911   // note that this type can only be used within the function and add it to
16912   // the list of decls to inject into the function definition scope.
16913   if ((Name || Kind == TTK_Enum) &&
16914       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16915     if (getLangOpts().CPlusPlus) {
16916       // C++ [dcl.fct]p6:
16917       //   Types shall not be defined in return or parameter types.
16918       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16919         Diag(Loc, diag::err_type_defined_in_param_type)
16920             << Name;
16921         Invalid = true;
16922       }
16923     } else if (!PrevDecl) {
16924       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16925     }
16926   }
16927 
16928   if (Invalid)
16929     New->setInvalidDecl();
16930 
16931   // Set the lexical context. If the tag has a C++ scope specifier, the
16932   // lexical context will be different from the semantic context.
16933   New->setLexicalDeclContext(CurContext);
16934 
16935   // Mark this as a friend decl if applicable.
16936   // In Microsoft mode, a friend declaration also acts as a forward
16937   // declaration so we always pass true to setObjectOfFriendDecl to make
16938   // the tag name visible.
16939   if (TUK == TUK_Friend)
16940     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16941 
16942   // Set the access specifier.
16943   if (!Invalid && SearchDC->isRecord())
16944     SetMemberAccessSpecifier(New, PrevDecl, AS);
16945 
16946   if (PrevDecl)
16947     CheckRedeclarationInModule(New, PrevDecl);
16948 
16949   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16950     New->startDefinition();
16951 
16952   ProcessDeclAttributeList(S, New, Attrs);
16953   AddPragmaAttributes(S, New);
16954 
16955   // If this has an identifier, add it to the scope stack.
16956   if (TUK == TUK_Friend) {
16957     // We might be replacing an existing declaration in the lookup tables;
16958     // if so, borrow its access specifier.
16959     if (PrevDecl)
16960       New->setAccess(PrevDecl->getAccess());
16961 
16962     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16963     DC->makeDeclVisibleInContext(New);
16964     if (Name) // can be null along some error paths
16965       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16966         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16967   } else if (Name) {
16968     S = getNonFieldDeclScope(S);
16969     PushOnScopeChains(New, S, true);
16970   } else {
16971     CurContext->addDecl(New);
16972   }
16973 
16974   // If this is the C FILE type, notify the AST context.
16975   if (IdentifierInfo *II = New->getIdentifier())
16976     if (!New->isInvalidDecl() &&
16977         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16978         II->isStr("FILE"))
16979       Context.setFILEDecl(New);
16980 
16981   if (PrevDecl)
16982     mergeDeclAttributes(New, PrevDecl);
16983 
16984   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16985     inferGslOwnerPointerAttribute(CXXRD);
16986 
16987   // If there's a #pragma GCC visibility in scope, set the visibility of this
16988   // record.
16989   AddPushedVisibilityAttribute(New);
16990 
16991   if (isMemberSpecialization && !New->isInvalidDecl())
16992     CompleteMemberSpecialization(New, Previous);
16993 
16994   OwnedDecl = true;
16995   // In C++, don't return an invalid declaration. We can't recover well from
16996   // the cases where we make the type anonymous.
16997   if (Invalid && getLangOpts().CPlusPlus) {
16998     if (New->isBeingDefined())
16999       if (auto RD = dyn_cast<RecordDecl>(New))
17000         RD->completeDefinition();
17001     return nullptr;
17002   } else if (SkipBody && SkipBody->ShouldSkip) {
17003     return SkipBody->Previous;
17004   } else {
17005     return New;
17006   }
17007 }
17008 
17009 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17010   AdjustDeclIfTemplate(TagD);
17011   TagDecl *Tag = cast<TagDecl>(TagD);
17012 
17013   // Enter the tag context.
17014   PushDeclContext(S, Tag);
17015 
17016   ActOnDocumentableDecl(TagD);
17017 
17018   // If there's a #pragma GCC visibility in scope, set the visibility of this
17019   // record.
17020   AddPushedVisibilityAttribute(Tag);
17021 }
17022 
17023 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17024   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17025     return false;
17026 
17027   // Make the previous decl visible.
17028   makeMergedDefinitionVisible(SkipBody.Previous);
17029   return true;
17030 }
17031 
17032 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17033   assert(IDecl->getLexicalParent() == CurContext &&
17034       "The next DeclContext should be lexically contained in the current one.");
17035   CurContext = IDecl;
17036 }
17037 
17038 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17039                                            SourceLocation FinalLoc,
17040                                            bool IsFinalSpelledSealed,
17041                                            bool IsAbstract,
17042                                            SourceLocation LBraceLoc) {
17043   AdjustDeclIfTemplate(TagD);
17044   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17045 
17046   FieldCollector->StartClass();
17047 
17048   if (!Record->getIdentifier())
17049     return;
17050 
17051   if (IsAbstract)
17052     Record->markAbstract();
17053 
17054   if (FinalLoc.isValid()) {
17055     Record->addAttr(FinalAttr::Create(
17056         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17057         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17058   }
17059   // C++ [class]p2:
17060   //   [...] The class-name is also inserted into the scope of the
17061   //   class itself; this is known as the injected-class-name. For
17062   //   purposes of access checking, the injected-class-name is treated
17063   //   as if it were a public member name.
17064   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17065       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17066       Record->getLocation(), Record->getIdentifier(),
17067       /*PrevDecl=*/nullptr,
17068       /*DelayTypeCreation=*/true);
17069   Context.getTypeDeclType(InjectedClassName, Record);
17070   InjectedClassName->setImplicit();
17071   InjectedClassName->setAccess(AS_public);
17072   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17073       InjectedClassName->setDescribedClassTemplate(Template);
17074   PushOnScopeChains(InjectedClassName, S);
17075   assert(InjectedClassName->isInjectedClassName() &&
17076          "Broken injected-class-name");
17077 }
17078 
17079 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17080                                     SourceRange BraceRange) {
17081   AdjustDeclIfTemplate(TagD);
17082   TagDecl *Tag = cast<TagDecl>(TagD);
17083   Tag->setBraceRange(BraceRange);
17084 
17085   // Make sure we "complete" the definition even it is invalid.
17086   if (Tag->isBeingDefined()) {
17087     assert(Tag->isInvalidDecl() && "We should already have completed it");
17088     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17089       RD->completeDefinition();
17090   }
17091 
17092   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17093     FieldCollector->FinishClass();
17094     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17095       auto *Def = RD->getDefinition();
17096       assert(Def && "The record is expected to have a completed definition");
17097       unsigned NumInitMethods = 0;
17098       for (auto *Method : Def->methods()) {
17099         if (!Method->getIdentifier())
17100             continue;
17101         if (Method->getName() == "__init")
17102           NumInitMethods++;
17103       }
17104       if (NumInitMethods > 1 || !Def->hasInitMethod())
17105         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17106     }
17107   }
17108 
17109   // Exit this scope of this tag's definition.
17110   PopDeclContext();
17111 
17112   if (getCurLexicalContext()->isObjCContainer() &&
17113       Tag->getDeclContext()->isFileContext())
17114     Tag->setTopLevelDeclInObjCContainer();
17115 
17116   // Notify the consumer that we've defined a tag.
17117   if (!Tag->isInvalidDecl())
17118     Consumer.HandleTagDeclDefinition(Tag);
17119 
17120   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17121   // from XLs and instead matches the XL #pragma pack(1) behavior.
17122   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17123       AlignPackStack.hasValue()) {
17124     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17125     // Only diagnose #pragma align(packed).
17126     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17127       return;
17128     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17129     if (!RD)
17130       return;
17131     // Only warn if there is at least 1 bitfield member.
17132     if (llvm::any_of(RD->fields(),
17133                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17134       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17135   }
17136 }
17137 
17138 void Sema::ActOnObjCContainerFinishDefinition() {
17139   // Exit this scope of this interface definition.
17140   PopDeclContext();
17141 }
17142 
17143 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17144   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17145   OriginalLexicalContext = ObjCCtx;
17146   ActOnObjCContainerFinishDefinition();
17147 }
17148 
17149 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17150   ActOnObjCContainerStartDefinition(ObjCCtx);
17151   OriginalLexicalContext = nullptr;
17152 }
17153 
17154 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17155   AdjustDeclIfTemplate(TagD);
17156   TagDecl *Tag = cast<TagDecl>(TagD);
17157   Tag->setInvalidDecl();
17158 
17159   // Make sure we "complete" the definition even it is invalid.
17160   if (Tag->isBeingDefined()) {
17161     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17162       RD->completeDefinition();
17163   }
17164 
17165   // We're undoing ActOnTagStartDefinition here, not
17166   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17167   // the FieldCollector.
17168 
17169   PopDeclContext();
17170 }
17171 
17172 // Note that FieldName may be null for anonymous bitfields.
17173 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17174                                 IdentifierInfo *FieldName, QualType FieldTy,
17175                                 bool IsMsStruct, Expr *BitWidth) {
17176   assert(BitWidth);
17177   if (BitWidth->containsErrors())
17178     return ExprError();
17179 
17180   // C99 6.7.2.1p4 - verify the field type.
17181   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17182   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17183     // Handle incomplete and sizeless types with a specific error.
17184     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17185                                  diag::err_field_incomplete_or_sizeless))
17186       return ExprError();
17187     if (FieldName)
17188       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17189         << FieldName << FieldTy << BitWidth->getSourceRange();
17190     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17191       << FieldTy << BitWidth->getSourceRange();
17192   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17193                                              UPPC_BitFieldWidth))
17194     return ExprError();
17195 
17196   // If the bit-width is type- or value-dependent, don't try to check
17197   // it now.
17198   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17199     return BitWidth;
17200 
17201   llvm::APSInt Value;
17202   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17203   if (ICE.isInvalid())
17204     return ICE;
17205   BitWidth = ICE.get();
17206 
17207   // Zero-width bitfield is ok for anonymous field.
17208   if (Value == 0 && FieldName)
17209     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17210 
17211   if (Value.isSigned() && Value.isNegative()) {
17212     if (FieldName)
17213       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17214                << FieldName << toString(Value, 10);
17215     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17216       << toString(Value, 10);
17217   }
17218 
17219   // The size of the bit-field must not exceed our maximum permitted object
17220   // size.
17221   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17222     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17223            << !FieldName << FieldName << toString(Value, 10);
17224   }
17225 
17226   if (!FieldTy->isDependentType()) {
17227     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17228     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17229     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17230 
17231     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17232     // ABI.
17233     bool CStdConstraintViolation =
17234         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17235     bool MSBitfieldViolation =
17236         Value.ugt(TypeStorageSize) &&
17237         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17238     if (CStdConstraintViolation || MSBitfieldViolation) {
17239       unsigned DiagWidth =
17240           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17241       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17242              << (bool)FieldName << FieldName << toString(Value, 10)
17243              << !CStdConstraintViolation << DiagWidth;
17244     }
17245 
17246     // Warn on types where the user might conceivably expect to get all
17247     // specified bits as value bits: that's all integral types other than
17248     // 'bool'.
17249     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17250       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17251           << FieldName << toString(Value, 10)
17252           << (unsigned)TypeWidth;
17253     }
17254   }
17255 
17256   return BitWidth;
17257 }
17258 
17259 /// ActOnField - Each field of a C struct/union is passed into this in order
17260 /// to create a FieldDecl object for it.
17261 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17262                        Declarator &D, Expr *BitfieldWidth) {
17263   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17264                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17265                                /*InitStyle=*/ICIS_NoInit, AS_public);
17266   return Res;
17267 }
17268 
17269 /// HandleField - Analyze a field of a C struct or a C++ data member.
17270 ///
17271 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17272                              SourceLocation DeclStart,
17273                              Declarator &D, Expr *BitWidth,
17274                              InClassInitStyle InitStyle,
17275                              AccessSpecifier AS) {
17276   if (D.isDecompositionDeclarator()) {
17277     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17278     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17279       << Decomp.getSourceRange();
17280     return nullptr;
17281   }
17282 
17283   IdentifierInfo *II = D.getIdentifier();
17284   SourceLocation Loc = DeclStart;
17285   if (II) Loc = D.getIdentifierLoc();
17286 
17287   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17288   QualType T = TInfo->getType();
17289   if (getLangOpts().CPlusPlus) {
17290     CheckExtraCXXDefaultArguments(D);
17291 
17292     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17293                                         UPPC_DataMemberType)) {
17294       D.setInvalidType();
17295       T = Context.IntTy;
17296       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17297     }
17298   }
17299 
17300   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17301 
17302   if (D.getDeclSpec().isInlineSpecified())
17303     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17304         << getLangOpts().CPlusPlus17;
17305   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17306     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17307          diag::err_invalid_thread)
17308       << DeclSpec::getSpecifierName(TSCS);
17309 
17310   // Check to see if this name was declared as a member previously
17311   NamedDecl *PrevDecl = nullptr;
17312   LookupResult Previous(*this, II, Loc, LookupMemberName,
17313                         ForVisibleRedeclaration);
17314   LookupName(Previous, S);
17315   switch (Previous.getResultKind()) {
17316     case LookupResult::Found:
17317     case LookupResult::FoundUnresolvedValue:
17318       PrevDecl = Previous.getAsSingle<NamedDecl>();
17319       break;
17320 
17321     case LookupResult::FoundOverloaded:
17322       PrevDecl = Previous.getRepresentativeDecl();
17323       break;
17324 
17325     case LookupResult::NotFound:
17326     case LookupResult::NotFoundInCurrentInstantiation:
17327     case LookupResult::Ambiguous:
17328       break;
17329   }
17330   Previous.suppressDiagnostics();
17331 
17332   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17333     // Maybe we will complain about the shadowed template parameter.
17334     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17335     // Just pretend that we didn't see the previous declaration.
17336     PrevDecl = nullptr;
17337   }
17338 
17339   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17340     PrevDecl = nullptr;
17341 
17342   bool Mutable
17343     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17344   SourceLocation TSSL = D.getBeginLoc();
17345   FieldDecl *NewFD
17346     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17347                      TSSL, AS, PrevDecl, &D);
17348 
17349   if (NewFD->isInvalidDecl())
17350     Record->setInvalidDecl();
17351 
17352   if (D.getDeclSpec().isModulePrivateSpecified())
17353     NewFD->setModulePrivate();
17354 
17355   if (NewFD->isInvalidDecl() && PrevDecl) {
17356     // Don't introduce NewFD into scope; there's already something
17357     // with the same name in the same scope.
17358   } else if (II) {
17359     PushOnScopeChains(NewFD, S);
17360   } else
17361     Record->addDecl(NewFD);
17362 
17363   return NewFD;
17364 }
17365 
17366 /// Build a new FieldDecl and check its well-formedness.
17367 ///
17368 /// This routine builds a new FieldDecl given the fields name, type,
17369 /// record, etc. \p PrevDecl should refer to any previous declaration
17370 /// with the same name and in the same scope as the field to be
17371 /// created.
17372 ///
17373 /// \returns a new FieldDecl.
17374 ///
17375 /// \todo The Declarator argument is a hack. It will be removed once
17376 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17377                                 TypeSourceInfo *TInfo,
17378                                 RecordDecl *Record, SourceLocation Loc,
17379                                 bool Mutable, Expr *BitWidth,
17380                                 InClassInitStyle InitStyle,
17381                                 SourceLocation TSSL,
17382                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17383                                 Declarator *D) {
17384   IdentifierInfo *II = Name.getAsIdentifierInfo();
17385   bool InvalidDecl = false;
17386   if (D) InvalidDecl = D->isInvalidType();
17387 
17388   // If we receive a broken type, recover by assuming 'int' and
17389   // marking this declaration as invalid.
17390   if (T.isNull() || T->containsErrors()) {
17391     InvalidDecl = true;
17392     T = Context.IntTy;
17393   }
17394 
17395   QualType EltTy = Context.getBaseElementType(T);
17396   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17397     if (RequireCompleteSizedType(Loc, EltTy,
17398                                  diag::err_field_incomplete_or_sizeless)) {
17399       // Fields of incomplete type force their record to be invalid.
17400       Record->setInvalidDecl();
17401       InvalidDecl = true;
17402     } else {
17403       NamedDecl *Def;
17404       EltTy->isIncompleteType(&Def);
17405       if (Def && Def->isInvalidDecl()) {
17406         Record->setInvalidDecl();
17407         InvalidDecl = true;
17408       }
17409     }
17410   }
17411 
17412   // TR 18037 does not allow fields to be declared with address space
17413   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17414       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17415     Diag(Loc, diag::err_field_with_address_space);
17416     Record->setInvalidDecl();
17417     InvalidDecl = true;
17418   }
17419 
17420   if (LangOpts.OpenCL) {
17421     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17422     // used as structure or union field: image, sampler, event or block types.
17423     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17424         T->isBlockPointerType()) {
17425       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17426       Record->setInvalidDecl();
17427       InvalidDecl = true;
17428     }
17429     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17430     // is enabled.
17431     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17432                         "__cl_clang_bitfields", LangOpts)) {
17433       Diag(Loc, diag::err_opencl_bitfields);
17434       InvalidDecl = true;
17435     }
17436   }
17437 
17438   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17439   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17440       T.hasQualifiers()) {
17441     InvalidDecl = true;
17442     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17443   }
17444 
17445   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17446   // than a variably modified type.
17447   if (!InvalidDecl && T->isVariablyModifiedType()) {
17448     if (!tryToFixVariablyModifiedVarType(
17449             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17450       InvalidDecl = true;
17451   }
17452 
17453   // Fields can not have abstract class types
17454   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17455                                              diag::err_abstract_type_in_decl,
17456                                              AbstractFieldType))
17457     InvalidDecl = true;
17458 
17459   if (InvalidDecl)
17460     BitWidth = nullptr;
17461   // If this is declared as a bit-field, check the bit-field.
17462   if (BitWidth) {
17463     BitWidth =
17464         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17465     if (!BitWidth) {
17466       InvalidDecl = true;
17467       BitWidth = nullptr;
17468     }
17469   }
17470 
17471   // Check that 'mutable' is consistent with the type of the declaration.
17472   if (!InvalidDecl && Mutable) {
17473     unsigned DiagID = 0;
17474     if (T->isReferenceType())
17475       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17476                                         : diag::err_mutable_reference;
17477     else if (T.isConstQualified())
17478       DiagID = diag::err_mutable_const;
17479 
17480     if (DiagID) {
17481       SourceLocation ErrLoc = Loc;
17482       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17483         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17484       Diag(ErrLoc, DiagID);
17485       if (DiagID != diag::ext_mutable_reference) {
17486         Mutable = false;
17487         InvalidDecl = true;
17488       }
17489     }
17490   }
17491 
17492   // C++11 [class.union]p8 (DR1460):
17493   //   At most one variant member of a union may have a
17494   //   brace-or-equal-initializer.
17495   if (InitStyle != ICIS_NoInit)
17496     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17497 
17498   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17499                                        BitWidth, Mutable, InitStyle);
17500   if (InvalidDecl)
17501     NewFD->setInvalidDecl();
17502 
17503   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17504     Diag(Loc, diag::err_duplicate_member) << II;
17505     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17506     NewFD->setInvalidDecl();
17507   }
17508 
17509   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17510     if (Record->isUnion()) {
17511       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17512         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17513         if (RDecl->getDefinition()) {
17514           // C++ [class.union]p1: An object of a class with a non-trivial
17515           // constructor, a non-trivial copy constructor, a non-trivial
17516           // destructor, or a non-trivial copy assignment operator
17517           // cannot be a member of a union, nor can an array of such
17518           // objects.
17519           if (CheckNontrivialField(NewFD))
17520             NewFD->setInvalidDecl();
17521         }
17522       }
17523 
17524       // C++ [class.union]p1: If a union contains a member of reference type,
17525       // the program is ill-formed, except when compiling with MSVC extensions
17526       // enabled.
17527       if (EltTy->isReferenceType()) {
17528         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17529                                     diag::ext_union_member_of_reference_type :
17530                                     diag::err_union_member_of_reference_type)
17531           << NewFD->getDeclName() << EltTy;
17532         if (!getLangOpts().MicrosoftExt)
17533           NewFD->setInvalidDecl();
17534       }
17535     }
17536   }
17537 
17538   // FIXME: We need to pass in the attributes given an AST
17539   // representation, not a parser representation.
17540   if (D) {
17541     // FIXME: The current scope is almost... but not entirely... correct here.
17542     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17543 
17544     if (NewFD->hasAttrs())
17545       CheckAlignasUnderalignment(NewFD);
17546   }
17547 
17548   // In auto-retain/release, infer strong retension for fields of
17549   // retainable type.
17550   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17551     NewFD->setInvalidDecl();
17552 
17553   if (T.isObjCGCWeak())
17554     Diag(Loc, diag::warn_attribute_weak_on_field);
17555 
17556   // PPC MMA non-pointer types are not allowed as field types.
17557   if (Context.getTargetInfo().getTriple().isPPC64() &&
17558       CheckPPCMMAType(T, NewFD->getLocation()))
17559     NewFD->setInvalidDecl();
17560 
17561   NewFD->setAccess(AS);
17562   return NewFD;
17563 }
17564 
17565 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17566   assert(FD);
17567   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17568 
17569   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17570     return false;
17571 
17572   QualType EltTy = Context.getBaseElementType(FD->getType());
17573   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17574     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17575     if (RDecl->getDefinition()) {
17576       // We check for copy constructors before constructors
17577       // because otherwise we'll never get complaints about
17578       // copy constructors.
17579 
17580       CXXSpecialMember member = CXXInvalid;
17581       // We're required to check for any non-trivial constructors. Since the
17582       // implicit default constructor is suppressed if there are any
17583       // user-declared constructors, we just need to check that there is a
17584       // trivial default constructor and a trivial copy constructor. (We don't
17585       // worry about move constructors here, since this is a C++98 check.)
17586       if (RDecl->hasNonTrivialCopyConstructor())
17587         member = CXXCopyConstructor;
17588       else if (!RDecl->hasTrivialDefaultConstructor())
17589         member = CXXDefaultConstructor;
17590       else if (RDecl->hasNonTrivialCopyAssignment())
17591         member = CXXCopyAssignment;
17592       else if (RDecl->hasNonTrivialDestructor())
17593         member = CXXDestructor;
17594 
17595       if (member != CXXInvalid) {
17596         if (!getLangOpts().CPlusPlus11 &&
17597             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17598           // Objective-C++ ARC: it is an error to have a non-trivial field of
17599           // a union. However, system headers in Objective-C programs
17600           // occasionally have Objective-C lifetime objects within unions,
17601           // and rather than cause the program to fail, we make those
17602           // members unavailable.
17603           SourceLocation Loc = FD->getLocation();
17604           if (getSourceManager().isInSystemHeader(Loc)) {
17605             if (!FD->hasAttr<UnavailableAttr>())
17606               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17607                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17608             return false;
17609           }
17610         }
17611 
17612         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17613                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17614                diag::err_illegal_union_or_anon_struct_member)
17615           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17616         DiagnoseNontrivial(RDecl, member);
17617         return !getLangOpts().CPlusPlus11;
17618       }
17619     }
17620   }
17621 
17622   return false;
17623 }
17624 
17625 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17626 ///  AST enum value.
17627 static ObjCIvarDecl::AccessControl
17628 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17629   switch (ivarVisibility) {
17630   default: llvm_unreachable("Unknown visitibility kind");
17631   case tok::objc_private: return ObjCIvarDecl::Private;
17632   case tok::objc_public: return ObjCIvarDecl::Public;
17633   case tok::objc_protected: return ObjCIvarDecl::Protected;
17634   case tok::objc_package: return ObjCIvarDecl::Package;
17635   }
17636 }
17637 
17638 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17639 /// in order to create an IvarDecl object for it.
17640 Decl *Sema::ActOnIvar(Scope *S,
17641                                 SourceLocation DeclStart,
17642                                 Declarator &D, Expr *BitfieldWidth,
17643                                 tok::ObjCKeywordKind Visibility) {
17644 
17645   IdentifierInfo *II = D.getIdentifier();
17646   Expr *BitWidth = (Expr*)BitfieldWidth;
17647   SourceLocation Loc = DeclStart;
17648   if (II) Loc = D.getIdentifierLoc();
17649 
17650   // FIXME: Unnamed fields can be handled in various different ways, for
17651   // example, unnamed unions inject all members into the struct namespace!
17652 
17653   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17654   QualType T = TInfo->getType();
17655 
17656   if (BitWidth) {
17657     // 6.7.2.1p3, 6.7.2.1p4
17658     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17659     if (!BitWidth)
17660       D.setInvalidType();
17661   } else {
17662     // Not a bitfield.
17663 
17664     // validate II.
17665 
17666   }
17667   if (T->isReferenceType()) {
17668     Diag(Loc, diag::err_ivar_reference_type);
17669     D.setInvalidType();
17670   }
17671   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17672   // than a variably modified type.
17673   else if (T->isVariablyModifiedType()) {
17674     if (!tryToFixVariablyModifiedVarType(
17675             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17676       D.setInvalidType();
17677   }
17678 
17679   // Get the visibility (access control) for this ivar.
17680   ObjCIvarDecl::AccessControl ac =
17681     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17682                                         : ObjCIvarDecl::None;
17683   // Must set ivar's DeclContext to its enclosing interface.
17684   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17685   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17686     return nullptr;
17687   ObjCContainerDecl *EnclosingContext;
17688   if (ObjCImplementationDecl *IMPDecl =
17689       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17690     if (LangOpts.ObjCRuntime.isFragile()) {
17691     // Case of ivar declared in an implementation. Context is that of its class.
17692       EnclosingContext = IMPDecl->getClassInterface();
17693       assert(EnclosingContext && "Implementation has no class interface!");
17694     }
17695     else
17696       EnclosingContext = EnclosingDecl;
17697   } else {
17698     if (ObjCCategoryDecl *CDecl =
17699         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17700       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17701         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17702         return nullptr;
17703       }
17704     }
17705     EnclosingContext = EnclosingDecl;
17706   }
17707 
17708   // Construct the decl.
17709   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17710                                              DeclStart, Loc, II, T,
17711                                              TInfo, ac, (Expr *)BitfieldWidth);
17712 
17713   if (II) {
17714     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17715                                            ForVisibleRedeclaration);
17716     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17717         && !isa<TagDecl>(PrevDecl)) {
17718       Diag(Loc, diag::err_duplicate_member) << II;
17719       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17720       NewID->setInvalidDecl();
17721     }
17722   }
17723 
17724   // Process attributes attached to the ivar.
17725   ProcessDeclAttributes(S, NewID, D);
17726 
17727   if (D.isInvalidType())
17728     NewID->setInvalidDecl();
17729 
17730   // In ARC, infer 'retaining' for ivars of retainable type.
17731   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17732     NewID->setInvalidDecl();
17733 
17734   if (D.getDeclSpec().isModulePrivateSpecified())
17735     NewID->setModulePrivate();
17736 
17737   if (II) {
17738     // FIXME: When interfaces are DeclContexts, we'll need to add
17739     // these to the interface.
17740     S->AddDecl(NewID);
17741     IdResolver.AddDecl(NewID);
17742   }
17743 
17744   if (LangOpts.ObjCRuntime.isNonFragile() &&
17745       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17746     Diag(Loc, diag::warn_ivars_in_interface);
17747 
17748   return NewID;
17749 }
17750 
17751 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17752 /// class and class extensions. For every class \@interface and class
17753 /// extension \@interface, if the last ivar is a bitfield of any type,
17754 /// then add an implicit `char :0` ivar to the end of that interface.
17755 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17756                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17757   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17758     return;
17759 
17760   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17761   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17762 
17763   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17764     return;
17765   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17766   if (!ID) {
17767     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17768       if (!CD->IsClassExtension())
17769         return;
17770     }
17771     // No need to add this to end of @implementation.
17772     else
17773       return;
17774   }
17775   // All conditions are met. Add a new bitfield to the tail end of ivars.
17776   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17777   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17778 
17779   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17780                               DeclLoc, DeclLoc, nullptr,
17781                               Context.CharTy,
17782                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17783                                                                DeclLoc),
17784                               ObjCIvarDecl::Private, BW,
17785                               true);
17786   AllIvarDecls.push_back(Ivar);
17787 }
17788 
17789 namespace {
17790 /// [class.dtor]p4:
17791 ///   At the end of the definition of a class, overload resolution is
17792 ///   performed among the prospective destructors declared in that class with
17793 ///   an empty argument list to select the destructor for the class, also
17794 ///   known as the selected destructor.
17795 ///
17796 /// We do the overload resolution here, then mark the selected constructor in the AST.
17797 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17798 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17799   if (!Record->hasUserDeclaredDestructor()) {
17800     return;
17801   }
17802 
17803   SourceLocation Loc = Record->getLocation();
17804   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17805 
17806   for (auto *Decl : Record->decls()) {
17807     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17808       if (DD->isInvalidDecl())
17809         continue;
17810       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17811                              OCS);
17812       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17813     }
17814   }
17815 
17816   if (OCS.empty()) {
17817     return;
17818   }
17819   OverloadCandidateSet::iterator Best;
17820   unsigned Msg = 0;
17821   OverloadCandidateDisplayKind DisplayKind;
17822 
17823   switch (OCS.BestViableFunction(S, Loc, Best)) {
17824   case OR_Success:
17825   case OR_Deleted:
17826     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17827     break;
17828 
17829   case OR_Ambiguous:
17830     Msg = diag::err_ambiguous_destructor;
17831     DisplayKind = OCD_AmbiguousCandidates;
17832     break;
17833 
17834   case OR_No_Viable_Function:
17835     Msg = diag::err_no_viable_destructor;
17836     DisplayKind = OCD_AllCandidates;
17837     break;
17838   }
17839 
17840   if (Msg) {
17841     // OpenCL have got their own thing going with destructors. It's slightly broken,
17842     // but we allow it.
17843     if (!S.LangOpts.OpenCL) {
17844       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17845       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17846       Record->setInvalidDecl();
17847     }
17848     // It's a bit hacky: At this point we've raised an error but we want the
17849     // rest of the compiler to continue somehow working. However almost
17850     // everything we'll try to do with the class will depend on there being a
17851     // destructor. So let's pretend the first one is selected and hope for the
17852     // best.
17853     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17854   }
17855 }
17856 } // namespace
17857 
17858 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17859                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17860                        SourceLocation RBrac,
17861                        const ParsedAttributesView &Attrs) {
17862   assert(EnclosingDecl && "missing record or interface decl");
17863 
17864   // If this is an Objective-C @implementation or category and we have
17865   // new fields here we should reset the layout of the interface since
17866   // it will now change.
17867   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17868     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17869     switch (DC->getKind()) {
17870     default: break;
17871     case Decl::ObjCCategory:
17872       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17873       break;
17874     case Decl::ObjCImplementation:
17875       Context.
17876         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17877       break;
17878     }
17879   }
17880 
17881   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17882   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17883 
17884   if (CXXRecord && !CXXRecord->isDependentType())
17885     ComputeSelectedDestructor(*this, CXXRecord);
17886 
17887   // Start counting up the number of named members; make sure to include
17888   // members of anonymous structs and unions in the total.
17889   unsigned NumNamedMembers = 0;
17890   if (Record) {
17891     for (const auto *I : Record->decls()) {
17892       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17893         if (IFD->getDeclName())
17894           ++NumNamedMembers;
17895     }
17896   }
17897 
17898   // Verify that all the fields are okay.
17899   SmallVector<FieldDecl*, 32> RecFields;
17900 
17901   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17902        i != end; ++i) {
17903     FieldDecl *FD = cast<FieldDecl>(*i);
17904 
17905     // Get the type for the field.
17906     const Type *FDTy = FD->getType().getTypePtr();
17907 
17908     if (!FD->isAnonymousStructOrUnion()) {
17909       // Remember all fields written by the user.
17910       RecFields.push_back(FD);
17911     }
17912 
17913     // If the field is already invalid for some reason, don't emit more
17914     // diagnostics about it.
17915     if (FD->isInvalidDecl()) {
17916       EnclosingDecl->setInvalidDecl();
17917       continue;
17918     }
17919 
17920     // C99 6.7.2.1p2:
17921     //   A structure or union shall not contain a member with
17922     //   incomplete or function type (hence, a structure shall not
17923     //   contain an instance of itself, but may contain a pointer to
17924     //   an instance of itself), except that the last member of a
17925     //   structure with more than one named member may have incomplete
17926     //   array type; such a structure (and any union containing,
17927     //   possibly recursively, a member that is such a structure)
17928     //   shall not be a member of a structure or an element of an
17929     //   array.
17930     bool IsLastField = (i + 1 == Fields.end());
17931     if (FDTy->isFunctionType()) {
17932       // Field declared as a function.
17933       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17934         << FD->getDeclName();
17935       FD->setInvalidDecl();
17936       EnclosingDecl->setInvalidDecl();
17937       continue;
17938     } else if (FDTy->isIncompleteArrayType() &&
17939                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17940       if (Record) {
17941         // Flexible array member.
17942         // Microsoft and g++ is more permissive regarding flexible array.
17943         // It will accept flexible array in union and also
17944         // as the sole element of a struct/class.
17945         unsigned DiagID = 0;
17946         if (!Record->isUnion() && !IsLastField) {
17947           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17948             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17949           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17950           FD->setInvalidDecl();
17951           EnclosingDecl->setInvalidDecl();
17952           continue;
17953         } else if (Record->isUnion())
17954           DiagID = getLangOpts().MicrosoftExt
17955                        ? diag::ext_flexible_array_union_ms
17956                        : getLangOpts().CPlusPlus
17957                              ? diag::ext_flexible_array_union_gnu
17958                              : diag::err_flexible_array_union;
17959         else if (NumNamedMembers < 1)
17960           DiagID = getLangOpts().MicrosoftExt
17961                        ? diag::ext_flexible_array_empty_aggregate_ms
17962                        : getLangOpts().CPlusPlus
17963                              ? diag::ext_flexible_array_empty_aggregate_gnu
17964                              : diag::err_flexible_array_empty_aggregate;
17965 
17966         if (DiagID)
17967           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17968                                           << Record->getTagKind();
17969         // While the layout of types that contain virtual bases is not specified
17970         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17971         // virtual bases after the derived members.  This would make a flexible
17972         // array member declared at the end of an object not adjacent to the end
17973         // of the type.
17974         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17975           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17976               << FD->getDeclName() << Record->getTagKind();
17977         if (!getLangOpts().C99)
17978           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17979             << FD->getDeclName() << Record->getTagKind();
17980 
17981         // If the element type has a non-trivial destructor, we would not
17982         // implicitly destroy the elements, so disallow it for now.
17983         //
17984         // FIXME: GCC allows this. We should probably either implicitly delete
17985         // the destructor of the containing class, or just allow this.
17986         QualType BaseElem = Context.getBaseElementType(FD->getType());
17987         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17988           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17989             << FD->getDeclName() << FD->getType();
17990           FD->setInvalidDecl();
17991           EnclosingDecl->setInvalidDecl();
17992           continue;
17993         }
17994         // Okay, we have a legal flexible array member at the end of the struct.
17995         Record->setHasFlexibleArrayMember(true);
17996       } else {
17997         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17998         // unless they are followed by another ivar. That check is done
17999         // elsewhere, after synthesized ivars are known.
18000       }
18001     } else if (!FDTy->isDependentType() &&
18002                RequireCompleteSizedType(
18003                    FD->getLocation(), FD->getType(),
18004                    diag::err_field_incomplete_or_sizeless)) {
18005       // Incomplete type
18006       FD->setInvalidDecl();
18007       EnclosingDecl->setInvalidDecl();
18008       continue;
18009     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18010       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18011         // A type which contains a flexible array member is considered to be a
18012         // flexible array member.
18013         Record->setHasFlexibleArrayMember(true);
18014         if (!Record->isUnion()) {
18015           // If this is a struct/class and this is not the last element, reject
18016           // it.  Note that GCC supports variable sized arrays in the middle of
18017           // structures.
18018           if (!IsLastField)
18019             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18020               << FD->getDeclName() << FD->getType();
18021           else {
18022             // We support flexible arrays at the end of structs in
18023             // other structs as an extension.
18024             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18025               << FD->getDeclName();
18026           }
18027         }
18028       }
18029       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18030           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18031                                  diag::err_abstract_type_in_decl,
18032                                  AbstractIvarType)) {
18033         // Ivars can not have abstract class types
18034         FD->setInvalidDecl();
18035       }
18036       if (Record && FDTTy->getDecl()->hasObjectMember())
18037         Record->setHasObjectMember(true);
18038       if (Record && FDTTy->getDecl()->hasVolatileMember())
18039         Record->setHasVolatileMember(true);
18040     } else if (FDTy->isObjCObjectType()) {
18041       /// A field cannot be an Objective-c object
18042       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18043         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18044       QualType T = Context.getObjCObjectPointerType(FD->getType());
18045       FD->setType(T);
18046     } else if (Record && Record->isUnion() &&
18047                FD->getType().hasNonTrivialObjCLifetime() &&
18048                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18049                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18050                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18051                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18052       // For backward compatibility, fields of C unions declared in system
18053       // headers that have non-trivial ObjC ownership qualifications are marked
18054       // as unavailable unless the qualifier is explicit and __strong. This can
18055       // break ABI compatibility between programs compiled with ARC and MRR, but
18056       // is a better option than rejecting programs using those unions under
18057       // ARC.
18058       FD->addAttr(UnavailableAttr::CreateImplicit(
18059           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18060           FD->getLocation()));
18061     } else if (getLangOpts().ObjC &&
18062                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18063                !Record->hasObjectMember()) {
18064       if (FD->getType()->isObjCObjectPointerType() ||
18065           FD->getType().isObjCGCStrong())
18066         Record->setHasObjectMember(true);
18067       else if (Context.getAsArrayType(FD->getType())) {
18068         QualType BaseType = Context.getBaseElementType(FD->getType());
18069         if (BaseType->isRecordType() &&
18070             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18071           Record->setHasObjectMember(true);
18072         else if (BaseType->isObjCObjectPointerType() ||
18073                  BaseType.isObjCGCStrong())
18074                Record->setHasObjectMember(true);
18075       }
18076     }
18077 
18078     if (Record && !getLangOpts().CPlusPlus &&
18079         !shouldIgnoreForRecordTriviality(FD)) {
18080       QualType FT = FD->getType();
18081       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18082         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18083         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18084             Record->isUnion())
18085           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18086       }
18087       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18088       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18089         Record->setNonTrivialToPrimitiveCopy(true);
18090         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18091           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18092       }
18093       if (FT.isDestructedType()) {
18094         Record->setNonTrivialToPrimitiveDestroy(true);
18095         Record->setParamDestroyedInCallee(true);
18096         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18097           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18098       }
18099 
18100       if (const auto *RT = FT->getAs<RecordType>()) {
18101         if (RT->getDecl()->getArgPassingRestrictions() ==
18102             RecordDecl::APK_CanNeverPassInRegs)
18103           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18104       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18105         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18106     }
18107 
18108     if (Record && FD->getType().isVolatileQualified())
18109       Record->setHasVolatileMember(true);
18110     // Keep track of the number of named members.
18111     if (FD->getIdentifier())
18112       ++NumNamedMembers;
18113   }
18114 
18115   // Okay, we successfully defined 'Record'.
18116   if (Record) {
18117     bool Completed = false;
18118     if (CXXRecord) {
18119       if (!CXXRecord->isInvalidDecl()) {
18120         // Set access bits correctly on the directly-declared conversions.
18121         for (CXXRecordDecl::conversion_iterator
18122                I = CXXRecord->conversion_begin(),
18123                E = CXXRecord->conversion_end(); I != E; ++I)
18124           I.setAccess((*I)->getAccess());
18125       }
18126 
18127       // Add any implicitly-declared members to this class.
18128       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18129 
18130       if (!CXXRecord->isDependentType()) {
18131         if (!CXXRecord->isInvalidDecl()) {
18132           // If we have virtual base classes, we may end up finding multiple
18133           // final overriders for a given virtual function. Check for this
18134           // problem now.
18135           if (CXXRecord->getNumVBases()) {
18136             CXXFinalOverriderMap FinalOverriders;
18137             CXXRecord->getFinalOverriders(FinalOverriders);
18138 
18139             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18140                                              MEnd = FinalOverriders.end();
18141                  M != MEnd; ++M) {
18142               for (OverridingMethods::iterator SO = M->second.begin(),
18143                                             SOEnd = M->second.end();
18144                    SO != SOEnd; ++SO) {
18145                 assert(SO->second.size() > 0 &&
18146                        "Virtual function without overriding functions?");
18147                 if (SO->second.size() == 1)
18148                   continue;
18149 
18150                 // C++ [class.virtual]p2:
18151                 //   In a derived class, if a virtual member function of a base
18152                 //   class subobject has more than one final overrider the
18153                 //   program is ill-formed.
18154                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18155                   << (const NamedDecl *)M->first << Record;
18156                 Diag(M->first->getLocation(),
18157                      diag::note_overridden_virtual_function);
18158                 for (OverridingMethods::overriding_iterator
18159                           OM = SO->second.begin(),
18160                        OMEnd = SO->second.end();
18161                      OM != OMEnd; ++OM)
18162                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18163                     << (const NamedDecl *)M->first << OM->Method->getParent();
18164 
18165                 Record->setInvalidDecl();
18166               }
18167             }
18168             CXXRecord->completeDefinition(&FinalOverriders);
18169             Completed = true;
18170           }
18171         }
18172       }
18173     }
18174 
18175     if (!Completed)
18176       Record->completeDefinition();
18177 
18178     // Handle attributes before checking the layout.
18179     ProcessDeclAttributeList(S, Record, Attrs);
18180 
18181     // Check to see if a FieldDecl is a pointer to a function.
18182     auto IsFunctionPointer = [&](const Decl *D) {
18183       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18184       if (!FD)
18185         return false;
18186       QualType FieldType = FD->getType().getDesugaredType(Context);
18187       if (isa<PointerType>(FieldType)) {
18188         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18189         return PointeeType.getDesugaredType(Context)->isFunctionType();
18190       }
18191       return false;
18192     };
18193 
18194     // Maybe randomize the record's decls. We automatically randomize a record
18195     // of function pointers, unless it has the "no_randomize_layout" attribute.
18196     if (!getLangOpts().CPlusPlus &&
18197         (Record->hasAttr<RandomizeLayoutAttr>() ||
18198          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18199           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18200         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18201         !Record->isRandomized()) {
18202       SmallVector<Decl *, 32> NewDeclOrdering;
18203       if (randstruct::randomizeStructureLayout(Context, Record,
18204                                                NewDeclOrdering))
18205         Record->reorderDecls(NewDeclOrdering);
18206     }
18207 
18208     // We may have deferred checking for a deleted destructor. Check now.
18209     if (CXXRecord) {
18210       auto *Dtor = CXXRecord->getDestructor();
18211       if (Dtor && Dtor->isImplicit() &&
18212           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18213         CXXRecord->setImplicitDestructorIsDeleted();
18214         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18215       }
18216     }
18217 
18218     if (Record->hasAttrs()) {
18219       CheckAlignasUnderalignment(Record);
18220 
18221       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18222         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18223                                            IA->getRange(), IA->getBestCase(),
18224                                            IA->getInheritanceModel());
18225     }
18226 
18227     // Check if the structure/union declaration is a type that can have zero
18228     // size in C. For C this is a language extension, for C++ it may cause
18229     // compatibility problems.
18230     bool CheckForZeroSize;
18231     if (!getLangOpts().CPlusPlus) {
18232       CheckForZeroSize = true;
18233     } else {
18234       // For C++ filter out types that cannot be referenced in C code.
18235       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18236       CheckForZeroSize =
18237           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18238           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18239           CXXRecord->isCLike();
18240     }
18241     if (CheckForZeroSize) {
18242       bool ZeroSize = true;
18243       bool IsEmpty = true;
18244       unsigned NonBitFields = 0;
18245       for (RecordDecl::field_iterator I = Record->field_begin(),
18246                                       E = Record->field_end();
18247            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18248         IsEmpty = false;
18249         if (I->isUnnamedBitfield()) {
18250           if (!I->isZeroLengthBitField(Context))
18251             ZeroSize = false;
18252         } else {
18253           ++NonBitFields;
18254           QualType FieldType = I->getType();
18255           if (FieldType->isIncompleteType() ||
18256               !Context.getTypeSizeInChars(FieldType).isZero())
18257             ZeroSize = false;
18258         }
18259       }
18260 
18261       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18262       // allowed in C++, but warn if its declaration is inside
18263       // extern "C" block.
18264       if (ZeroSize) {
18265         Diag(RecLoc, getLangOpts().CPlusPlus ?
18266                          diag::warn_zero_size_struct_union_in_extern_c :
18267                          diag::warn_zero_size_struct_union_compat)
18268           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18269       }
18270 
18271       // Structs without named members are extension in C (C99 6.7.2.1p7),
18272       // but are accepted by GCC.
18273       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18274         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18275                                diag::ext_no_named_members_in_struct_union)
18276           << Record->isUnion();
18277       }
18278     }
18279   } else {
18280     ObjCIvarDecl **ClsFields =
18281       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18282     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18283       ID->setEndOfDefinitionLoc(RBrac);
18284       // Add ivar's to class's DeclContext.
18285       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18286         ClsFields[i]->setLexicalDeclContext(ID);
18287         ID->addDecl(ClsFields[i]);
18288       }
18289       // Must enforce the rule that ivars in the base classes may not be
18290       // duplicates.
18291       if (ID->getSuperClass())
18292         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18293     } else if (ObjCImplementationDecl *IMPDecl =
18294                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18295       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18296       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18297         // Ivar declared in @implementation never belongs to the implementation.
18298         // Only it is in implementation's lexical context.
18299         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18300       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18301       IMPDecl->setIvarLBraceLoc(LBrac);
18302       IMPDecl->setIvarRBraceLoc(RBrac);
18303     } else if (ObjCCategoryDecl *CDecl =
18304                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18305       // case of ivars in class extension; all other cases have been
18306       // reported as errors elsewhere.
18307       // FIXME. Class extension does not have a LocEnd field.
18308       // CDecl->setLocEnd(RBrac);
18309       // Add ivar's to class extension's DeclContext.
18310       // Diagnose redeclaration of private ivars.
18311       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18312       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18313         if (IDecl) {
18314           if (const ObjCIvarDecl *ClsIvar =
18315               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18316             Diag(ClsFields[i]->getLocation(),
18317                  diag::err_duplicate_ivar_declaration);
18318             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18319             continue;
18320           }
18321           for (const auto *Ext : IDecl->known_extensions()) {
18322             if (const ObjCIvarDecl *ClsExtIvar
18323                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18324               Diag(ClsFields[i]->getLocation(),
18325                    diag::err_duplicate_ivar_declaration);
18326               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18327               continue;
18328             }
18329           }
18330         }
18331         ClsFields[i]->setLexicalDeclContext(CDecl);
18332         CDecl->addDecl(ClsFields[i]);
18333       }
18334       CDecl->setIvarLBraceLoc(LBrac);
18335       CDecl->setIvarRBraceLoc(RBrac);
18336     }
18337   }
18338 }
18339 
18340 /// Determine whether the given integral value is representable within
18341 /// the given type T.
18342 static bool isRepresentableIntegerValue(ASTContext &Context,
18343                                         llvm::APSInt &Value,
18344                                         QualType T) {
18345   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18346          "Integral type required!");
18347   unsigned BitWidth = Context.getIntWidth(T);
18348 
18349   if (Value.isUnsigned() || Value.isNonNegative()) {
18350     if (T->isSignedIntegerOrEnumerationType())
18351       --BitWidth;
18352     return Value.getActiveBits() <= BitWidth;
18353   }
18354   return Value.getMinSignedBits() <= BitWidth;
18355 }
18356 
18357 // Given an integral type, return the next larger integral type
18358 // (or a NULL type of no such type exists).
18359 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18360   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18361   // enum checking below.
18362   assert((T->isIntegralType(Context) ||
18363          T->isEnumeralType()) && "Integral type required!");
18364   const unsigned NumTypes = 4;
18365   QualType SignedIntegralTypes[NumTypes] = {
18366     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18367   };
18368   QualType UnsignedIntegralTypes[NumTypes] = {
18369     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18370     Context.UnsignedLongLongTy
18371   };
18372 
18373   unsigned BitWidth = Context.getTypeSize(T);
18374   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18375                                                         : UnsignedIntegralTypes;
18376   for (unsigned I = 0; I != NumTypes; ++I)
18377     if (Context.getTypeSize(Types[I]) > BitWidth)
18378       return Types[I];
18379 
18380   return QualType();
18381 }
18382 
18383 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18384                                           EnumConstantDecl *LastEnumConst,
18385                                           SourceLocation IdLoc,
18386                                           IdentifierInfo *Id,
18387                                           Expr *Val) {
18388   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18389   llvm::APSInt EnumVal(IntWidth);
18390   QualType EltTy;
18391 
18392   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18393     Val = nullptr;
18394 
18395   if (Val)
18396     Val = DefaultLvalueConversion(Val).get();
18397 
18398   if (Val) {
18399     if (Enum->isDependentType() || Val->isTypeDependent() ||
18400         Val->containsErrors())
18401       EltTy = Context.DependentTy;
18402     else {
18403       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18404       // underlying type, but do allow it in all other contexts.
18405       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18406         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18407         // constant-expression in the enumerator-definition shall be a converted
18408         // constant expression of the underlying type.
18409         EltTy = Enum->getIntegerType();
18410         ExprResult Converted =
18411           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18412                                            CCEK_Enumerator);
18413         if (Converted.isInvalid())
18414           Val = nullptr;
18415         else
18416           Val = Converted.get();
18417       } else if (!Val->isValueDependent() &&
18418                  !(Val =
18419                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18420                            .get())) {
18421         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18422       } else {
18423         if (Enum->isComplete()) {
18424           EltTy = Enum->getIntegerType();
18425 
18426           // In Obj-C and Microsoft mode, require the enumeration value to be
18427           // representable in the underlying type of the enumeration. In C++11,
18428           // we perform a non-narrowing conversion as part of converted constant
18429           // expression checking.
18430           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18431             if (Context.getTargetInfo()
18432                     .getTriple()
18433                     .isWindowsMSVCEnvironment()) {
18434               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18435             } else {
18436               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18437             }
18438           }
18439 
18440           // Cast to the underlying type.
18441           Val = ImpCastExprToType(Val, EltTy,
18442                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18443                                                          : CK_IntegralCast)
18444                     .get();
18445         } else if (getLangOpts().CPlusPlus) {
18446           // C++11 [dcl.enum]p5:
18447           //   If the underlying type is not fixed, the type of each enumerator
18448           //   is the type of its initializing value:
18449           //     - If an initializer is specified for an enumerator, the
18450           //       initializing value has the same type as the expression.
18451           EltTy = Val->getType();
18452         } else {
18453           // C99 6.7.2.2p2:
18454           //   The expression that defines the value of an enumeration constant
18455           //   shall be an integer constant expression that has a value
18456           //   representable as an int.
18457 
18458           // Complain if the value is not representable in an int.
18459           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18460             Diag(IdLoc, diag::ext_enum_value_not_int)
18461               << toString(EnumVal, 10) << Val->getSourceRange()
18462               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18463           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18464             // Force the type of the expression to 'int'.
18465             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18466           }
18467           EltTy = Val->getType();
18468         }
18469       }
18470     }
18471   }
18472 
18473   if (!Val) {
18474     if (Enum->isDependentType())
18475       EltTy = Context.DependentTy;
18476     else if (!LastEnumConst) {
18477       // C++0x [dcl.enum]p5:
18478       //   If the underlying type is not fixed, the type of each enumerator
18479       //   is the type of its initializing value:
18480       //     - If no initializer is specified for the first enumerator, the
18481       //       initializing value has an unspecified integral type.
18482       //
18483       // GCC uses 'int' for its unspecified integral type, as does
18484       // C99 6.7.2.2p3.
18485       if (Enum->isFixed()) {
18486         EltTy = Enum->getIntegerType();
18487       }
18488       else {
18489         EltTy = Context.IntTy;
18490       }
18491     } else {
18492       // Assign the last value + 1.
18493       EnumVal = LastEnumConst->getInitVal();
18494       ++EnumVal;
18495       EltTy = LastEnumConst->getType();
18496 
18497       // Check for overflow on increment.
18498       if (EnumVal < LastEnumConst->getInitVal()) {
18499         // C++0x [dcl.enum]p5:
18500         //   If the underlying type is not fixed, the type of each enumerator
18501         //   is the type of its initializing value:
18502         //
18503         //     - Otherwise the type of the initializing value is the same as
18504         //       the type of the initializing value of the preceding enumerator
18505         //       unless the incremented value is not representable in that type,
18506         //       in which case the type is an unspecified integral type
18507         //       sufficient to contain the incremented value. If no such type
18508         //       exists, the program is ill-formed.
18509         QualType T = getNextLargerIntegralType(Context, EltTy);
18510         if (T.isNull() || Enum->isFixed()) {
18511           // There is no integral type larger enough to represent this
18512           // value. Complain, then allow the value to wrap around.
18513           EnumVal = LastEnumConst->getInitVal();
18514           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18515           ++EnumVal;
18516           if (Enum->isFixed())
18517             // When the underlying type is fixed, this is ill-formed.
18518             Diag(IdLoc, diag::err_enumerator_wrapped)
18519               << toString(EnumVal, 10)
18520               << EltTy;
18521           else
18522             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18523               << toString(EnumVal, 10);
18524         } else {
18525           EltTy = T;
18526         }
18527 
18528         // Retrieve the last enumerator's value, extent that type to the
18529         // type that is supposed to be large enough to represent the incremented
18530         // value, then increment.
18531         EnumVal = LastEnumConst->getInitVal();
18532         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18533         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18534         ++EnumVal;
18535 
18536         // If we're not in C++, diagnose the overflow of enumerator values,
18537         // which in C99 means that the enumerator value is not representable in
18538         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18539         // permits enumerator values that are representable in some larger
18540         // integral type.
18541         if (!getLangOpts().CPlusPlus && !T.isNull())
18542           Diag(IdLoc, diag::warn_enum_value_overflow);
18543       } else if (!getLangOpts().CPlusPlus &&
18544                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18545         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18546         Diag(IdLoc, diag::ext_enum_value_not_int)
18547           << toString(EnumVal, 10) << 1;
18548       }
18549     }
18550   }
18551 
18552   if (!EltTy->isDependentType()) {
18553     // Make the enumerator value match the signedness and size of the
18554     // enumerator's type.
18555     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18556     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18557   }
18558 
18559   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18560                                   Val, EnumVal);
18561 }
18562 
18563 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18564                                                 SourceLocation IILoc) {
18565   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18566       !getLangOpts().CPlusPlus)
18567     return SkipBodyInfo();
18568 
18569   // We have an anonymous enum definition. Look up the first enumerator to
18570   // determine if we should merge the definition with an existing one and
18571   // skip the body.
18572   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18573                                          forRedeclarationInCurContext());
18574   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18575   if (!PrevECD)
18576     return SkipBodyInfo();
18577 
18578   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18579   NamedDecl *Hidden;
18580   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18581     SkipBodyInfo Skip;
18582     Skip.Previous = Hidden;
18583     return Skip;
18584   }
18585 
18586   return SkipBodyInfo();
18587 }
18588 
18589 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18590                               SourceLocation IdLoc, IdentifierInfo *Id,
18591                               const ParsedAttributesView &Attrs,
18592                               SourceLocation EqualLoc, Expr *Val) {
18593   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18594   EnumConstantDecl *LastEnumConst =
18595     cast_or_null<EnumConstantDecl>(lastEnumConst);
18596 
18597   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18598   // we find one that is.
18599   S = getNonFieldDeclScope(S);
18600 
18601   // Verify that there isn't already something declared with this name in this
18602   // scope.
18603   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18604   LookupName(R, S);
18605   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18606 
18607   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18608     // Maybe we will complain about the shadowed template parameter.
18609     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18610     // Just pretend that we didn't see the previous declaration.
18611     PrevDecl = nullptr;
18612   }
18613 
18614   // C++ [class.mem]p15:
18615   // If T is the name of a class, then each of the following shall have a name
18616   // different from T:
18617   // - every enumerator of every member of class T that is an unscoped
18618   // enumerated type
18619   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18620     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18621                             DeclarationNameInfo(Id, IdLoc));
18622 
18623   EnumConstantDecl *New =
18624     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18625   if (!New)
18626     return nullptr;
18627 
18628   if (PrevDecl) {
18629     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18630       // Check for other kinds of shadowing not already handled.
18631       CheckShadow(New, PrevDecl, R);
18632     }
18633 
18634     // When in C++, we may get a TagDecl with the same name; in this case the
18635     // enum constant will 'hide' the tag.
18636     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18637            "Received TagDecl when not in C++!");
18638     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18639       if (isa<EnumConstantDecl>(PrevDecl))
18640         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18641       else
18642         Diag(IdLoc, diag::err_redefinition) << Id;
18643       notePreviousDefinition(PrevDecl, IdLoc);
18644       return nullptr;
18645     }
18646   }
18647 
18648   // Process attributes.
18649   ProcessDeclAttributeList(S, New, Attrs);
18650   AddPragmaAttributes(S, New);
18651 
18652   // Register this decl in the current scope stack.
18653   New->setAccess(TheEnumDecl->getAccess());
18654   PushOnScopeChains(New, S);
18655 
18656   ActOnDocumentableDecl(New);
18657 
18658   return New;
18659 }
18660 
18661 // Returns true when the enum initial expression does not trigger the
18662 // duplicate enum warning.  A few common cases are exempted as follows:
18663 // Element2 = Element1
18664 // Element2 = Element1 + 1
18665 // Element2 = Element1 - 1
18666 // Where Element2 and Element1 are from the same enum.
18667 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18668   Expr *InitExpr = ECD->getInitExpr();
18669   if (!InitExpr)
18670     return true;
18671   InitExpr = InitExpr->IgnoreImpCasts();
18672 
18673   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18674     if (!BO->isAdditiveOp())
18675       return true;
18676     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18677     if (!IL)
18678       return true;
18679     if (IL->getValue() != 1)
18680       return true;
18681 
18682     InitExpr = BO->getLHS();
18683   }
18684 
18685   // This checks if the elements are from the same enum.
18686   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18687   if (!DRE)
18688     return true;
18689 
18690   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18691   if (!EnumConstant)
18692     return true;
18693 
18694   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18695       Enum)
18696     return true;
18697 
18698   return false;
18699 }
18700 
18701 // Emits a warning when an element is implicitly set a value that
18702 // a previous element has already been set to.
18703 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18704                                         EnumDecl *Enum, QualType EnumType) {
18705   // Avoid anonymous enums
18706   if (!Enum->getIdentifier())
18707     return;
18708 
18709   // Only check for small enums.
18710   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18711     return;
18712 
18713   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18714     return;
18715 
18716   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18717   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18718 
18719   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18720 
18721   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18722   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18723 
18724   // Use int64_t as a key to avoid needing special handling for map keys.
18725   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18726     llvm::APSInt Val = D->getInitVal();
18727     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18728   };
18729 
18730   DuplicatesVector DupVector;
18731   ValueToVectorMap EnumMap;
18732 
18733   // Populate the EnumMap with all values represented by enum constants without
18734   // an initializer.
18735   for (auto *Element : Elements) {
18736     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18737 
18738     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18739     // this constant.  Skip this enum since it may be ill-formed.
18740     if (!ECD) {
18741       return;
18742     }
18743 
18744     // Constants with initalizers are handled in the next loop.
18745     if (ECD->getInitExpr())
18746       continue;
18747 
18748     // Duplicate values are handled in the next loop.
18749     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18750   }
18751 
18752   if (EnumMap.size() == 0)
18753     return;
18754 
18755   // Create vectors for any values that has duplicates.
18756   for (auto *Element : Elements) {
18757     // The last loop returned if any constant was null.
18758     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18759     if (!ValidDuplicateEnum(ECD, Enum))
18760       continue;
18761 
18762     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18763     if (Iter == EnumMap.end())
18764       continue;
18765 
18766     DeclOrVector& Entry = Iter->second;
18767     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18768       // Ensure constants are different.
18769       if (D == ECD)
18770         continue;
18771 
18772       // Create new vector and push values onto it.
18773       auto Vec = std::make_unique<ECDVector>();
18774       Vec->push_back(D);
18775       Vec->push_back(ECD);
18776 
18777       // Update entry to point to the duplicates vector.
18778       Entry = Vec.get();
18779 
18780       // Store the vector somewhere we can consult later for quick emission of
18781       // diagnostics.
18782       DupVector.emplace_back(std::move(Vec));
18783       continue;
18784     }
18785 
18786     ECDVector *Vec = Entry.get<ECDVector*>();
18787     // Make sure constants are not added more than once.
18788     if (*Vec->begin() == ECD)
18789       continue;
18790 
18791     Vec->push_back(ECD);
18792   }
18793 
18794   // Emit diagnostics.
18795   for (const auto &Vec : DupVector) {
18796     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18797 
18798     // Emit warning for one enum constant.
18799     auto *FirstECD = Vec->front();
18800     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18801       << FirstECD << toString(FirstECD->getInitVal(), 10)
18802       << FirstECD->getSourceRange();
18803 
18804     // Emit one note for each of the remaining enum constants with
18805     // the same value.
18806     for (auto *ECD : llvm::drop_begin(*Vec))
18807       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18808         << ECD << toString(ECD->getInitVal(), 10)
18809         << ECD->getSourceRange();
18810   }
18811 }
18812 
18813 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18814                              bool AllowMask) const {
18815   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18816   assert(ED->isCompleteDefinition() && "expected enum definition");
18817 
18818   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18819   llvm::APInt &FlagBits = R.first->second;
18820 
18821   if (R.second) {
18822     for (auto *E : ED->enumerators()) {
18823       const auto &EVal = E->getInitVal();
18824       // Only single-bit enumerators introduce new flag values.
18825       if (EVal.isPowerOf2())
18826         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18827     }
18828   }
18829 
18830   // A value is in a flag enum if either its bits are a subset of the enum's
18831   // flag bits (the first condition) or we are allowing masks and the same is
18832   // true of its complement (the second condition). When masks are allowed, we
18833   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18834   //
18835   // While it's true that any value could be used as a mask, the assumption is
18836   // that a mask will have all of the insignificant bits set. Anything else is
18837   // likely a logic error.
18838   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18839   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18840 }
18841 
18842 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18843                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18844                          const ParsedAttributesView &Attrs) {
18845   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18846   QualType EnumType = Context.getTypeDeclType(Enum);
18847 
18848   ProcessDeclAttributeList(S, Enum, Attrs);
18849 
18850   if (Enum->isDependentType()) {
18851     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18852       EnumConstantDecl *ECD =
18853         cast_or_null<EnumConstantDecl>(Elements[i]);
18854       if (!ECD) continue;
18855 
18856       ECD->setType(EnumType);
18857     }
18858 
18859     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18860     return;
18861   }
18862 
18863   // TODO: If the result value doesn't fit in an int, it must be a long or long
18864   // long value.  ISO C does not support this, but GCC does as an extension,
18865   // emit a warning.
18866   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18867   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18868   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18869 
18870   // Verify that all the values are okay, compute the size of the values, and
18871   // reverse the list.
18872   unsigned NumNegativeBits = 0;
18873   unsigned NumPositiveBits = 0;
18874 
18875   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18876     EnumConstantDecl *ECD =
18877       cast_or_null<EnumConstantDecl>(Elements[i]);
18878     if (!ECD) continue;  // Already issued a diagnostic.
18879 
18880     const llvm::APSInt &InitVal = ECD->getInitVal();
18881 
18882     // Keep track of the size of positive and negative values.
18883     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18884       NumPositiveBits = std::max(NumPositiveBits,
18885                                  (unsigned)InitVal.getActiveBits());
18886     else
18887       NumNegativeBits = std::max(NumNegativeBits,
18888                                  (unsigned)InitVal.getMinSignedBits());
18889   }
18890 
18891   // Figure out the type that should be used for this enum.
18892   QualType BestType;
18893   unsigned BestWidth;
18894 
18895   // C++0x N3000 [conv.prom]p3:
18896   //   An rvalue of an unscoped enumeration type whose underlying
18897   //   type is not fixed can be converted to an rvalue of the first
18898   //   of the following types that can represent all the values of
18899   //   the enumeration: int, unsigned int, long int, unsigned long
18900   //   int, long long int, or unsigned long long int.
18901   // C99 6.4.4.3p2:
18902   //   An identifier declared as an enumeration constant has type int.
18903   // The C99 rule is modified by a gcc extension
18904   QualType BestPromotionType;
18905 
18906   bool Packed = Enum->hasAttr<PackedAttr>();
18907   // -fshort-enums is the equivalent to specifying the packed attribute on all
18908   // enum definitions.
18909   if (LangOpts.ShortEnums)
18910     Packed = true;
18911 
18912   // If the enum already has a type because it is fixed or dictated by the
18913   // target, promote that type instead of analyzing the enumerators.
18914   if (Enum->isComplete()) {
18915     BestType = Enum->getIntegerType();
18916     if (BestType->isPromotableIntegerType())
18917       BestPromotionType = Context.getPromotedIntegerType(BestType);
18918     else
18919       BestPromotionType = BestType;
18920 
18921     BestWidth = Context.getIntWidth(BestType);
18922   }
18923   else if (NumNegativeBits) {
18924     // If there is a negative value, figure out the smallest integer type (of
18925     // int/long/longlong) that fits.
18926     // If it's packed, check also if it fits a char or a short.
18927     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18928       BestType = Context.SignedCharTy;
18929       BestWidth = CharWidth;
18930     } else if (Packed && NumNegativeBits <= ShortWidth &&
18931                NumPositiveBits < ShortWidth) {
18932       BestType = Context.ShortTy;
18933       BestWidth = ShortWidth;
18934     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18935       BestType = Context.IntTy;
18936       BestWidth = IntWidth;
18937     } else {
18938       BestWidth = Context.getTargetInfo().getLongWidth();
18939 
18940       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18941         BestType = Context.LongTy;
18942       } else {
18943         BestWidth = Context.getTargetInfo().getLongLongWidth();
18944 
18945         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18946           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18947         BestType = Context.LongLongTy;
18948       }
18949     }
18950     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18951   } else {
18952     // If there is no negative value, figure out the smallest type that fits
18953     // all of the enumerator values.
18954     // If it's packed, check also if it fits a char or a short.
18955     if (Packed && NumPositiveBits <= CharWidth) {
18956       BestType = Context.UnsignedCharTy;
18957       BestPromotionType = Context.IntTy;
18958       BestWidth = CharWidth;
18959     } else if (Packed && NumPositiveBits <= ShortWidth) {
18960       BestType = Context.UnsignedShortTy;
18961       BestPromotionType = Context.IntTy;
18962       BestWidth = ShortWidth;
18963     } else if (NumPositiveBits <= IntWidth) {
18964       BestType = Context.UnsignedIntTy;
18965       BestWidth = IntWidth;
18966       BestPromotionType
18967         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18968                            ? Context.UnsignedIntTy : Context.IntTy;
18969     } else if (NumPositiveBits <=
18970                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18971       BestType = Context.UnsignedLongTy;
18972       BestPromotionType
18973         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18974                            ? Context.UnsignedLongTy : Context.LongTy;
18975     } else {
18976       BestWidth = Context.getTargetInfo().getLongLongWidth();
18977       assert(NumPositiveBits <= BestWidth &&
18978              "How could an initializer get larger than ULL?");
18979       BestType = Context.UnsignedLongLongTy;
18980       BestPromotionType
18981         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18982                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18983     }
18984   }
18985 
18986   // Loop over all of the enumerator constants, changing their types to match
18987   // the type of the enum if needed.
18988   for (auto *D : Elements) {
18989     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18990     if (!ECD) continue;  // Already issued a diagnostic.
18991 
18992     // Standard C says the enumerators have int type, but we allow, as an
18993     // extension, the enumerators to be larger than int size.  If each
18994     // enumerator value fits in an int, type it as an int, otherwise type it the
18995     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18996     // that X has type 'int', not 'unsigned'.
18997 
18998     // Determine whether the value fits into an int.
18999     llvm::APSInt InitVal = ECD->getInitVal();
19000 
19001     // If it fits into an integer type, force it.  Otherwise force it to match
19002     // the enum decl type.
19003     QualType NewTy;
19004     unsigned NewWidth;
19005     bool NewSign;
19006     if (!getLangOpts().CPlusPlus &&
19007         !Enum->isFixed() &&
19008         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19009       NewTy = Context.IntTy;
19010       NewWidth = IntWidth;
19011       NewSign = true;
19012     } else if (ECD->getType() == BestType) {
19013       // Already the right type!
19014       if (getLangOpts().CPlusPlus)
19015         // C++ [dcl.enum]p4: Following the closing brace of an
19016         // enum-specifier, each enumerator has the type of its
19017         // enumeration.
19018         ECD->setType(EnumType);
19019       continue;
19020     } else {
19021       NewTy = BestType;
19022       NewWidth = BestWidth;
19023       NewSign = BestType->isSignedIntegerOrEnumerationType();
19024     }
19025 
19026     // Adjust the APSInt value.
19027     InitVal = InitVal.extOrTrunc(NewWidth);
19028     InitVal.setIsSigned(NewSign);
19029     ECD->setInitVal(InitVal);
19030 
19031     // Adjust the Expr initializer and type.
19032     if (ECD->getInitExpr() &&
19033         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19034       ECD->setInitExpr(ImplicitCastExpr::Create(
19035           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19036           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19037     if (getLangOpts().CPlusPlus)
19038       // C++ [dcl.enum]p4: Following the closing brace of an
19039       // enum-specifier, each enumerator has the type of its
19040       // enumeration.
19041       ECD->setType(EnumType);
19042     else
19043       ECD->setType(NewTy);
19044   }
19045 
19046   Enum->completeDefinition(BestType, BestPromotionType,
19047                            NumPositiveBits, NumNegativeBits);
19048 
19049   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19050 
19051   if (Enum->isClosedFlag()) {
19052     for (Decl *D : Elements) {
19053       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19054       if (!ECD) continue;  // Already issued a diagnostic.
19055 
19056       llvm::APSInt InitVal = ECD->getInitVal();
19057       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19058           !IsValueInFlagEnum(Enum, InitVal, true))
19059         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19060           << ECD << Enum;
19061     }
19062   }
19063 
19064   // Now that the enum type is defined, ensure it's not been underaligned.
19065   if (Enum->hasAttrs())
19066     CheckAlignasUnderalignment(Enum);
19067 }
19068 
19069 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19070                                   SourceLocation StartLoc,
19071                                   SourceLocation EndLoc) {
19072   StringLiteral *AsmString = cast<StringLiteral>(expr);
19073 
19074   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19075                                                    AsmString, StartLoc,
19076                                                    EndLoc);
19077   CurContext->addDecl(New);
19078   return New;
19079 }
19080 
19081 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19082                                       IdentifierInfo* AliasName,
19083                                       SourceLocation PragmaLoc,
19084                                       SourceLocation NameLoc,
19085                                       SourceLocation AliasNameLoc) {
19086   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19087                                          LookupOrdinaryName);
19088   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19089                            AttributeCommonInfo::AS_Pragma);
19090   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19091       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19092 
19093   // If a declaration that:
19094   // 1) declares a function or a variable
19095   // 2) has external linkage
19096   // already exists, add a label attribute to it.
19097   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19098     if (isDeclExternC(PrevDecl))
19099       PrevDecl->addAttr(Attr);
19100     else
19101       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19102           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19103   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19104   } else
19105     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19106 }
19107 
19108 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19109                              SourceLocation PragmaLoc,
19110                              SourceLocation NameLoc) {
19111   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19112 
19113   if (PrevDecl) {
19114     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19115   } else {
19116     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19117   }
19118 }
19119 
19120 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19121                                 IdentifierInfo* AliasName,
19122                                 SourceLocation PragmaLoc,
19123                                 SourceLocation NameLoc,
19124                                 SourceLocation AliasNameLoc) {
19125   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19126                                     LookupOrdinaryName);
19127   WeakInfo W = WeakInfo(Name, NameLoc);
19128 
19129   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19130     if (!PrevDecl->hasAttr<AliasAttr>())
19131       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19132         DeclApplyPragmaWeak(TUScope, ND, W);
19133   } else {
19134     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19135   }
19136 }
19137 
19138 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19139   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19140 }
19141 
19142 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19143                                                      bool Final) {
19144   assert(FD && "Expected non-null FunctionDecl");
19145 
19146   // SYCL functions can be template, so we check if they have appropriate
19147   // attribute prior to checking if it is a template.
19148   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19149     return FunctionEmissionStatus::Emitted;
19150 
19151   // Templates are emitted when they're instantiated.
19152   if (FD->isDependentContext())
19153     return FunctionEmissionStatus::TemplateDiscarded;
19154 
19155   // Check whether this function is an externally visible definition.
19156   auto IsEmittedForExternalSymbol = [this, FD]() {
19157     // We have to check the GVA linkage of the function's *definition* -- if we
19158     // only have a declaration, we don't know whether or not the function will
19159     // be emitted, because (say) the definition could include "inline".
19160     FunctionDecl *Def = FD->getDefinition();
19161 
19162     return Def && !isDiscardableGVALinkage(
19163                       getASTContext().GetGVALinkageForFunction(Def));
19164   };
19165 
19166   if (LangOpts.OpenMPIsDevice) {
19167     // In OpenMP device mode we will not emit host only functions, or functions
19168     // we don't need due to their linkage.
19169     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19170         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19171     // DevTy may be changed later by
19172     //  #pragma omp declare target to(*) device_type(*).
19173     // Therefore DevTy having no value does not imply host. The emission status
19174     // will be checked again at the end of compilation unit with Final = true.
19175     if (DevTy)
19176       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19177         return FunctionEmissionStatus::OMPDiscarded;
19178     // If we have an explicit value for the device type, or we are in a target
19179     // declare context, we need to emit all extern and used symbols.
19180     if (isInOpenMPDeclareTargetContext() || DevTy)
19181       if (IsEmittedForExternalSymbol())
19182         return FunctionEmissionStatus::Emitted;
19183     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19184     // we'll omit it.
19185     if (Final)
19186       return FunctionEmissionStatus::OMPDiscarded;
19187   } else if (LangOpts.OpenMP > 45) {
19188     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19189     // function. In 5.0, no_host was introduced which might cause a function to
19190     // be ommitted.
19191     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19192         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19193     if (DevTy)
19194       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19195         return FunctionEmissionStatus::OMPDiscarded;
19196   }
19197 
19198   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19199     return FunctionEmissionStatus::Emitted;
19200 
19201   if (LangOpts.CUDA) {
19202     // When compiling for device, host functions are never emitted.  Similarly,
19203     // when compiling for host, device and global functions are never emitted.
19204     // (Technically, we do emit a host-side stub for global functions, but this
19205     // doesn't count for our purposes here.)
19206     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19207     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19208       return FunctionEmissionStatus::CUDADiscarded;
19209     if (!LangOpts.CUDAIsDevice &&
19210         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19211       return FunctionEmissionStatus::CUDADiscarded;
19212 
19213     if (IsEmittedForExternalSymbol())
19214       return FunctionEmissionStatus::Emitted;
19215   }
19216 
19217   // Otherwise, the function is known-emitted if it's in our set of
19218   // known-emitted functions.
19219   return FunctionEmissionStatus::Unknown;
19220 }
19221 
19222 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19223   // Host-side references to a __global__ function refer to the stub, so the
19224   // function itself is never emitted and therefore should not be marked.
19225   // If we have host fn calls kernel fn calls host+device, the HD function
19226   // does not get instantiated on the host. We model this by omitting at the
19227   // call to the kernel from the callgraph. This ensures that, when compiling
19228   // for host, only HD functions actually called from the host get marked as
19229   // known-emitted.
19230   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19231          IdentifyCUDATarget(Callee) == CFT_Global;
19232 }
19233