1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw___ibm128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   UsingShadowDecl *FoundUsingShadow = nullptr;
376   switch (Result.getResultKind()) {
377   case LookupResult::NotFound:
378   case LookupResult::NotFoundInCurrentInstantiation:
379     if (CorrectedII) {
380       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381                                AllowDeducedTemplate);
382       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383                                               S, SS, CCC, CTK_ErrorRecovery);
384       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385       TemplateTy Template;
386       bool MemberOfUnknownSpecialization;
387       UnqualifiedId TemplateName;
388       TemplateName.setIdentifier(NewII, NameLoc);
389       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390       CXXScopeSpec NewSS, *NewSSPtr = SS;
391       if (SS && NNS) {
392         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393         NewSSPtr = &NewSS;
394       }
395       if (Correction && (NNS || NewII != &II) &&
396           // Ignore a correction to a template type as the to-be-corrected
397           // identifier is not a template (typo correction for template names
398           // is handled elsewhere).
399           !(getLangOpts().CPlusPlus && NewSSPtr &&
400             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401                            Template, MemberOfUnknownSpecialization))) {
402         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403                                     isClassName, HasTrailingDot, ObjectTypePtr,
404                                     IsCtorOrDtorName,
405                                     WantNontrivialTypeSourceInfo,
406                                     IsClassTemplateDeductionContext);
407         if (Ty) {
408           diagnoseTypo(Correction,
409                        PDiag(diag::err_unknown_type_or_class_name_suggest)
410                          << Result.getLookupName() << isClassName);
411           if (SS && NNS)
412             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413           *CorrectedII = NewII;
414           return Ty;
415         }
416       }
417     }
418     // If typo correction failed or was not performed, fall through
419     LLVM_FALLTHROUGH;
420   case LookupResult::FoundOverloaded:
421   case LookupResult::FoundUnresolvedValue:
422     Result.suppressDiagnostics();
423     return nullptr;
424 
425   case LookupResult::Ambiguous:
426     // Recover from type-hiding ambiguities by hiding the type.  We'll
427     // do the lookup again when looking for an object, and we can
428     // diagnose the error then.  If we don't do this, then the error
429     // about hiding the type will be immediately followed by an error
430     // that only makes sense if the identifier was treated like a type.
431     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432       Result.suppressDiagnostics();
433       return nullptr;
434     }
435 
436     // Look to see if we have a type anywhere in the list of results.
437     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438          Res != ResEnd; ++Res) {
439       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441               RealRes) ||
442           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
443         if (!IIDecl ||
444             // Make the selection of the recovery decl deterministic.
445             RealRes->getLocation() < IIDecl->getLocation()) {
446           IIDecl = RealRes;
447           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448         }
449       }
450     }
451 
452     if (!IIDecl) {
453       // None of the entities we found is a type, so there is no way
454       // to even assume that the result is a type. In this case, don't
455       // complain about the ambiguity. The parser will either try to
456       // perform this lookup again (e.g., as an object name), which
457       // will produce the ambiguity, or will complain that it expected
458       // a type name.
459       Result.suppressDiagnostics();
460       return nullptr;
461     }
462 
463     // We found a type within the ambiguous lookup; diagnose the
464     // ambiguity and then return that type. This might be the right
465     // answer, or it might not be, but it suppresses any attempt to
466     // perform the name lookup again.
467     break;
468 
469   case LookupResult::Found:
470     IIDecl = Result.getFoundDecl();
471     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472     break;
473   }
474 
475   assert(IIDecl && "Didn't find decl");
476 
477   QualType T;
478   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479     // C++ [class.qual]p2: A lookup that would find the injected-class-name
480     // instead names the constructors of the class, except when naming a class.
481     // This is ill-formed when we're not actually forming a ctor or dtor name.
482     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485         FoundRD->isInjectedClassName() &&
486         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
487       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488           << &II << /*Type*/1;
489 
490     DiagnoseUseOfDecl(IIDecl, NameLoc);
491 
492     T = Context.getTypeDeclType(TD);
493     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496     if (!HasTrailingDot)
497       T = Context.getObjCInterfaceType(IDecl);
498     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500     (void)DiagnoseUseOfDecl(UD, NameLoc);
501     // Recover with 'int'
502     T = Context.IntTy;
503     FoundUsingShadow = nullptr;
504   } else if (AllowDeducedTemplate) {
505     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506       // FIXME: TemplateName should include FoundUsingShadow sugar.
507       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
508                                                        QualType(), false);
509       // Don't wrap in a further UsingType.
510       FoundUsingShadow = nullptr;
511     }
512   }
513 
514   if (T.isNull()) {
515     // If it's not plausibly a type, suppress diagnostics.
516     Result.suppressDiagnostics();
517     return nullptr;
518   }
519 
520   if (FoundUsingShadow)
521     T = Context.getUsingType(FoundUsingShadow, T);
522 
523   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524   // constructor or destructor name (in such a case, the scope specifier
525   // will be attached to the enclosing Expr or Decl node).
526   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
527       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528     if (WantNontrivialTypeSourceInfo) {
529       // Construct a type with type-source information.
530       TypeLocBuilder Builder;
531       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532 
533       T = getElaboratedType(ETK_None, *SS, T);
534       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
535       ElabTL.setElaboratedKeywordLoc(SourceLocation());
536       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538     } else {
539       T = getElaboratedType(ETK_None, *SS, T);
540     }
541   }
542 
543   return ParsedType::make(T);
544 }
545 
546 // Builds a fake NNS for the given decl context.
547 static NestedNameSpecifier *
548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
549   for (;; DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     auto *ND = dyn_cast<NamespaceDecl>(DC);
552     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
553       return NestedNameSpecifier::Create(Context, nullptr, ND);
554     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556                                          RD->getTypeForDecl());
557     else if (isa<TranslationUnitDecl>(DC))
558       return NestedNameSpecifier::GlobalSpecifier(Context);
559   }
560   llvm_unreachable("something isn't in TU scope?");
561 }
562 
563 /// Find the parent class with dependent bases of the innermost enclosing method
564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565 /// up allowing unqualified dependent type names at class-level, which MSVC
566 /// correctly rejects.
567 static const CXXRecordDecl *
568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
569   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
570     DC = DC->getPrimaryContext();
571     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572       if (MD->getParent()->hasAnyDependentBases())
573         return MD->getParent();
574   }
575   return nullptr;
576 }
577 
578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
579                                           SourceLocation NameLoc,
580                                           bool IsTemplateTypeArg) {
581   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582 
583   NestedNameSpecifier *NNS = nullptr;
584   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
585     // If we weren't able to parse a default template argument, delay lookup
586     // until instantiation time by making a non-dependent DependentTypeName. We
587     // pretend we saw a NestedNameSpecifier referring to the current scope, and
588     // lookup is retried.
589     // FIXME: This hurts our diagnostic quality, since we get errors like "no
590     // type named 'Foo' in 'current_namespace'" when the user didn't write any
591     // name specifiers.
592     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594   } else if (const CXXRecordDecl *RD =
595                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
596     // Build a DependentNameType that will perform lookup into RD at
597     // instantiation time.
598     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599                                       RD->getTypeForDecl());
600 
601     // Diagnose that this identifier was undeclared, and retry the lookup during
602     // template instantiation.
603     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604                                                                       << RD;
605   } else {
606     // This is not a situation that we should recover from.
607     return ParsedType();
608   }
609 
610   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611 
612   // Build type location information.  We synthesized the qualifier, so we have
613   // to build a fake NestedNameSpecifierLoc.
614   NestedNameSpecifierLocBuilder NNSLocBuilder;
615   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617 
618   TypeLocBuilder Builder;
619   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620   DepTL.setNameLoc(NameLoc);
621   DepTL.setElaboratedKeywordLoc(SourceLocation());
622   DepTL.setQualifierLoc(QualifierLoc);
623   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624 }
625 
626 /// isTagName() - This method is called *for error recovery purposes only*
627 /// to determine if the specified name is a valid tag name ("struct foo").  If
628 /// so, this returns the TST for the tag corresponding to it (TST_enum,
629 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
630 /// cases in C where the user forgot to specify the tag.
631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
632   // Do a tag name lookup in this scope.
633   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634   LookupName(R, S, false);
635   R.suppressDiagnostics();
636   if (R.getResultKind() == LookupResult::Found)
637     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638       switch (TD->getTagKind()) {
639       case TTK_Struct: return DeclSpec::TST_struct;
640       case TTK_Interface: return DeclSpec::TST_interface;
641       case TTK_Union:  return DeclSpec::TST_union;
642       case TTK_Class:  return DeclSpec::TST_class;
643       case TTK_Enum:   return DeclSpec::TST_enum;
644       }
645     }
646 
647   return DeclSpec::TST_unspecified;
648 }
649 
650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
652 /// then downgrade the missing typename error to a warning.
653 /// This is needed for MSVC compatibility; Example:
654 /// @code
655 /// template<class T> class A {
656 /// public:
657 ///   typedef int TYPE;
658 /// };
659 /// template<class T> class B : public A<T> {
660 /// public:
661 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
662 /// };
663 /// @endcode
664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
665   if (CurContext->isRecord()) {
666     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
667       return true;
668 
669     const Type *Ty = SS->getScopeRep()->getAsType();
670 
671     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672     for (const auto &Base : RD->bases())
673       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674         return true;
675     return S->isFunctionPrototypeScope();
676   }
677   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678 }
679 
680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
681                                    SourceLocation IILoc,
682                                    Scope *S,
683                                    CXXScopeSpec *SS,
684                                    ParsedType &SuggestedType,
685                                    bool IsTemplateName) {
686   // Don't report typename errors for editor placeholders.
687   if (II->isEditorPlaceholder())
688     return;
689   // We don't have anything to suggest (yet).
690   SuggestedType = nullptr;
691 
692   // There may have been a typo in the name of the type. Look up typo
693   // results, in case we have something that we can suggest.
694   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695                            /*AllowTemplates=*/IsTemplateName,
696                            /*AllowNonTemplates=*/!IsTemplateName);
697   if (TypoCorrection Corrected =
698           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699                       CCC, CTK_ErrorRecovery)) {
700     // FIXME: Support error recovery for the template-name case.
701     bool CanRecover = !IsTemplateName;
702     if (Corrected.isKeyword()) {
703       // We corrected to a keyword.
704       diagnoseTypo(Corrected,
705                    PDiag(IsTemplateName ? diag::err_no_template_suggest
706                                         : diag::err_unknown_typename_suggest)
707                        << II);
708       II = Corrected.getCorrectionAsIdentifierInfo();
709     } else {
710       // We found a similarly-named type or interface; suggest that.
711       if (!SS || !SS->isSet()) {
712         diagnoseTypo(Corrected,
713                      PDiag(IsTemplateName ? diag::err_no_template_suggest
714                                           : diag::err_unknown_typename_suggest)
715                          << II, CanRecover);
716       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719                                 II->getName().equals(CorrectedStr);
720         diagnoseTypo(Corrected,
721                      PDiag(IsTemplateName
722                                ? diag::err_no_member_template_suggest
723                                : diag::err_unknown_nested_typename_suggest)
724                          << II << DC << DroppedSpecifier << SS->getRange(),
725                      CanRecover);
726       } else {
727         llvm_unreachable("could not have corrected a typo here");
728       }
729 
730       if (!CanRecover)
731         return;
732 
733       CXXScopeSpec tmpSS;
734       if (Corrected.getCorrectionSpecifier())
735         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736                           SourceRange(IILoc));
737       // FIXME: Support class template argument deduction here.
738       SuggestedType =
739           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741                       /*IsCtorOrDtorName=*/false,
742                       /*WantNontrivialTypeSourceInfo=*/true);
743     }
744     return;
745   }
746 
747   if (getLangOpts().CPlusPlus && !IsTemplateName) {
748     // See if II is a class template that the user forgot to pass arguments to.
749     UnqualifiedId Name;
750     Name.setIdentifier(II, IILoc);
751     CXXScopeSpec EmptySS;
752     TemplateTy TemplateResult;
753     bool MemberOfUnknownSpecialization;
754     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755                        Name, nullptr, true, TemplateResult,
756                        MemberOfUnknownSpecialization) == TNK_Type_template) {
757       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758       return;
759     }
760   }
761 
762   // FIXME: Should we move the logic that tries to recover from a missing tag
763   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764 
765   if (!SS || (!SS->isSet() && !SS->isInvalid()))
766     Diag(IILoc, IsTemplateName ? diag::err_no_template
767                                : diag::err_unknown_typename)
768         << II;
769   else if (DeclContext *DC = computeDeclContext(*SS, false))
770     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771                                : diag::err_typename_nested_not_found)
772         << II << DC << SS->getRange();
773   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774     SuggestedType =
775         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776   } else if (isDependentScopeSpecifier(*SS)) {
777     unsigned DiagID = diag::err_typename_missing;
778     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779       DiagID = diag::ext_typename_missing;
780 
781     Diag(SS->getRange().getBegin(), DiagID)
782       << SS->getScopeRep() << II->getName()
783       << SourceRange(SS->getRange().getBegin(), IILoc)
784       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785     SuggestedType = ActOnTypenameType(S, SourceLocation(),
786                                       *SS, *II, IILoc).get();
787   } else {
788     assert(SS && SS->isInvalid() &&
789            "Invalid scope specifier has already been diagnosed");
790   }
791 }
792 
793 /// Determine whether the given result set contains either a type name
794 /// or
795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797                        NextToken.is(tok::less);
798 
799   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801       return true;
802 
803     if (CheckTemplate && isa<TemplateDecl>(*I))
804       return true;
805   }
806 
807   return false;
808 }
809 
810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811                                     Scope *S, CXXScopeSpec &SS,
812                                     IdentifierInfo *&Name,
813                                     SourceLocation NameLoc) {
814   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815   SemaRef.LookupParsedName(R, S, &SS);
816   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817     StringRef FixItTagName;
818     switch (Tag->getTagKind()) {
819       case TTK_Class:
820         FixItTagName = "class ";
821         break;
822 
823       case TTK_Enum:
824         FixItTagName = "enum ";
825         break;
826 
827       case TTK_Struct:
828         FixItTagName = "struct ";
829         break;
830 
831       case TTK_Interface:
832         FixItTagName = "__interface ";
833         break;
834 
835       case TTK_Union:
836         FixItTagName = "union ";
837         break;
838     }
839 
840     StringRef TagName = FixItTagName.drop_back();
841     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844 
845     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846          I != IEnd; ++I)
847       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848         << Name << TagName;
849 
850     // Replace lookup results with just the tag decl.
851     Result.clear(Sema::LookupTagName);
852     SemaRef.LookupParsedName(Result, S, &SS);
853     return true;
854   }
855 
856   return false;
857 }
858 
859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
860                                             IdentifierInfo *&Name,
861                                             SourceLocation NameLoc,
862                                             const Token &NextToken,
863                                             CorrectionCandidateCallback *CCC) {
864   DeclarationNameInfo NameInfo(Name, NameLoc);
865   ObjCMethodDecl *CurMethod = getCurMethodDecl();
866 
867   assert(NextToken.isNot(tok::coloncolon) &&
868          "parse nested name specifiers before calling ClassifyName");
869   if (getLangOpts().CPlusPlus && SS.isSet() &&
870       isCurrentClassName(*Name, S, &SS)) {
871     // Per [class.qual]p2, this names the constructors of SS, not the
872     // injected-class-name. We don't have a classification for that.
873     // There's not much point caching this result, since the parser
874     // will reject it later.
875     return NameClassification::Unknown();
876   }
877 
878   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879   LookupParsedName(Result, S, &SS, !CurMethod);
880 
881   if (SS.isInvalid())
882     return NameClassification::Error();
883 
884   // For unqualified lookup in a class template in MSVC mode, look into
885   // dependent base classes where the primary class template is known.
886   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887     if (ParsedType TypeInBase =
888             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889       return TypeInBase;
890   }
891 
892   // Perform lookup for Objective-C instance variables (including automatically
893   // synthesized instance variables), if we're in an Objective-C method.
894   // FIXME: This lookup really, really needs to be folded in to the normal
895   // unqualified lookup mechanism.
896   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898     if (Ivar.isInvalid())
899       return NameClassification::Error();
900     if (Ivar.isUsable())
901       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902 
903     // We defer builtin creation until after ivar lookup inside ObjC methods.
904     if (Result.empty())
905       LookupBuiltin(Result);
906   }
907 
908   bool SecondTry = false;
909   bool IsFilteredTemplateName = false;
910 
911 Corrected:
912   switch (Result.getResultKind()) {
913   case LookupResult::NotFound:
914     // If an unqualified-id is followed by a '(', then we have a function
915     // call.
916     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917       // In C++, this is an ADL-only call.
918       // FIXME: Reference?
919       if (getLangOpts().CPlusPlus)
920         return NameClassification::UndeclaredNonType();
921 
922       // C90 6.3.2.2:
923       //   If the expression that precedes the parenthesized argument list in a
924       //   function call consists solely of an identifier, and if no
925       //   declaration is visible for this identifier, the identifier is
926       //   implicitly declared exactly as if, in the innermost block containing
927       //   the function call, the declaration
928       //
929       //     extern int identifier ();
930       //
931       //   appeared.
932       //
933       // We also allow this in C99 as an extension.
934       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935         return NameClassification::NonType(D);
936     }
937 
938     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
939       // In C++20 onwards, this could be an ADL-only call to a function
940       // template, and we're required to assume that this is a template name.
941       //
942       // FIXME: Find a way to still do typo correction in this case.
943       TemplateName Template =
944           Context.getAssumedTemplateName(NameInfo.getName());
945       return NameClassification::UndeclaredTemplate(Template);
946     }
947 
948     // In C, we first see whether there is a tag type by the same name, in
949     // which case it's likely that the user just forgot to write "enum",
950     // "struct", or "union".
951     if (!getLangOpts().CPlusPlus && !SecondTry &&
952         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
953       break;
954     }
955 
956     // Perform typo correction to determine if there is another name that is
957     // close to this name.
958     if (!SecondTry && CCC) {
959       SecondTry = true;
960       if (TypoCorrection Corrected =
961               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962                           &SS, *CCC, CTK_ErrorRecovery)) {
963         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964         unsigned QualifiedDiag = diag::err_no_member_suggest;
965 
966         NamedDecl *FirstDecl = Corrected.getFoundDecl();
967         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
969             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970           UnqualifiedDiag = diag::err_no_template_suggest;
971           QualifiedDiag = diag::err_no_member_template_suggest;
972         } else if (UnderlyingFirstDecl &&
973                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
974                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976           UnqualifiedDiag = diag::err_unknown_typename_suggest;
977           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978         }
979 
980         if (SS.isEmpty()) {
981           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982         } else {// FIXME: is this even reachable? Test it.
983           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985                                   Name->getName().equals(CorrectedStr);
986           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987                                     << Name << computeDeclContext(SS, false)
988                                     << DroppedSpecifier << SS.getRange());
989         }
990 
991         // Update the name, so that the caller has the new name.
992         Name = Corrected.getCorrectionAsIdentifierInfo();
993 
994         // Typo correction corrected to a keyword.
995         if (Corrected.isKeyword())
996           return Name;
997 
998         // Also update the LookupResult...
999         // FIXME: This should probably go away at some point
1000         Result.clear();
1001         Result.setLookupName(Corrected.getCorrection());
1002         if (FirstDecl)
1003           Result.addDecl(FirstDecl);
1004 
1005         // If we found an Objective-C instance variable, let
1006         // LookupInObjCMethod build the appropriate expression to
1007         // reference the ivar.
1008         // FIXME: This is a gross hack.
1009         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010           DeclResult R =
1011               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012           if (R.isInvalid())
1013             return NameClassification::Error();
1014           if (R.isUsable())
1015             return NameClassification::NonType(Ivar);
1016         }
1017 
1018         goto Corrected;
1019       }
1020     }
1021 
1022     // We failed to correct; just fall through and let the parser deal with it.
1023     Result.suppressDiagnostics();
1024     return NameClassification::Unknown();
1025 
1026   case LookupResult::NotFoundInCurrentInstantiation: {
1027     // We performed name lookup into the current instantiation, and there were
1028     // dependent bases, so we treat this result the same way as any other
1029     // dependent nested-name-specifier.
1030 
1031     // C++ [temp.res]p2:
1032     //   A name used in a template declaration or definition and that is
1033     //   dependent on a template-parameter is assumed not to name a type
1034     //   unless the applicable name lookup finds a type name or the name is
1035     //   qualified by the keyword typename.
1036     //
1037     // FIXME: If the next token is '<', we might want to ask the parser to
1038     // perform some heroics to see if we actually have a
1039     // template-argument-list, which would indicate a missing 'template'
1040     // keyword here.
1041     return NameClassification::DependentNonType();
1042   }
1043 
1044   case LookupResult::Found:
1045   case LookupResult::FoundOverloaded:
1046   case LookupResult::FoundUnresolvedValue:
1047     break;
1048 
1049   case LookupResult::Ambiguous:
1050     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1051         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052                                       /*AllowDependent=*/false)) {
1053       // C++ [temp.local]p3:
1054       //   A lookup that finds an injected-class-name (10.2) can result in an
1055       //   ambiguity in certain cases (for example, if it is found in more than
1056       //   one base class). If all of the injected-class-names that are found
1057       //   refer to specializations of the same class template, and if the name
1058       //   is followed by a template-argument-list, the reference refers to the
1059       //   class template itself and not a specialization thereof, and is not
1060       //   ambiguous.
1061       //
1062       // This filtering can make an ambiguous result into an unambiguous one,
1063       // so try again after filtering out template names.
1064       FilterAcceptableTemplateNames(Result);
1065       if (!Result.isAmbiguous()) {
1066         IsFilteredTemplateName = true;
1067         break;
1068       }
1069     }
1070 
1071     // Diagnose the ambiguity and return an error.
1072     return NameClassification::Error();
1073   }
1074 
1075   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076       (IsFilteredTemplateName ||
1077        hasAnyAcceptableTemplateNames(
1078            Result, /*AllowFunctionTemplates=*/true,
1079            /*AllowDependent=*/false,
1080            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081                getLangOpts().CPlusPlus20))) {
1082     // C++ [temp.names]p3:
1083     //   After name lookup (3.4) finds that a name is a template-name or that
1084     //   an operator-function-id or a literal- operator-id refers to a set of
1085     //   overloaded functions any member of which is a function template if
1086     //   this is followed by a <, the < is always taken as the delimiter of a
1087     //   template-argument-list and never as the less-than operator.
1088     // C++2a [temp.names]p2:
1089     //   A name is also considered to refer to a template if it is an
1090     //   unqualified-id followed by a < and name lookup finds either one
1091     //   or more functions or finds nothing.
1092     if (!IsFilteredTemplateName)
1093       FilterAcceptableTemplateNames(Result);
1094 
1095     bool IsFunctionTemplate;
1096     bool IsVarTemplate;
1097     TemplateName Template;
1098     if (Result.end() - Result.begin() > 1) {
1099       IsFunctionTemplate = true;
1100       Template = Context.getOverloadedTemplateName(Result.begin(),
1101                                                    Result.end());
1102     } else if (!Result.empty()) {
1103       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104           *Result.begin(), /*AllowFunctionTemplates=*/true,
1105           /*AllowDependent=*/false));
1106       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107       IsVarTemplate = isa<VarTemplateDecl>(TD);
1108 
1109       if (SS.isNotEmpty())
1110         Template =
1111             Context.getQualifiedTemplateName(SS.getScopeRep(),
1112                                              /*TemplateKeyword=*/false, TD);
1113       else
1114         Template = TemplateName(TD);
1115     } else {
1116       // All results were non-template functions. This is a function template
1117       // name.
1118       IsFunctionTemplate = true;
1119       Template = Context.getAssumedTemplateName(NameInfo.getName());
1120     }
1121 
1122     if (IsFunctionTemplate) {
1123       // Function templates always go through overload resolution, at which
1124       // point we'll perform the various checks (e.g., accessibility) we need
1125       // to based on which function we selected.
1126       Result.suppressDiagnostics();
1127 
1128       return NameClassification::FunctionTemplate(Template);
1129     }
1130 
1131     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132                          : NameClassification::TypeTemplate(Template);
1133   }
1134 
1135   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136     QualType T = Context.getTypeDeclType(Type);
1137     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138       T = Context.getUsingType(USD, T);
1139 
1140     if (SS.isEmpty()) // No elaborated type, trivial location info
1141       return ParsedType::make(T);
1142 
1143     TypeLocBuilder Builder;
1144     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145     T = getElaboratedType(ETK_None, SS, T);
1146     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1147     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1148     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150   };
1151 
1152   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154     DiagnoseUseOfDecl(Type, NameLoc);
1155     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156     return BuildTypeFor(Type, *Result.begin());
1157   }
1158 
1159   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160   if (!Class) {
1161     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162     if (ObjCCompatibleAliasDecl *Alias =
1163             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164       Class = Alias->getClassInterface();
1165   }
1166 
1167   if (Class) {
1168     DiagnoseUseOfDecl(Class, NameLoc);
1169 
1170     if (NextToken.is(tok::period)) {
1171       // Interface. <something> is parsed as a property reference expression.
1172       // Just return "unknown" as a fall-through for now.
1173       Result.suppressDiagnostics();
1174       return NameClassification::Unknown();
1175     }
1176 
1177     QualType T = Context.getObjCInterfaceType(Class);
1178     return ParsedType::make(T);
1179   }
1180 
1181   if (isa<ConceptDecl>(FirstDecl))
1182     return NameClassification::Concept(
1183         TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 
1185   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187     return NameClassification::Error();
1188   }
1189 
1190   // We can have a type template here if we're classifying a template argument.
1191   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192       !isa<VarTemplateDecl>(FirstDecl))
1193     return NameClassification::TypeTemplate(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   // Check for a tag type hidden by a non-type decl in a few cases where it
1197   // seems likely a type is wanted instead of the non-type that was found.
1198   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199   if ((NextToken.is(tok::identifier) ||
1200        (NextIsOp &&
1201         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204     DiagnoseUseOfDecl(Type, NameLoc);
1205     return BuildTypeFor(Type, *Result.begin());
1206   }
1207 
1208   // If we already know which single declaration is referenced, just annotate
1209   // that declaration directly. Defer resolving even non-overloaded class
1210   // member accesses, as we need to defer certain access checks until we know
1211   // the context.
1212   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1214     return NameClassification::NonType(Result.getRepresentativeDecl());
1215 
1216   // Otherwise, this is an overload set that we will need to resolve later.
1217   Result.suppressDiagnostics();
1218   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221       Result.begin(), Result.end()));
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1226                                              SourceLocation NameLoc) {
1227   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228   CXXScopeSpec SS;
1229   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231 }
1232 
1233 ExprResult
1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1235                                             IdentifierInfo *Name,
1236                                             SourceLocation NameLoc,
1237                                             bool IsAddressOfOperand) {
1238   DeclarationNameInfo NameInfo(Name, NameLoc);
1239   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240                                     NameInfo, IsAddressOfOperand,
1241                                     /*TemplateArgs=*/nullptr);
1242 }
1243 
1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1245                                               NamedDecl *Found,
1246                                               SourceLocation NameLoc,
1247                                               const Token &NextToken) {
1248   if (getCurMethodDecl() && SS.isEmpty())
1249     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250       return BuildIvarRefExpr(S, NameLoc, Ivar);
1251 
1252   // Reconstruct the lookup result.
1253   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254   Result.addDecl(Found);
1255   Result.resolveKind();
1256 
1257   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258   return BuildDeclarationNameExpr(SS, Result, ADL);
1259 }
1260 
1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1262   // For an implicit class member access, transform the result into a member
1263   // access expression if necessary.
1264   auto *ULE = cast<UnresolvedLookupExpr>(E);
1265   if ((*ULE->decls_begin())->isCXXClassMember()) {
1266     CXXScopeSpec SS;
1267     SS.Adopt(ULE->getQualifierLoc());
1268 
1269     // Reconstruct the lookup result.
1270     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271                         LookupOrdinaryName);
1272     Result.setNamingClass(ULE->getNamingClass());
1273     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274       Result.addDecl(*I, I.getAccess());
1275     Result.resolveKind();
1276     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277                                            nullptr, S);
1278   }
1279 
1280   // Otherwise, this is already in the form we needed, and no further checks
1281   // are necessary.
1282   return ULE;
1283 }
1284 
1285 Sema::TemplateNameKindForDiagnostics
1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1287   auto *TD = Name.getAsTemplateDecl();
1288   if (!TD)
1289     return TemplateNameKindForDiagnostics::DependentTemplate;
1290   if (isa<ClassTemplateDecl>(TD))
1291     return TemplateNameKindForDiagnostics::ClassTemplate;
1292   if (isa<FunctionTemplateDecl>(TD))
1293     return TemplateNameKindForDiagnostics::FunctionTemplate;
1294   if (isa<VarTemplateDecl>(TD))
1295     return TemplateNameKindForDiagnostics::VarTemplate;
1296   if (isa<TypeAliasTemplateDecl>(TD))
1297     return TemplateNameKindForDiagnostics::AliasTemplate;
1298   if (isa<TemplateTemplateParmDecl>(TD))
1299     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300   if (isa<ConceptDecl>(TD))
1301     return TemplateNameKindForDiagnostics::Concept;
1302   return TemplateNameKindForDiagnostics::DependentTemplate;
1303 }
1304 
1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1306   assert(DC->getLexicalParent() == CurContext &&
1307       "The next DeclContext should be lexically contained in the current one.");
1308   CurContext = DC;
1309   S->setEntity(DC);
1310 }
1311 
1312 void Sema::PopDeclContext() {
1313   assert(CurContext && "DeclContext imbalance!");
1314 
1315   CurContext = CurContext->getLexicalParent();
1316   assert(CurContext && "Popped translation unit!");
1317 }
1318 
1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1320                                                                     Decl *D) {
1321   // Unlike PushDeclContext, the context to which we return is not necessarily
1322   // the containing DC of TD, because the new context will be some pre-existing
1323   // TagDecl definition instead of a fresh one.
1324   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325   CurContext = cast<TagDecl>(D)->getDefinition();
1326   assert(CurContext && "skipping definition of undefined tag");
1327   // Start lookups from the parent of the current context; we don't want to look
1328   // into the pre-existing complete definition.
1329   S->setEntity(CurContext->getLookupParent());
1330   return Result;
1331 }
1332 
1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1334   CurContext = static_cast<decltype(CurContext)>(Context);
1335 }
1336 
1337 /// EnterDeclaratorContext - Used when we must lookup names in the context
1338 /// of a declarator's nested name specifier.
1339 ///
1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1341   // C++0x [basic.lookup.unqual]p13:
1342   //   A name used in the definition of a static data member of class
1343   //   X (after the qualified-id of the static member) is looked up as
1344   //   if the name was used in a member function of X.
1345   // C++0x [basic.lookup.unqual]p14:
1346   //   If a variable member of a namespace is defined outside of the
1347   //   scope of its namespace then any name used in the definition of
1348   //   the variable member (after the declarator-id) is looked up as
1349   //   if the definition of the variable member occurred in its
1350   //   namespace.
1351   // Both of these imply that we should push a scope whose context
1352   // is the semantic context of the declaration.  We can't use
1353   // PushDeclContext here because that context is not necessarily
1354   // lexically contained in the current context.  Fortunately,
1355   // the containing scope should have the appropriate information.
1356 
1357   assert(!S->getEntity() && "scope already has entity");
1358 
1359 #ifndef NDEBUG
1360   Scope *Ancestor = S->getParent();
1361   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363 #endif
1364 
1365   CurContext = DC;
1366   S->setEntity(DC);
1367 
1368   if (S->getParent()->isTemplateParamScope()) {
1369     // Also set the corresponding entities for all immediately-enclosing
1370     // template parameter scopes.
1371     EnterTemplatedContext(S->getParent(), DC);
1372   }
1373 }
1374 
1375 void Sema::ExitDeclaratorContext(Scope *S) {
1376   assert(S->getEntity() == CurContext && "Context imbalance!");
1377 
1378   // Switch back to the lexical context.  The safety of this is
1379   // enforced by an assert in EnterDeclaratorContext.
1380   Scope *Ancestor = S->getParent();
1381   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382   CurContext = Ancestor->getEntity();
1383 
1384   // We don't need to do anything with the scope, which is going to
1385   // disappear.
1386 }
1387 
1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1389   assert(S->isTemplateParamScope() &&
1390          "expected to be initializing a template parameter scope");
1391 
1392   // C++20 [temp.local]p7:
1393   //   In the definition of a member of a class template that appears outside
1394   //   of the class template definition, the name of a member of the class
1395   //   template hides the name of a template-parameter of any enclosing class
1396   //   templates (but not a template-parameter of the member if the member is a
1397   //   class or function template).
1398   // C++20 [temp.local]p9:
1399   //   In the definition of a class template or in the definition of a member
1400   //   of such a template that appears outside of the template definition, for
1401   //   each non-dependent base class (13.8.2.1), if the name of the base class
1402   //   or the name of a member of the base class is the same as the name of a
1403   //   template-parameter, the base class name or member name hides the
1404   //   template-parameter name (6.4.10).
1405   //
1406   // This means that a template parameter scope should be searched immediately
1407   // after searching the DeclContext for which it is a template parameter
1408   // scope. For example, for
1409   //   template<typename T> template<typename U> template<typename V>
1410   //     void N::A<T>::B<U>::f(...)
1411   // we search V then B<U> (and base classes) then U then A<T> (and base
1412   // classes) then T then N then ::.
1413   unsigned ScopeDepth = getTemplateDepth(S);
1414   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415     DeclContext *SearchDCAfterScope = DC;
1416     for (; DC; DC = DC->getLookupParent()) {
1417       if (const TemplateParameterList *TPL =
1418               cast<Decl>(DC)->getDescribedTemplateParams()) {
1419         unsigned DCDepth = TPL->getDepth() + 1;
1420         if (DCDepth > ScopeDepth)
1421           continue;
1422         if (ScopeDepth == DCDepth)
1423           SearchDCAfterScope = DC = DC->getLookupParent();
1424         break;
1425       }
1426     }
1427     S->setLookupEntity(SearchDCAfterScope);
1428   }
1429 }
1430 
1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1432   // We assume that the caller has already called
1433   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434   FunctionDecl *FD = D->getAsFunction();
1435   if (!FD)
1436     return;
1437 
1438   // Same implementation as PushDeclContext, but enters the context
1439   // from the lexical parent, rather than the top-level class.
1440   assert(CurContext == FD->getLexicalParent() &&
1441     "The next DeclContext should be lexically contained in the current one.");
1442   CurContext = FD;
1443   S->setEntity(CurContext);
1444 
1445   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446     ParmVarDecl *Param = FD->getParamDecl(P);
1447     // If the parameter has an identifier, then add it to the scope
1448     if (Param->getIdentifier()) {
1449       S->AddDecl(Param);
1450       IdResolver.AddDecl(Param);
1451     }
1452   }
1453 }
1454 
1455 void Sema::ActOnExitFunctionContext() {
1456   // Same implementation as PopDeclContext, but returns to the lexical parent,
1457   // rather than the top-level class.
1458   assert(CurContext && "DeclContext imbalance!");
1459   CurContext = CurContext->getLexicalParent();
1460   assert(CurContext && "Popped translation unit!");
1461 }
1462 
1463 /// Determine whether overloading is allowed for a new function
1464 /// declaration considering prior declarations of the same name.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether a new declaration actually overloads a previous one.
1468 /// It will return true in C++ (where overloads are alway permitted)
1469 /// or, as a C extension, when either the new declaration or a
1470 /// previous one is declared with the 'overloadable' attribute.
1471 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1472                                        ASTContext &Context,
1473                                        const FunctionDecl *New) {
1474   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1475     return true;
1476 
1477   // Multiversion function declarations are not overloads in the
1478   // usual sense of that term, but lookup will report that an
1479   // overload set was found if more than one multiversion function
1480   // declaration is present for the same name. It is therefore
1481   // inadequate to assume that some prior declaration(s) had
1482   // the overloadable attribute; checking is required. Since one
1483   // declaration is permitted to omit the attribute, it is necessary
1484   // to check at least two; hence the 'any_of' check below. Note that
1485   // the overloadable attribute is implicitly added to declarations
1486   // that were required to have it but did not.
1487   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1488     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1489       return ND->hasAttr<OverloadableAttr>();
1490     });
1491   } else if (Previous.getResultKind() == LookupResult::Found)
1492     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1493 
1494   return false;
1495 }
1496 
1497 /// Add this decl to the scope shadowed decl chains.
1498 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1499   // Move up the scope chain until we find the nearest enclosing
1500   // non-transparent context. The declaration will be introduced into this
1501   // scope.
1502   while (S->getEntity() && S->getEntity()->isTransparentContext())
1503     S = S->getParent();
1504 
1505   // Add scoped declarations into their context, so that they can be
1506   // found later. Declarations without a context won't be inserted
1507   // into any context.
1508   if (AddToContext)
1509     CurContext->addDecl(D);
1510 
1511   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1512   // are function-local declarations.
1513   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1514     return;
1515 
1516   // Template instantiations should also not be pushed into scope.
1517   if (isa<FunctionDecl>(D) &&
1518       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1519     return;
1520 
1521   // If this replaces anything in the current scope,
1522   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1523                                IEnd = IdResolver.end();
1524   for (; I != IEnd; ++I) {
1525     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1526       S->RemoveDecl(*I);
1527       IdResolver.RemoveDecl(*I);
1528 
1529       // Should only need to replace one decl.
1530       break;
1531     }
1532   }
1533 
1534   S->AddDecl(D);
1535 
1536   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1537     // Implicitly-generated labels may end up getting generated in an order that
1538     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1539     // the label at the appropriate place in the identifier chain.
1540     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1541       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1542       if (IDC == CurContext) {
1543         if (!S->isDeclScope(*I))
1544           continue;
1545       } else if (IDC->Encloses(CurContext))
1546         break;
1547     }
1548 
1549     IdResolver.InsertDeclAfter(I, D);
1550   } else {
1551     IdResolver.AddDecl(D);
1552   }
1553   warnOnReservedIdentifier(D);
1554 }
1555 
1556 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1557                          bool AllowInlineNamespace) {
1558   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1559 }
1560 
1561 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1562   DeclContext *TargetDC = DC->getPrimaryContext();
1563   do {
1564     if (DeclContext *ScopeDC = S->getEntity())
1565       if (ScopeDC->getPrimaryContext() == TargetDC)
1566         return S;
1567   } while ((S = S->getParent()));
1568 
1569   return nullptr;
1570 }
1571 
1572 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1573                                             DeclContext*,
1574                                             ASTContext&);
1575 
1576 /// Filters out lookup results that don't fall within the given scope
1577 /// as determined by isDeclInScope.
1578 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1579                                 bool ConsiderLinkage,
1580                                 bool AllowInlineNamespace) {
1581   LookupResult::Filter F = R.makeFilter();
1582   while (F.hasNext()) {
1583     NamedDecl *D = F.next();
1584 
1585     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586       continue;
1587 
1588     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589       continue;
1590 
1591     F.erase();
1592   }
1593 
1594   F.done();
1595 }
1596 
1597 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1598 /// have compatible owning modules.
1599 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1600   // [module.interface]p7:
1601   // A declaration is attached to a module as follows:
1602   // - If the declaration is a non-dependent friend declaration that nominates a
1603   // function with a declarator-id that is a qualified-id or template-id or that
1604   // nominates a class other than with an elaborated-type-specifier with neither
1605   // a nested-name-specifier nor a simple-template-id, it is attached to the
1606   // module to which the friend is attached ([basic.link]).
1607   if (New->getFriendObjectKind() &&
1608       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1609     New->setLocalOwningModule(Old->getOwningModule());
1610     makeMergedDefinitionVisible(New);
1611     return false;
1612   }
1613 
1614   Module *NewM = New->getOwningModule();
1615   Module *OldM = Old->getOwningModule();
1616 
1617   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1618     NewM = NewM->Parent;
1619   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1620     OldM = OldM->Parent;
1621 
1622   // If we have a decl in a module partition, it is part of the containing
1623   // module (which is the only thing that can be importing it).
1624   if (NewM && OldM &&
1625       (OldM->Kind == Module::ModulePartitionInterface ||
1626        OldM->Kind == Module::ModulePartitionImplementation)) {
1627     return false;
1628   }
1629 
1630   if (NewM == OldM)
1631     return false;
1632 
1633   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1634   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1635   if (NewIsModuleInterface || OldIsModuleInterface) {
1636     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1637     //   if a declaration of D [...] appears in the purview of a module, all
1638     //   other such declarations shall appear in the purview of the same module
1639     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1640       << New
1641       << NewIsModuleInterface
1642       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1643       << OldIsModuleInterface
1644       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1645     Diag(Old->getLocation(), diag::note_previous_declaration);
1646     New->setInvalidDecl();
1647     return true;
1648   }
1649 
1650   return false;
1651 }
1652 
1653 // [module.interface]p6:
1654 // A redeclaration of an entity X is implicitly exported if X was introduced by
1655 // an exported declaration; otherwise it shall not be exported.
1656 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1657   // [module.interface]p1:
1658   // An export-declaration shall inhabit a namespace scope.
1659   //
1660   // So it is meaningless to talk about redeclaration which is not at namespace
1661   // scope.
1662   if (!New->getLexicalDeclContext()
1663            ->getNonTransparentContext()
1664            ->isFileContext() ||
1665       !Old->getLexicalDeclContext()
1666            ->getNonTransparentContext()
1667            ->isFileContext())
1668     return false;
1669 
1670   bool IsNewExported = New->isInExportDeclContext();
1671   bool IsOldExported = Old->isInExportDeclContext();
1672 
1673   // It should be irrevelant if both of them are not exported.
1674   if (!IsNewExported && !IsOldExported)
1675     return false;
1676 
1677   if (IsOldExported)
1678     return false;
1679 
1680   assert(IsNewExported);
1681 
1682   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
1683   Diag(Old->getLocation(), diag::note_previous_declaration);
1684   return true;
1685 }
1686 
1687 // A wrapper function for checking the semantic restrictions of
1688 // a redeclaration within a module.
1689 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1690   if (CheckRedeclarationModuleOwnership(New, Old))
1691     return true;
1692 
1693   if (CheckRedeclarationExported(New, Old))
1694     return true;
1695 
1696   return false;
1697 }
1698 
1699 static bool isUsingDecl(NamedDecl *D) {
1700   return isa<UsingShadowDecl>(D) ||
1701          isa<UnresolvedUsingTypenameDecl>(D) ||
1702          isa<UnresolvedUsingValueDecl>(D);
1703 }
1704 
1705 /// Removes using shadow declarations from the lookup results.
1706 static void RemoveUsingDecls(LookupResult &R) {
1707   LookupResult::Filter F = R.makeFilter();
1708   while (F.hasNext())
1709     if (isUsingDecl(F.next()))
1710       F.erase();
1711 
1712   F.done();
1713 }
1714 
1715 /// Check for this common pattern:
1716 /// @code
1717 /// class S {
1718 ///   S(const S&); // DO NOT IMPLEMENT
1719 ///   void operator=(const S&); // DO NOT IMPLEMENT
1720 /// };
1721 /// @endcode
1722 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1723   // FIXME: Should check for private access too but access is set after we get
1724   // the decl here.
1725   if (D->doesThisDeclarationHaveABody())
1726     return false;
1727 
1728   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1729     return CD->isCopyConstructor();
1730   return D->isCopyAssignmentOperator();
1731 }
1732 
1733 // We need this to handle
1734 //
1735 // typedef struct {
1736 //   void *foo() { return 0; }
1737 // } A;
1738 //
1739 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1740 // for example. If 'A', foo will have external linkage. If we have '*A',
1741 // foo will have no linkage. Since we can't know until we get to the end
1742 // of the typedef, this function finds out if D might have non-external linkage.
1743 // Callers should verify at the end of the TU if it D has external linkage or
1744 // not.
1745 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1746   const DeclContext *DC = D->getDeclContext();
1747   while (!DC->isTranslationUnit()) {
1748     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1749       if (!RD->hasNameForLinkage())
1750         return true;
1751     }
1752     DC = DC->getParent();
1753   }
1754 
1755   return !D->isExternallyVisible();
1756 }
1757 
1758 // FIXME: This needs to be refactored; some other isInMainFile users want
1759 // these semantics.
1760 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1761   if (S.TUKind != TU_Complete)
1762     return false;
1763   return S.SourceMgr.isInMainFile(Loc);
1764 }
1765 
1766 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1767   assert(D);
1768 
1769   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1770     return false;
1771 
1772   // Ignore all entities declared within templates, and out-of-line definitions
1773   // of members of class templates.
1774   if (D->getDeclContext()->isDependentContext() ||
1775       D->getLexicalDeclContext()->isDependentContext())
1776     return false;
1777 
1778   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1779     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1780       return false;
1781     // A non-out-of-line declaration of a member specialization was implicitly
1782     // instantiated; it's the out-of-line declaration that we're interested in.
1783     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1784         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1785       return false;
1786 
1787     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1788       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1789         return false;
1790     } else {
1791       // 'static inline' functions are defined in headers; don't warn.
1792       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1793         return false;
1794     }
1795 
1796     if (FD->doesThisDeclarationHaveABody() &&
1797         Context.DeclMustBeEmitted(FD))
1798       return false;
1799   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     // Constants and utility variables are defined in headers with internal
1801     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1802     // like "inline".)
1803     if (!isMainFileLoc(*this, VD->getLocation()))
1804       return false;
1805 
1806     if (Context.DeclMustBeEmitted(VD))
1807       return false;
1808 
1809     if (VD->isStaticDataMember() &&
1810         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1811       return false;
1812     if (VD->isStaticDataMember() &&
1813         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1814         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1815       return false;
1816 
1817     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1818       return false;
1819   } else {
1820     return false;
1821   }
1822 
1823   // Only warn for unused decls internal to the translation unit.
1824   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1825   // for inline functions defined in the main source file, for instance.
1826   return mightHaveNonExternalLinkage(D);
1827 }
1828 
1829 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1830   if (!D)
1831     return;
1832 
1833   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1834     const FunctionDecl *First = FD->getFirstDecl();
1835     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1836       return; // First should already be in the vector.
1837   }
1838 
1839   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1840     const VarDecl *First = VD->getFirstDecl();
1841     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1842       return; // First should already be in the vector.
1843   }
1844 
1845   if (ShouldWarnIfUnusedFileScopedDecl(D))
1846     UnusedFileScopedDecls.push_back(D);
1847 }
1848 
1849 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1850   if (D->isInvalidDecl())
1851     return false;
1852 
1853   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1854     // For a decomposition declaration, warn if none of the bindings are
1855     // referenced, instead of if the variable itself is referenced (which
1856     // it is, by the bindings' expressions).
1857     for (auto *BD : DD->bindings())
1858       if (BD->isReferenced())
1859         return false;
1860   } else if (!D->getDeclName()) {
1861     return false;
1862   } else if (D->isReferenced() || D->isUsed()) {
1863     return false;
1864   }
1865 
1866   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1867     return false;
1868 
1869   if (isa<LabelDecl>(D))
1870     return true;
1871 
1872   // Except for labels, we only care about unused decls that are local to
1873   // functions.
1874   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1875   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1876     // For dependent types, the diagnostic is deferred.
1877     WithinFunction =
1878         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1879   if (!WithinFunction)
1880     return false;
1881 
1882   if (isa<TypedefNameDecl>(D))
1883     return true;
1884 
1885   // White-list anything that isn't a local variable.
1886   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1887     return false;
1888 
1889   // Types of valid local variables should be complete, so this should succeed.
1890   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1891 
1892     // White-list anything with an __attribute__((unused)) type.
1893     const auto *Ty = VD->getType().getTypePtr();
1894 
1895     // Only look at the outermost level of typedef.
1896     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1897       if (TT->getDecl()->hasAttr<UnusedAttr>())
1898         return false;
1899     }
1900 
1901     // If we failed to complete the type for some reason, or if the type is
1902     // dependent, don't diagnose the variable.
1903     if (Ty->isIncompleteType() || Ty->isDependentType())
1904       return false;
1905 
1906     // Look at the element type to ensure that the warning behaviour is
1907     // consistent for both scalars and arrays.
1908     Ty = Ty->getBaseElementTypeUnsafe();
1909 
1910     if (const TagType *TT = Ty->getAs<TagType>()) {
1911       const TagDecl *Tag = TT->getDecl();
1912       if (Tag->hasAttr<UnusedAttr>())
1913         return false;
1914 
1915       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1916         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1917           return false;
1918 
1919         if (const Expr *Init = VD->getInit()) {
1920           if (const ExprWithCleanups *Cleanups =
1921                   dyn_cast<ExprWithCleanups>(Init))
1922             Init = Cleanups->getSubExpr();
1923           const CXXConstructExpr *Construct =
1924             dyn_cast<CXXConstructExpr>(Init);
1925           if (Construct && !Construct->isElidable()) {
1926             CXXConstructorDecl *CD = Construct->getConstructor();
1927             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1928                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1929               return false;
1930           }
1931 
1932           // Suppress the warning if we don't know how this is constructed, and
1933           // it could possibly be non-trivial constructor.
1934           if (Init->isTypeDependent())
1935             for (const CXXConstructorDecl *Ctor : RD->ctors())
1936               if (!Ctor->isTrivial())
1937                 return false;
1938         }
1939       }
1940     }
1941 
1942     // TODO: __attribute__((unused)) templates?
1943   }
1944 
1945   return true;
1946 }
1947 
1948 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1949                                      FixItHint &Hint) {
1950   if (isa<LabelDecl>(D)) {
1951     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1952         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1953         true);
1954     if (AfterColon.isInvalid())
1955       return;
1956     Hint = FixItHint::CreateRemoval(
1957         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1958   }
1959 }
1960 
1961 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1962   if (D->getTypeForDecl()->isDependentType())
1963     return;
1964 
1965   for (auto *TmpD : D->decls()) {
1966     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1967       DiagnoseUnusedDecl(T);
1968     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1969       DiagnoseUnusedNestedTypedefs(R);
1970   }
1971 }
1972 
1973 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1974 /// unless they are marked attr(unused).
1975 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1976   if (!ShouldDiagnoseUnusedDecl(D))
1977     return;
1978 
1979   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1980     // typedefs can be referenced later on, so the diagnostics are emitted
1981     // at end-of-translation-unit.
1982     UnusedLocalTypedefNameCandidates.insert(TD);
1983     return;
1984   }
1985 
1986   FixItHint Hint;
1987   GenerateFixForUnusedDecl(D, Context, Hint);
1988 
1989   unsigned DiagID;
1990   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1991     DiagID = diag::warn_unused_exception_param;
1992   else if (isa<LabelDecl>(D))
1993     DiagID = diag::warn_unused_label;
1994   else
1995     DiagID = diag::warn_unused_variable;
1996 
1997   Diag(D->getLocation(), DiagID) << D << Hint;
1998 }
1999 
2000 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2001   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2002   // it's not really unused.
2003   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2004       VD->hasAttr<CleanupAttr>())
2005     return;
2006 
2007   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2008 
2009   if (Ty->isReferenceType() || Ty->isDependentType())
2010     return;
2011 
2012   if (const TagType *TT = Ty->getAs<TagType>()) {
2013     const TagDecl *Tag = TT->getDecl();
2014     if (Tag->hasAttr<UnusedAttr>())
2015       return;
2016     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2017     // mimic gcc's behavior.
2018     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2019       if (!RD->hasAttr<WarnUnusedAttr>())
2020         return;
2021     }
2022   }
2023 
2024   // Don't warn about __block Objective-C pointer variables, as they might
2025   // be assigned in the block but not used elsewhere for the purpose of lifetime
2026   // extension.
2027   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2028     return;
2029 
2030   // Don't warn about Objective-C pointer variables with precise lifetime
2031   // semantics; they can be used to ensure ARC releases the object at a known
2032   // time, which may mean assignment but no other references.
2033   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2034     return;
2035 
2036   auto iter = RefsMinusAssignments.find(VD);
2037   if (iter == RefsMinusAssignments.end())
2038     return;
2039 
2040   assert(iter->getSecond() >= 0 &&
2041          "Found a negative number of references to a VarDecl");
2042   if (iter->getSecond() != 0)
2043     return;
2044   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2045                                          : diag::warn_unused_but_set_variable;
2046   Diag(VD->getLocation(), DiagID) << VD;
2047 }
2048 
2049 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2050   // Verify that we have no forward references left.  If so, there was a goto
2051   // or address of a label taken, but no definition of it.  Label fwd
2052   // definitions are indicated with a null substmt which is also not a resolved
2053   // MS inline assembly label name.
2054   bool Diagnose = false;
2055   if (L->isMSAsmLabel())
2056     Diagnose = !L->isResolvedMSAsmLabel();
2057   else
2058     Diagnose = L->getStmt() == nullptr;
2059   if (Diagnose)
2060     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2061 }
2062 
2063 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2064   S->mergeNRVOIntoParent();
2065 
2066   if (S->decl_empty()) return;
2067   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2068          "Scope shouldn't contain decls!");
2069 
2070   for (auto *TmpD : S->decls()) {
2071     assert(TmpD && "This decl didn't get pushed??");
2072 
2073     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2074     NamedDecl *D = cast<NamedDecl>(TmpD);
2075 
2076     // Diagnose unused variables in this scope.
2077     if (!S->hasUnrecoverableErrorOccurred()) {
2078       DiagnoseUnusedDecl(D);
2079       if (const auto *RD = dyn_cast<RecordDecl>(D))
2080         DiagnoseUnusedNestedTypedefs(RD);
2081       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2082         DiagnoseUnusedButSetDecl(VD);
2083         RefsMinusAssignments.erase(VD);
2084       }
2085     }
2086 
2087     if (!D->getDeclName()) continue;
2088 
2089     // If this was a forward reference to a label, verify it was defined.
2090     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2091       CheckPoppedLabel(LD, *this);
2092 
2093     // Remove this name from our lexical scope, and warn on it if we haven't
2094     // already.
2095     IdResolver.RemoveDecl(D);
2096     auto ShadowI = ShadowingDecls.find(D);
2097     if (ShadowI != ShadowingDecls.end()) {
2098       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2099         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2100             << D << FD << FD->getParent();
2101         Diag(FD->getLocation(), diag::note_previous_declaration);
2102       }
2103       ShadowingDecls.erase(ShadowI);
2104     }
2105   }
2106 }
2107 
2108 /// Look for an Objective-C class in the translation unit.
2109 ///
2110 /// \param Id The name of the Objective-C class we're looking for. If
2111 /// typo-correction fixes this name, the Id will be updated
2112 /// to the fixed name.
2113 ///
2114 /// \param IdLoc The location of the name in the translation unit.
2115 ///
2116 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2117 /// if there is no class with the given name.
2118 ///
2119 /// \returns The declaration of the named Objective-C class, or NULL if the
2120 /// class could not be found.
2121 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2122                                               SourceLocation IdLoc,
2123                                               bool DoTypoCorrection) {
2124   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2125   // creation from this context.
2126   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2127 
2128   if (!IDecl && DoTypoCorrection) {
2129     // Perform typo correction at the given location, but only if we
2130     // find an Objective-C class name.
2131     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2132     if (TypoCorrection C =
2133             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2134                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2135       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2136       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2137       Id = IDecl->getIdentifier();
2138     }
2139   }
2140   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2141   // This routine must always return a class definition, if any.
2142   if (Def && Def->getDefinition())
2143       Def = Def->getDefinition();
2144   return Def;
2145 }
2146 
2147 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2148 /// from S, where a non-field would be declared. This routine copes
2149 /// with the difference between C and C++ scoping rules in structs and
2150 /// unions. For example, the following code is well-formed in C but
2151 /// ill-formed in C++:
2152 /// @code
2153 /// struct S6 {
2154 ///   enum { BAR } e;
2155 /// };
2156 ///
2157 /// void test_S6() {
2158 ///   struct S6 a;
2159 ///   a.e = BAR;
2160 /// }
2161 /// @endcode
2162 /// For the declaration of BAR, this routine will return a different
2163 /// scope. The scope S will be the scope of the unnamed enumeration
2164 /// within S6. In C++, this routine will return the scope associated
2165 /// with S6, because the enumeration's scope is a transparent
2166 /// context but structures can contain non-field names. In C, this
2167 /// routine will return the translation unit scope, since the
2168 /// enumeration's scope is a transparent context and structures cannot
2169 /// contain non-field names.
2170 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2171   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2172          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2173          (S->isClassScope() && !getLangOpts().CPlusPlus))
2174     S = S->getParent();
2175   return S;
2176 }
2177 
2178 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2179                                ASTContext::GetBuiltinTypeError Error) {
2180   switch (Error) {
2181   case ASTContext::GE_None:
2182     return "";
2183   case ASTContext::GE_Missing_type:
2184     return BuiltinInfo.getHeaderName(ID);
2185   case ASTContext::GE_Missing_stdio:
2186     return "stdio.h";
2187   case ASTContext::GE_Missing_setjmp:
2188     return "setjmp.h";
2189   case ASTContext::GE_Missing_ucontext:
2190     return "ucontext.h";
2191   }
2192   llvm_unreachable("unhandled error kind");
2193 }
2194 
2195 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2196                                   unsigned ID, SourceLocation Loc) {
2197   DeclContext *Parent = Context.getTranslationUnitDecl();
2198 
2199   if (getLangOpts().CPlusPlus) {
2200     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2201         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2202     CLinkageDecl->setImplicit();
2203     Parent->addDecl(CLinkageDecl);
2204     Parent = CLinkageDecl;
2205   }
2206 
2207   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2208                                            /*TInfo=*/nullptr, SC_Extern,
2209                                            getCurFPFeatures().isFPConstrained(),
2210                                            false, Type->isFunctionProtoType());
2211   New->setImplicit();
2212   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2213 
2214   // Create Decl objects for each parameter, adding them to the
2215   // FunctionDecl.
2216   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2217     SmallVector<ParmVarDecl *, 16> Params;
2218     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2219       ParmVarDecl *parm = ParmVarDecl::Create(
2220           Context, New, SourceLocation(), SourceLocation(), nullptr,
2221           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2222       parm->setScopeInfo(0, i);
2223       Params.push_back(parm);
2224     }
2225     New->setParams(Params);
2226   }
2227 
2228   AddKnownFunctionAttributes(New);
2229   return New;
2230 }
2231 
2232 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2233 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2234 /// if we're creating this built-in in anticipation of redeclaring the
2235 /// built-in.
2236 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2237                                      Scope *S, bool ForRedeclaration,
2238                                      SourceLocation Loc) {
2239   LookupNecessaryTypesForBuiltin(S, ID);
2240 
2241   ASTContext::GetBuiltinTypeError Error;
2242   QualType R = Context.GetBuiltinType(ID, Error);
2243   if (Error) {
2244     if (!ForRedeclaration)
2245       return nullptr;
2246 
2247     // If we have a builtin without an associated type we should not emit a
2248     // warning when we were not able to find a type for it.
2249     if (Error == ASTContext::GE_Missing_type ||
2250         Context.BuiltinInfo.allowTypeMismatch(ID))
2251       return nullptr;
2252 
2253     // If we could not find a type for setjmp it is because the jmp_buf type was
2254     // not defined prior to the setjmp declaration.
2255     if (Error == ASTContext::GE_Missing_setjmp) {
2256       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2257           << Context.BuiltinInfo.getName(ID);
2258       return nullptr;
2259     }
2260 
2261     // Generally, we emit a warning that the declaration requires the
2262     // appropriate header.
2263     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2264         << getHeaderName(Context.BuiltinInfo, ID, Error)
2265         << Context.BuiltinInfo.getName(ID);
2266     return nullptr;
2267   }
2268 
2269   if (!ForRedeclaration &&
2270       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2271        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2272     Diag(Loc, diag::ext_implicit_lib_function_decl)
2273         << Context.BuiltinInfo.getName(ID) << R;
2274     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2275       Diag(Loc, diag::note_include_header_or_declare)
2276           << Header << Context.BuiltinInfo.getName(ID);
2277   }
2278 
2279   if (R.isNull())
2280     return nullptr;
2281 
2282   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2283   RegisterLocallyScopedExternCDecl(New, S);
2284 
2285   // TUScope is the translation-unit scope to insert this function into.
2286   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2287   // relate Scopes to DeclContexts, and probably eliminate CurContext
2288   // entirely, but we're not there yet.
2289   DeclContext *SavedContext = CurContext;
2290   CurContext = New->getDeclContext();
2291   PushOnScopeChains(New, TUScope);
2292   CurContext = SavedContext;
2293   return New;
2294 }
2295 
2296 /// Typedef declarations don't have linkage, but they still denote the same
2297 /// entity if their types are the same.
2298 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2299 /// isSameEntity.
2300 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2301                                                      TypedefNameDecl *Decl,
2302                                                      LookupResult &Previous) {
2303   // This is only interesting when modules are enabled.
2304   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2305     return;
2306 
2307   // Empty sets are uninteresting.
2308   if (Previous.empty())
2309     return;
2310 
2311   LookupResult::Filter Filter = Previous.makeFilter();
2312   while (Filter.hasNext()) {
2313     NamedDecl *Old = Filter.next();
2314 
2315     // Non-hidden declarations are never ignored.
2316     if (S.isVisible(Old))
2317       continue;
2318 
2319     // Declarations of the same entity are not ignored, even if they have
2320     // different linkages.
2321     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2322       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2323                                 Decl->getUnderlyingType()))
2324         continue;
2325 
2326       // If both declarations give a tag declaration a typedef name for linkage
2327       // purposes, then they declare the same entity.
2328       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2329           Decl->getAnonDeclWithTypedefName())
2330         continue;
2331     }
2332 
2333     Filter.erase();
2334   }
2335 
2336   Filter.done();
2337 }
2338 
2339 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2340   QualType OldType;
2341   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2342     OldType = OldTypedef->getUnderlyingType();
2343   else
2344     OldType = Context.getTypeDeclType(Old);
2345   QualType NewType = New->getUnderlyingType();
2346 
2347   if (NewType->isVariablyModifiedType()) {
2348     // Must not redefine a typedef with a variably-modified type.
2349     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2350     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2351       << Kind << NewType;
2352     if (Old->getLocation().isValid())
2353       notePreviousDefinition(Old, New->getLocation());
2354     New->setInvalidDecl();
2355     return true;
2356   }
2357 
2358   if (OldType != NewType &&
2359       !OldType->isDependentType() &&
2360       !NewType->isDependentType() &&
2361       !Context.hasSameType(OldType, NewType)) {
2362     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2363     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2364       << Kind << NewType << OldType;
2365     if (Old->getLocation().isValid())
2366       notePreviousDefinition(Old, New->getLocation());
2367     New->setInvalidDecl();
2368     return true;
2369   }
2370   return false;
2371 }
2372 
2373 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2374 /// same name and scope as a previous declaration 'Old'.  Figure out
2375 /// how to resolve this situation, merging decls or emitting
2376 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2377 ///
2378 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2379                                 LookupResult &OldDecls) {
2380   // If the new decl is known invalid already, don't bother doing any
2381   // merging checks.
2382   if (New->isInvalidDecl()) return;
2383 
2384   // Allow multiple definitions for ObjC built-in typedefs.
2385   // FIXME: Verify the underlying types are equivalent!
2386   if (getLangOpts().ObjC) {
2387     const IdentifierInfo *TypeID = New->getIdentifier();
2388     switch (TypeID->getLength()) {
2389     default: break;
2390     case 2:
2391       {
2392         if (!TypeID->isStr("id"))
2393           break;
2394         QualType T = New->getUnderlyingType();
2395         if (!T->isPointerType())
2396           break;
2397         if (!T->isVoidPointerType()) {
2398           QualType PT = T->castAs<PointerType>()->getPointeeType();
2399           if (!PT->isStructureType())
2400             break;
2401         }
2402         Context.setObjCIdRedefinitionType(T);
2403         // Install the built-in type for 'id', ignoring the current definition.
2404         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2405         return;
2406       }
2407     case 5:
2408       if (!TypeID->isStr("Class"))
2409         break;
2410       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2411       // Install the built-in type for 'Class', ignoring the current definition.
2412       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2413       return;
2414     case 3:
2415       if (!TypeID->isStr("SEL"))
2416         break;
2417       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2418       // Install the built-in type for 'SEL', ignoring the current definition.
2419       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2420       return;
2421     }
2422     // Fall through - the typedef name was not a builtin type.
2423   }
2424 
2425   // Verify the old decl was also a type.
2426   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2427   if (!Old) {
2428     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2429       << New->getDeclName();
2430 
2431     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2432     if (OldD->getLocation().isValid())
2433       notePreviousDefinition(OldD, New->getLocation());
2434 
2435     return New->setInvalidDecl();
2436   }
2437 
2438   // If the old declaration is invalid, just give up here.
2439   if (Old->isInvalidDecl())
2440     return New->setInvalidDecl();
2441 
2442   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2443     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2444     auto *NewTag = New->getAnonDeclWithTypedefName();
2445     NamedDecl *Hidden = nullptr;
2446     if (OldTag && NewTag &&
2447         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2448         !hasVisibleDefinition(OldTag, &Hidden)) {
2449       // There is a definition of this tag, but it is not visible. Use it
2450       // instead of our tag.
2451       New->setTypeForDecl(OldTD->getTypeForDecl());
2452       if (OldTD->isModed())
2453         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2454                                     OldTD->getUnderlyingType());
2455       else
2456         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2457 
2458       // Make the old tag definition visible.
2459       makeMergedDefinitionVisible(Hidden);
2460 
2461       // If this was an unscoped enumeration, yank all of its enumerators
2462       // out of the scope.
2463       if (isa<EnumDecl>(NewTag)) {
2464         Scope *EnumScope = getNonFieldDeclScope(S);
2465         for (auto *D : NewTag->decls()) {
2466           auto *ED = cast<EnumConstantDecl>(D);
2467           assert(EnumScope->isDeclScope(ED));
2468           EnumScope->RemoveDecl(ED);
2469           IdResolver.RemoveDecl(ED);
2470           ED->getLexicalDeclContext()->removeDecl(ED);
2471         }
2472       }
2473     }
2474   }
2475 
2476   // If the typedef types are not identical, reject them in all languages and
2477   // with any extensions enabled.
2478   if (isIncompatibleTypedef(Old, New))
2479     return;
2480 
2481   // The types match.  Link up the redeclaration chain and merge attributes if
2482   // the old declaration was a typedef.
2483   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2484     New->setPreviousDecl(Typedef);
2485     mergeDeclAttributes(New, Old);
2486   }
2487 
2488   if (getLangOpts().MicrosoftExt)
2489     return;
2490 
2491   if (getLangOpts().CPlusPlus) {
2492     // C++ [dcl.typedef]p2:
2493     //   In a given non-class scope, a typedef specifier can be used to
2494     //   redefine the name of any type declared in that scope to refer
2495     //   to the type to which it already refers.
2496     if (!isa<CXXRecordDecl>(CurContext))
2497       return;
2498 
2499     // C++0x [dcl.typedef]p4:
2500     //   In a given class scope, a typedef specifier can be used to redefine
2501     //   any class-name declared in that scope that is not also a typedef-name
2502     //   to refer to the type to which it already refers.
2503     //
2504     // This wording came in via DR424, which was a correction to the
2505     // wording in DR56, which accidentally banned code like:
2506     //
2507     //   struct S {
2508     //     typedef struct A { } A;
2509     //   };
2510     //
2511     // in the C++03 standard. We implement the C++0x semantics, which
2512     // allow the above but disallow
2513     //
2514     //   struct S {
2515     //     typedef int I;
2516     //     typedef int I;
2517     //   };
2518     //
2519     // since that was the intent of DR56.
2520     if (!isa<TypedefNameDecl>(Old))
2521       return;
2522 
2523     Diag(New->getLocation(), diag::err_redefinition)
2524       << New->getDeclName();
2525     notePreviousDefinition(Old, New->getLocation());
2526     return New->setInvalidDecl();
2527   }
2528 
2529   // Modules always permit redefinition of typedefs, as does C11.
2530   if (getLangOpts().Modules || getLangOpts().C11)
2531     return;
2532 
2533   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2534   // is normally mapped to an error, but can be controlled with
2535   // -Wtypedef-redefinition.  If either the original or the redefinition is
2536   // in a system header, don't emit this for compatibility with GCC.
2537   if (getDiagnostics().getSuppressSystemWarnings() &&
2538       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2539       (Old->isImplicit() ||
2540        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2541        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2542     return;
2543 
2544   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2545     << New->getDeclName();
2546   notePreviousDefinition(Old, New->getLocation());
2547 }
2548 
2549 /// DeclhasAttr - returns true if decl Declaration already has the target
2550 /// attribute.
2551 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2552   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2553   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2554   for (const auto *i : D->attrs())
2555     if (i->getKind() == A->getKind()) {
2556       if (Ann) {
2557         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2558           return true;
2559         continue;
2560       }
2561       // FIXME: Don't hardcode this check
2562       if (OA && isa<OwnershipAttr>(i))
2563         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2564       return true;
2565     }
2566 
2567   return false;
2568 }
2569 
2570 static bool isAttributeTargetADefinition(Decl *D) {
2571   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2572     return VD->isThisDeclarationADefinition();
2573   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2574     return TD->isCompleteDefinition() || TD->isBeingDefined();
2575   return true;
2576 }
2577 
2578 /// Merge alignment attributes from \p Old to \p New, taking into account the
2579 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2580 ///
2581 /// \return \c true if any attributes were added to \p New.
2582 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2583   // Look for alignas attributes on Old, and pick out whichever attribute
2584   // specifies the strictest alignment requirement.
2585   AlignedAttr *OldAlignasAttr = nullptr;
2586   AlignedAttr *OldStrictestAlignAttr = nullptr;
2587   unsigned OldAlign = 0;
2588   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2589     // FIXME: We have no way of representing inherited dependent alignments
2590     // in a case like:
2591     //   template<int A, int B> struct alignas(A) X;
2592     //   template<int A, int B> struct alignas(B) X {};
2593     // For now, we just ignore any alignas attributes which are not on the
2594     // definition in such a case.
2595     if (I->isAlignmentDependent())
2596       return false;
2597 
2598     if (I->isAlignas())
2599       OldAlignasAttr = I;
2600 
2601     unsigned Align = I->getAlignment(S.Context);
2602     if (Align > OldAlign) {
2603       OldAlign = Align;
2604       OldStrictestAlignAttr = I;
2605     }
2606   }
2607 
2608   // Look for alignas attributes on New.
2609   AlignedAttr *NewAlignasAttr = nullptr;
2610   unsigned NewAlign = 0;
2611   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2612     if (I->isAlignmentDependent())
2613       return false;
2614 
2615     if (I->isAlignas())
2616       NewAlignasAttr = I;
2617 
2618     unsigned Align = I->getAlignment(S.Context);
2619     if (Align > NewAlign)
2620       NewAlign = Align;
2621   }
2622 
2623   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2624     // Both declarations have 'alignas' attributes. We require them to match.
2625     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2626     // fall short. (If two declarations both have alignas, they must both match
2627     // every definition, and so must match each other if there is a definition.)
2628 
2629     // If either declaration only contains 'alignas(0)' specifiers, then it
2630     // specifies the natural alignment for the type.
2631     if (OldAlign == 0 || NewAlign == 0) {
2632       QualType Ty;
2633       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2634         Ty = VD->getType();
2635       else
2636         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2637 
2638       if (OldAlign == 0)
2639         OldAlign = S.Context.getTypeAlign(Ty);
2640       if (NewAlign == 0)
2641         NewAlign = S.Context.getTypeAlign(Ty);
2642     }
2643 
2644     if (OldAlign != NewAlign) {
2645       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2646         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2647         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2648       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2649     }
2650   }
2651 
2652   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2653     // C++11 [dcl.align]p6:
2654     //   if any declaration of an entity has an alignment-specifier,
2655     //   every defining declaration of that entity shall specify an
2656     //   equivalent alignment.
2657     // C11 6.7.5/7:
2658     //   If the definition of an object does not have an alignment
2659     //   specifier, any other declaration of that object shall also
2660     //   have no alignment specifier.
2661     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2662       << OldAlignasAttr;
2663     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2664       << OldAlignasAttr;
2665   }
2666 
2667   bool AnyAdded = false;
2668 
2669   // Ensure we have an attribute representing the strictest alignment.
2670   if (OldAlign > NewAlign) {
2671     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2672     Clone->setInherited(true);
2673     New->addAttr(Clone);
2674     AnyAdded = true;
2675   }
2676 
2677   // Ensure we have an alignas attribute if the old declaration had one.
2678   if (OldAlignasAttr && !NewAlignasAttr &&
2679       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2680     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2681     Clone->setInherited(true);
2682     New->addAttr(Clone);
2683     AnyAdded = true;
2684   }
2685 
2686   return AnyAdded;
2687 }
2688 
2689 #define WANT_DECL_MERGE_LOGIC
2690 #include "clang/Sema/AttrParsedAttrImpl.inc"
2691 #undef WANT_DECL_MERGE_LOGIC
2692 
2693 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2694                                const InheritableAttr *Attr,
2695                                Sema::AvailabilityMergeKind AMK) {
2696   // Diagnose any mutual exclusions between the attribute that we want to add
2697   // and attributes that already exist on the declaration.
2698   if (!DiagnoseMutualExclusions(S, D, Attr))
2699     return false;
2700 
2701   // This function copies an attribute Attr from a previous declaration to the
2702   // new declaration D if the new declaration doesn't itself have that attribute
2703   // yet or if that attribute allows duplicates.
2704   // If you're adding a new attribute that requires logic different from
2705   // "use explicit attribute on decl if present, else use attribute from
2706   // previous decl", for example if the attribute needs to be consistent
2707   // between redeclarations, you need to call a custom merge function here.
2708   InheritableAttr *NewAttr = nullptr;
2709   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2710     NewAttr = S.mergeAvailabilityAttr(
2711         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2712         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2713         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2714         AA->getPriority());
2715   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2716     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2717   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2718     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2719   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2720     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2721   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2722     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2723   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2724     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2725   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2726     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2727                                 FA->getFirstArg());
2728   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2729     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2730   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2731     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2732   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2733     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2734                                        IA->getInheritanceModel());
2735   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2736     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2737                                       &S.Context.Idents.get(AA->getSpelling()));
2738   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2739            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2740             isa<CUDAGlobalAttr>(Attr))) {
2741     // CUDA target attributes are part of function signature for
2742     // overloading purposes and must not be merged.
2743     return false;
2744   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2745     NewAttr = S.mergeMinSizeAttr(D, *MA);
2746   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2747     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2748   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2749     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2750   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2751     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2752   else if (isa<AlignedAttr>(Attr))
2753     // AlignedAttrs are handled separately, because we need to handle all
2754     // such attributes on a declaration at the same time.
2755     NewAttr = nullptr;
2756   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2757            (AMK == Sema::AMK_Override ||
2758             AMK == Sema::AMK_ProtocolImplementation ||
2759             AMK == Sema::AMK_OptionalProtocolImplementation))
2760     NewAttr = nullptr;
2761   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2762     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2763   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2764     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2765   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2766     NewAttr = S.mergeImportNameAttr(D, *INA);
2767   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2768     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2769   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2770     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2771   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2772     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2773   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2774     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2775 
2776   if (NewAttr) {
2777     NewAttr->setInherited(true);
2778     D->addAttr(NewAttr);
2779     if (isa<MSInheritanceAttr>(NewAttr))
2780       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2781     return true;
2782   }
2783 
2784   return false;
2785 }
2786 
2787 static const NamedDecl *getDefinition(const Decl *D) {
2788   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2789     return TD->getDefinition();
2790   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2791     const VarDecl *Def = VD->getDefinition();
2792     if (Def)
2793       return Def;
2794     return VD->getActingDefinition();
2795   }
2796   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2797     const FunctionDecl *Def = nullptr;
2798     if (FD->isDefined(Def, true))
2799       return Def;
2800   }
2801   return nullptr;
2802 }
2803 
2804 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2805   for (const auto *Attribute : D->attrs())
2806     if (Attribute->getKind() == Kind)
2807       return true;
2808   return false;
2809 }
2810 
2811 /// checkNewAttributesAfterDef - If we already have a definition, check that
2812 /// there are no new attributes in this declaration.
2813 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2814   if (!New->hasAttrs())
2815     return;
2816 
2817   const NamedDecl *Def = getDefinition(Old);
2818   if (!Def || Def == New)
2819     return;
2820 
2821   AttrVec &NewAttributes = New->getAttrs();
2822   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2823     const Attr *NewAttribute = NewAttributes[I];
2824 
2825     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2826       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2827         Sema::SkipBodyInfo SkipBody;
2828         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2829 
2830         // If we're skipping this definition, drop the "alias" attribute.
2831         if (SkipBody.ShouldSkip) {
2832           NewAttributes.erase(NewAttributes.begin() + I);
2833           --E;
2834           continue;
2835         }
2836       } else {
2837         VarDecl *VD = cast<VarDecl>(New);
2838         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2839                                 VarDecl::TentativeDefinition
2840                             ? diag::err_alias_after_tentative
2841                             : diag::err_redefinition;
2842         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2843         if (Diag == diag::err_redefinition)
2844           S.notePreviousDefinition(Def, VD->getLocation());
2845         else
2846           S.Diag(Def->getLocation(), diag::note_previous_definition);
2847         VD->setInvalidDecl();
2848       }
2849       ++I;
2850       continue;
2851     }
2852 
2853     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2854       // Tentative definitions are only interesting for the alias check above.
2855       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2856         ++I;
2857         continue;
2858       }
2859     }
2860 
2861     if (hasAttribute(Def, NewAttribute->getKind())) {
2862       ++I;
2863       continue; // regular attr merging will take care of validating this.
2864     }
2865 
2866     if (isa<C11NoReturnAttr>(NewAttribute)) {
2867       // C's _Noreturn is allowed to be added to a function after it is defined.
2868       ++I;
2869       continue;
2870     } else if (isa<UuidAttr>(NewAttribute)) {
2871       // msvc will allow a subsequent definition to add an uuid to a class
2872       ++I;
2873       continue;
2874     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2875       if (AA->isAlignas()) {
2876         // C++11 [dcl.align]p6:
2877         //   if any declaration of an entity has an alignment-specifier,
2878         //   every defining declaration of that entity shall specify an
2879         //   equivalent alignment.
2880         // C11 6.7.5/7:
2881         //   If the definition of an object does not have an alignment
2882         //   specifier, any other declaration of that object shall also
2883         //   have no alignment specifier.
2884         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2885           << AA;
2886         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2887           << AA;
2888         NewAttributes.erase(NewAttributes.begin() + I);
2889         --E;
2890         continue;
2891       }
2892     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2893       // If there is a C definition followed by a redeclaration with this
2894       // attribute then there are two different definitions. In C++, prefer the
2895       // standard diagnostics.
2896       if (!S.getLangOpts().CPlusPlus) {
2897         S.Diag(NewAttribute->getLocation(),
2898                diag::err_loader_uninitialized_redeclaration);
2899         S.Diag(Def->getLocation(), diag::note_previous_definition);
2900         NewAttributes.erase(NewAttributes.begin() + I);
2901         --E;
2902         continue;
2903       }
2904     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2905                cast<VarDecl>(New)->isInline() &&
2906                !cast<VarDecl>(New)->isInlineSpecified()) {
2907       // Don't warn about applying selectany to implicitly inline variables.
2908       // Older compilers and language modes would require the use of selectany
2909       // to make such variables inline, and it would have no effect if we
2910       // honored it.
2911       ++I;
2912       continue;
2913     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2914       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2915       // declarations after defintions.
2916       ++I;
2917       continue;
2918     }
2919 
2920     S.Diag(NewAttribute->getLocation(),
2921            diag::warn_attribute_precede_definition);
2922     S.Diag(Def->getLocation(), diag::note_previous_definition);
2923     NewAttributes.erase(NewAttributes.begin() + I);
2924     --E;
2925   }
2926 }
2927 
2928 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2929                                      const ConstInitAttr *CIAttr,
2930                                      bool AttrBeforeInit) {
2931   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2932 
2933   // Figure out a good way to write this specifier on the old declaration.
2934   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2935   // enough of the attribute list spelling information to extract that without
2936   // heroics.
2937   std::string SuitableSpelling;
2938   if (S.getLangOpts().CPlusPlus20)
2939     SuitableSpelling = std::string(
2940         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2941   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2942     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2943         InsertLoc, {tok::l_square, tok::l_square,
2944                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2945                     S.PP.getIdentifierInfo("require_constant_initialization"),
2946                     tok::r_square, tok::r_square}));
2947   if (SuitableSpelling.empty())
2948     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2949         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2950                     S.PP.getIdentifierInfo("require_constant_initialization"),
2951                     tok::r_paren, tok::r_paren}));
2952   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2953     SuitableSpelling = "constinit";
2954   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2955     SuitableSpelling = "[[clang::require_constant_initialization]]";
2956   if (SuitableSpelling.empty())
2957     SuitableSpelling = "__attribute__((require_constant_initialization))";
2958   SuitableSpelling += " ";
2959 
2960   if (AttrBeforeInit) {
2961     // extern constinit int a;
2962     // int a = 0; // error (missing 'constinit'), accepted as extension
2963     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2964     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2965         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2966     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2967   } else {
2968     // int a = 0;
2969     // constinit extern int a; // error (missing 'constinit')
2970     S.Diag(CIAttr->getLocation(),
2971            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2972                                  : diag::warn_require_const_init_added_too_late)
2973         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2974     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2975         << CIAttr->isConstinit()
2976         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2977   }
2978 }
2979 
2980 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2981 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2982                                AvailabilityMergeKind AMK) {
2983   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2984     UsedAttr *NewAttr = OldAttr->clone(Context);
2985     NewAttr->setInherited(true);
2986     New->addAttr(NewAttr);
2987   }
2988   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2989     RetainAttr *NewAttr = OldAttr->clone(Context);
2990     NewAttr->setInherited(true);
2991     New->addAttr(NewAttr);
2992   }
2993 
2994   if (!Old->hasAttrs() && !New->hasAttrs())
2995     return;
2996 
2997   // [dcl.constinit]p1:
2998   //   If the [constinit] specifier is applied to any declaration of a
2999   //   variable, it shall be applied to the initializing declaration.
3000   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3001   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3002   if (bool(OldConstInit) != bool(NewConstInit)) {
3003     const auto *OldVD = cast<VarDecl>(Old);
3004     auto *NewVD = cast<VarDecl>(New);
3005 
3006     // Find the initializing declaration. Note that we might not have linked
3007     // the new declaration into the redeclaration chain yet.
3008     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3009     if (!InitDecl &&
3010         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3011       InitDecl = NewVD;
3012 
3013     if (InitDecl == NewVD) {
3014       // This is the initializing declaration. If it would inherit 'constinit',
3015       // that's ill-formed. (Note that we do not apply this to the attribute
3016       // form).
3017       if (OldConstInit && OldConstInit->isConstinit())
3018         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3019                                  /*AttrBeforeInit=*/true);
3020     } else if (NewConstInit) {
3021       // This is the first time we've been told that this declaration should
3022       // have a constant initializer. If we already saw the initializing
3023       // declaration, this is too late.
3024       if (InitDecl && InitDecl != NewVD) {
3025         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3026                                  /*AttrBeforeInit=*/false);
3027         NewVD->dropAttr<ConstInitAttr>();
3028       }
3029     }
3030   }
3031 
3032   // Attributes declared post-definition are currently ignored.
3033   checkNewAttributesAfterDef(*this, New, Old);
3034 
3035   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3036     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3037       if (!OldA->isEquivalent(NewA)) {
3038         // This redeclaration changes __asm__ label.
3039         Diag(New->getLocation(), diag::err_different_asm_label);
3040         Diag(OldA->getLocation(), diag::note_previous_declaration);
3041       }
3042     } else if (Old->isUsed()) {
3043       // This redeclaration adds an __asm__ label to a declaration that has
3044       // already been ODR-used.
3045       Diag(New->getLocation(), diag::err_late_asm_label_name)
3046         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3047     }
3048   }
3049 
3050   // Re-declaration cannot add abi_tag's.
3051   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3052     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3053       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3054         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3055           Diag(NewAbiTagAttr->getLocation(),
3056                diag::err_new_abi_tag_on_redeclaration)
3057               << NewTag;
3058           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3059         }
3060       }
3061     } else {
3062       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3063       Diag(Old->getLocation(), diag::note_previous_declaration);
3064     }
3065   }
3066 
3067   // This redeclaration adds a section attribute.
3068   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3069     if (auto *VD = dyn_cast<VarDecl>(New)) {
3070       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3071         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3072         Diag(Old->getLocation(), diag::note_previous_declaration);
3073       }
3074     }
3075   }
3076 
3077   // Redeclaration adds code-seg attribute.
3078   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3079   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3080       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3081     Diag(New->getLocation(), diag::warn_mismatched_section)
3082          << 0 /*codeseg*/;
3083     Diag(Old->getLocation(), diag::note_previous_declaration);
3084   }
3085 
3086   if (!Old->hasAttrs())
3087     return;
3088 
3089   bool foundAny = New->hasAttrs();
3090 
3091   // Ensure that any moving of objects within the allocated map is done before
3092   // we process them.
3093   if (!foundAny) New->setAttrs(AttrVec());
3094 
3095   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3096     // Ignore deprecated/unavailable/availability attributes if requested.
3097     AvailabilityMergeKind LocalAMK = AMK_None;
3098     if (isa<DeprecatedAttr>(I) ||
3099         isa<UnavailableAttr>(I) ||
3100         isa<AvailabilityAttr>(I)) {
3101       switch (AMK) {
3102       case AMK_None:
3103         continue;
3104 
3105       case AMK_Redeclaration:
3106       case AMK_Override:
3107       case AMK_ProtocolImplementation:
3108       case AMK_OptionalProtocolImplementation:
3109         LocalAMK = AMK;
3110         break;
3111       }
3112     }
3113 
3114     // Already handled.
3115     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3116       continue;
3117 
3118     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3119       foundAny = true;
3120   }
3121 
3122   if (mergeAlignedAttrs(*this, New, Old))
3123     foundAny = true;
3124 
3125   if (!foundAny) New->dropAttrs();
3126 }
3127 
3128 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3129 /// to the new one.
3130 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3131                                      const ParmVarDecl *oldDecl,
3132                                      Sema &S) {
3133   // C++11 [dcl.attr.depend]p2:
3134   //   The first declaration of a function shall specify the
3135   //   carries_dependency attribute for its declarator-id if any declaration
3136   //   of the function specifies the carries_dependency attribute.
3137   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3138   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3139     S.Diag(CDA->getLocation(),
3140            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3141     // Find the first declaration of the parameter.
3142     // FIXME: Should we build redeclaration chains for function parameters?
3143     const FunctionDecl *FirstFD =
3144       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3145     const ParmVarDecl *FirstVD =
3146       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3147     S.Diag(FirstVD->getLocation(),
3148            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3149   }
3150 
3151   if (!oldDecl->hasAttrs())
3152     return;
3153 
3154   bool foundAny = newDecl->hasAttrs();
3155 
3156   // Ensure that any moving of objects within the allocated map is
3157   // done before we process them.
3158   if (!foundAny) newDecl->setAttrs(AttrVec());
3159 
3160   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3161     if (!DeclHasAttr(newDecl, I)) {
3162       InheritableAttr *newAttr =
3163         cast<InheritableParamAttr>(I->clone(S.Context));
3164       newAttr->setInherited(true);
3165       newDecl->addAttr(newAttr);
3166       foundAny = true;
3167     }
3168   }
3169 
3170   if (!foundAny) newDecl->dropAttrs();
3171 }
3172 
3173 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3174                                 const ParmVarDecl *OldParam,
3175                                 Sema &S) {
3176   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3177     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3178       if (*Oldnullability != *Newnullability) {
3179         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3180           << DiagNullabilityKind(
3181                *Newnullability,
3182                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3183                 != 0))
3184           << DiagNullabilityKind(
3185                *Oldnullability,
3186                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3187                 != 0));
3188         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3189       }
3190     } else {
3191       QualType NewT = NewParam->getType();
3192       NewT = S.Context.getAttributedType(
3193                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3194                          NewT, NewT);
3195       NewParam->setType(NewT);
3196     }
3197   }
3198 }
3199 
3200 namespace {
3201 
3202 /// Used in MergeFunctionDecl to keep track of function parameters in
3203 /// C.
3204 struct GNUCompatibleParamWarning {
3205   ParmVarDecl *OldParm;
3206   ParmVarDecl *NewParm;
3207   QualType PromotedType;
3208 };
3209 
3210 } // end anonymous namespace
3211 
3212 // Determine whether the previous declaration was a definition, implicit
3213 // declaration, or a declaration.
3214 template <typename T>
3215 static std::pair<diag::kind, SourceLocation>
3216 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3217   diag::kind PrevDiag;
3218   SourceLocation OldLocation = Old->getLocation();
3219   if (Old->isThisDeclarationADefinition())
3220     PrevDiag = diag::note_previous_definition;
3221   else if (Old->isImplicit()) {
3222     PrevDiag = diag::note_previous_implicit_declaration;
3223     if (OldLocation.isInvalid())
3224       OldLocation = New->getLocation();
3225   } else
3226     PrevDiag = diag::note_previous_declaration;
3227   return std::make_pair(PrevDiag, OldLocation);
3228 }
3229 
3230 /// canRedefineFunction - checks if a function can be redefined. Currently,
3231 /// only extern inline functions can be redefined, and even then only in
3232 /// GNU89 mode.
3233 static bool canRedefineFunction(const FunctionDecl *FD,
3234                                 const LangOptions& LangOpts) {
3235   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3236           !LangOpts.CPlusPlus &&
3237           FD->isInlineSpecified() &&
3238           FD->getStorageClass() == SC_Extern);
3239 }
3240 
3241 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3242   const AttributedType *AT = T->getAs<AttributedType>();
3243   while (AT && !AT->isCallingConv())
3244     AT = AT->getModifiedType()->getAs<AttributedType>();
3245   return AT;
3246 }
3247 
3248 template <typename T>
3249 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3250   const DeclContext *DC = Old->getDeclContext();
3251   if (DC->isRecord())
3252     return false;
3253 
3254   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3255   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3256     return true;
3257   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3258     return true;
3259   return false;
3260 }
3261 
3262 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3263 static bool isExternC(VarTemplateDecl *) { return false; }
3264 static bool isExternC(FunctionTemplateDecl *) { return false; }
3265 
3266 /// Check whether a redeclaration of an entity introduced by a
3267 /// using-declaration is valid, given that we know it's not an overload
3268 /// (nor a hidden tag declaration).
3269 template<typename ExpectedDecl>
3270 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3271                                    ExpectedDecl *New) {
3272   // C++11 [basic.scope.declarative]p4:
3273   //   Given a set of declarations in a single declarative region, each of
3274   //   which specifies the same unqualified name,
3275   //   -- they shall all refer to the same entity, or all refer to functions
3276   //      and function templates; or
3277   //   -- exactly one declaration shall declare a class name or enumeration
3278   //      name that is not a typedef name and the other declarations shall all
3279   //      refer to the same variable or enumerator, or all refer to functions
3280   //      and function templates; in this case the class name or enumeration
3281   //      name is hidden (3.3.10).
3282 
3283   // C++11 [namespace.udecl]p14:
3284   //   If a function declaration in namespace scope or block scope has the
3285   //   same name and the same parameter-type-list as a function introduced
3286   //   by a using-declaration, and the declarations do not declare the same
3287   //   function, the program is ill-formed.
3288 
3289   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3290   if (Old &&
3291       !Old->getDeclContext()->getRedeclContext()->Equals(
3292           New->getDeclContext()->getRedeclContext()) &&
3293       !(isExternC(Old) && isExternC(New)))
3294     Old = nullptr;
3295 
3296   if (!Old) {
3297     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3298     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3299     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3300     return true;
3301   }
3302   return false;
3303 }
3304 
3305 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3306                                             const FunctionDecl *B) {
3307   assert(A->getNumParams() == B->getNumParams());
3308 
3309   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3310     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3311     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3312     if (AttrA == AttrB)
3313       return true;
3314     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3315            AttrA->isDynamic() == AttrB->isDynamic();
3316   };
3317 
3318   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3319 }
3320 
3321 /// If necessary, adjust the semantic declaration context for a qualified
3322 /// declaration to name the correct inline namespace within the qualifier.
3323 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3324                                                DeclaratorDecl *OldD) {
3325   // The only case where we need to update the DeclContext is when
3326   // redeclaration lookup for a qualified name finds a declaration
3327   // in an inline namespace within the context named by the qualifier:
3328   //
3329   //   inline namespace N { int f(); }
3330   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3331   //
3332   // For unqualified declarations, the semantic context *can* change
3333   // along the redeclaration chain (for local extern declarations,
3334   // extern "C" declarations, and friend declarations in particular).
3335   if (!NewD->getQualifier())
3336     return;
3337 
3338   // NewD is probably already in the right context.
3339   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3340   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3341   if (NamedDC->Equals(SemaDC))
3342     return;
3343 
3344   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3345           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3346          "unexpected context for redeclaration");
3347 
3348   auto *LexDC = NewD->getLexicalDeclContext();
3349   auto FixSemaDC = [=](NamedDecl *D) {
3350     if (!D)
3351       return;
3352     D->setDeclContext(SemaDC);
3353     D->setLexicalDeclContext(LexDC);
3354   };
3355 
3356   FixSemaDC(NewD);
3357   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3358     FixSemaDC(FD->getDescribedFunctionTemplate());
3359   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3360     FixSemaDC(VD->getDescribedVarTemplate());
3361 }
3362 
3363 /// MergeFunctionDecl - We just parsed a function 'New' from
3364 /// declarator D which has the same name and scope as a previous
3365 /// declaration 'Old'.  Figure out how to resolve this situation,
3366 /// merging decls or emitting diagnostics as appropriate.
3367 ///
3368 /// In C++, New and Old must be declarations that are not
3369 /// overloaded. Use IsOverload to determine whether New and Old are
3370 /// overloaded, and to select the Old declaration that New should be
3371 /// merged with.
3372 ///
3373 /// Returns true if there was an error, false otherwise.
3374 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3375                              Scope *S, bool MergeTypeWithOld) {
3376   // Verify the old decl was also a function.
3377   FunctionDecl *Old = OldD->getAsFunction();
3378   if (!Old) {
3379     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3380       if (New->getFriendObjectKind()) {
3381         Diag(New->getLocation(), diag::err_using_decl_friend);
3382         Diag(Shadow->getTargetDecl()->getLocation(),
3383              diag::note_using_decl_target);
3384         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3385             << 0;
3386         return true;
3387       }
3388 
3389       // Check whether the two declarations might declare the same function or
3390       // function template.
3391       if (FunctionTemplateDecl *NewTemplate =
3392               New->getDescribedFunctionTemplate()) {
3393         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3394                                                          NewTemplate))
3395           return true;
3396         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3397                          ->getAsFunction();
3398       } else {
3399         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3400           return true;
3401         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3402       }
3403     } else {
3404       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3405         << New->getDeclName();
3406       notePreviousDefinition(OldD, New->getLocation());
3407       return true;
3408     }
3409   }
3410 
3411   // If the old declaration was found in an inline namespace and the new
3412   // declaration was qualified, update the DeclContext to match.
3413   adjustDeclContextForDeclaratorDecl(New, Old);
3414 
3415   // If the old declaration is invalid, just give up here.
3416   if (Old->isInvalidDecl())
3417     return true;
3418 
3419   // Disallow redeclaration of some builtins.
3420   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3421     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3422     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3423         << Old << Old->getType();
3424     return true;
3425   }
3426 
3427   diag::kind PrevDiag;
3428   SourceLocation OldLocation;
3429   std::tie(PrevDiag, OldLocation) =
3430       getNoteDiagForInvalidRedeclaration(Old, New);
3431 
3432   // Don't complain about this if we're in GNU89 mode and the old function
3433   // is an extern inline function.
3434   // Don't complain about specializations. They are not supposed to have
3435   // storage classes.
3436   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3437       New->getStorageClass() == SC_Static &&
3438       Old->hasExternalFormalLinkage() &&
3439       !New->getTemplateSpecializationInfo() &&
3440       !canRedefineFunction(Old, getLangOpts())) {
3441     if (getLangOpts().MicrosoftExt) {
3442       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3443       Diag(OldLocation, PrevDiag);
3444     } else {
3445       Diag(New->getLocation(), diag::err_static_non_static) << New;
3446       Diag(OldLocation, PrevDiag);
3447       return true;
3448     }
3449   }
3450 
3451   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3452     if (!Old->hasAttr<InternalLinkageAttr>()) {
3453       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3454           << ILA;
3455       Diag(Old->getLocation(), diag::note_previous_declaration);
3456       New->dropAttr<InternalLinkageAttr>();
3457     }
3458 
3459   if (auto *EA = New->getAttr<ErrorAttr>()) {
3460     if (!Old->hasAttr<ErrorAttr>()) {
3461       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3462       Diag(Old->getLocation(), diag::note_previous_declaration);
3463       New->dropAttr<ErrorAttr>();
3464     }
3465   }
3466 
3467   if (CheckRedeclarationInModule(New, Old))
3468     return true;
3469 
3470   if (!getLangOpts().CPlusPlus) {
3471     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3472     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3473       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3474         << New << OldOvl;
3475 
3476       // Try our best to find a decl that actually has the overloadable
3477       // attribute for the note. In most cases (e.g. programs with only one
3478       // broken declaration/definition), this won't matter.
3479       //
3480       // FIXME: We could do this if we juggled some extra state in
3481       // OverloadableAttr, rather than just removing it.
3482       const Decl *DiagOld = Old;
3483       if (OldOvl) {
3484         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3485           const auto *A = D->getAttr<OverloadableAttr>();
3486           return A && !A->isImplicit();
3487         });
3488         // If we've implicitly added *all* of the overloadable attrs to this
3489         // chain, emitting a "previous redecl" note is pointless.
3490         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3491       }
3492 
3493       if (DiagOld)
3494         Diag(DiagOld->getLocation(),
3495              diag::note_attribute_overloadable_prev_overload)
3496           << OldOvl;
3497 
3498       if (OldOvl)
3499         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3500       else
3501         New->dropAttr<OverloadableAttr>();
3502     }
3503   }
3504 
3505   // If a function is first declared with a calling convention, but is later
3506   // declared or defined without one, all following decls assume the calling
3507   // convention of the first.
3508   //
3509   // It's OK if a function is first declared without a calling convention,
3510   // but is later declared or defined with the default calling convention.
3511   //
3512   // To test if either decl has an explicit calling convention, we look for
3513   // AttributedType sugar nodes on the type as written.  If they are missing or
3514   // were canonicalized away, we assume the calling convention was implicit.
3515   //
3516   // Note also that we DO NOT return at this point, because we still have
3517   // other tests to run.
3518   QualType OldQType = Context.getCanonicalType(Old->getType());
3519   QualType NewQType = Context.getCanonicalType(New->getType());
3520   const FunctionType *OldType = cast<FunctionType>(OldQType);
3521   const FunctionType *NewType = cast<FunctionType>(NewQType);
3522   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3523   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3524   bool RequiresAdjustment = false;
3525 
3526   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3527     FunctionDecl *First = Old->getFirstDecl();
3528     const FunctionType *FT =
3529         First->getType().getCanonicalType()->castAs<FunctionType>();
3530     FunctionType::ExtInfo FI = FT->getExtInfo();
3531     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3532     if (!NewCCExplicit) {
3533       // Inherit the CC from the previous declaration if it was specified
3534       // there but not here.
3535       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3536       RequiresAdjustment = true;
3537     } else if (Old->getBuiltinID()) {
3538       // Builtin attribute isn't propagated to the new one yet at this point,
3539       // so we check if the old one is a builtin.
3540 
3541       // Calling Conventions on a Builtin aren't really useful and setting a
3542       // default calling convention and cdecl'ing some builtin redeclarations is
3543       // common, so warn and ignore the calling convention on the redeclaration.
3544       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3545           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3546           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3547       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3548       RequiresAdjustment = true;
3549     } else {
3550       // Calling conventions aren't compatible, so complain.
3551       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3552       Diag(New->getLocation(), diag::err_cconv_change)
3553         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3554         << !FirstCCExplicit
3555         << (!FirstCCExplicit ? "" :
3556             FunctionType::getNameForCallConv(FI.getCC()));
3557 
3558       // Put the note on the first decl, since it is the one that matters.
3559       Diag(First->getLocation(), diag::note_previous_declaration);
3560       return true;
3561     }
3562   }
3563 
3564   // FIXME: diagnose the other way around?
3565   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3566     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3567     RequiresAdjustment = true;
3568   }
3569 
3570   // Merge regparm attribute.
3571   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3572       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3573     if (NewTypeInfo.getHasRegParm()) {
3574       Diag(New->getLocation(), diag::err_regparm_mismatch)
3575         << NewType->getRegParmType()
3576         << OldType->getRegParmType();
3577       Diag(OldLocation, diag::note_previous_declaration);
3578       return true;
3579     }
3580 
3581     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3582     RequiresAdjustment = true;
3583   }
3584 
3585   // Merge ns_returns_retained attribute.
3586   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3587     if (NewTypeInfo.getProducesResult()) {
3588       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3589           << "'ns_returns_retained'";
3590       Diag(OldLocation, diag::note_previous_declaration);
3591       return true;
3592     }
3593 
3594     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3595     RequiresAdjustment = true;
3596   }
3597 
3598   if (OldTypeInfo.getNoCallerSavedRegs() !=
3599       NewTypeInfo.getNoCallerSavedRegs()) {
3600     if (NewTypeInfo.getNoCallerSavedRegs()) {
3601       AnyX86NoCallerSavedRegistersAttr *Attr =
3602         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3603       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3604       Diag(OldLocation, diag::note_previous_declaration);
3605       return true;
3606     }
3607 
3608     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3609     RequiresAdjustment = true;
3610   }
3611 
3612   if (RequiresAdjustment) {
3613     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3614     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3615     New->setType(QualType(AdjustedType, 0));
3616     NewQType = Context.getCanonicalType(New->getType());
3617   }
3618 
3619   // If this redeclaration makes the function inline, we may need to add it to
3620   // UndefinedButUsed.
3621   if (!Old->isInlined() && New->isInlined() &&
3622       !New->hasAttr<GNUInlineAttr>() &&
3623       !getLangOpts().GNUInline &&
3624       Old->isUsed(false) &&
3625       !Old->isDefined() && !New->isThisDeclarationADefinition())
3626     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3627                                            SourceLocation()));
3628 
3629   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3630   // about it.
3631   if (New->hasAttr<GNUInlineAttr>() &&
3632       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3633     UndefinedButUsed.erase(Old->getCanonicalDecl());
3634   }
3635 
3636   // If pass_object_size params don't match up perfectly, this isn't a valid
3637   // redeclaration.
3638   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3639       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3640     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3641         << New->getDeclName();
3642     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3643     return true;
3644   }
3645 
3646   if (getLangOpts().CPlusPlus) {
3647     // C++1z [over.load]p2
3648     //   Certain function declarations cannot be overloaded:
3649     //     -- Function declarations that differ only in the return type,
3650     //        the exception specification, or both cannot be overloaded.
3651 
3652     // Check the exception specifications match. This may recompute the type of
3653     // both Old and New if it resolved exception specifications, so grab the
3654     // types again after this. Because this updates the type, we do this before
3655     // any of the other checks below, which may update the "de facto" NewQType
3656     // but do not necessarily update the type of New.
3657     if (CheckEquivalentExceptionSpec(Old, New))
3658       return true;
3659     OldQType = Context.getCanonicalType(Old->getType());
3660     NewQType = Context.getCanonicalType(New->getType());
3661 
3662     // Go back to the type source info to compare the declared return types,
3663     // per C++1y [dcl.type.auto]p13:
3664     //   Redeclarations or specializations of a function or function template
3665     //   with a declared return type that uses a placeholder type shall also
3666     //   use that placeholder, not a deduced type.
3667     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3668     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3669     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3670         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3671                                        OldDeclaredReturnType)) {
3672       QualType ResQT;
3673       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3674           OldDeclaredReturnType->isObjCObjectPointerType())
3675         // FIXME: This does the wrong thing for a deduced return type.
3676         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3677       if (ResQT.isNull()) {
3678         if (New->isCXXClassMember() && New->isOutOfLine())
3679           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3680               << New << New->getReturnTypeSourceRange();
3681         else
3682           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3683               << New->getReturnTypeSourceRange();
3684         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3685                                     << Old->getReturnTypeSourceRange();
3686         return true;
3687       }
3688       else
3689         NewQType = ResQT;
3690     }
3691 
3692     QualType OldReturnType = OldType->getReturnType();
3693     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3694     if (OldReturnType != NewReturnType) {
3695       // If this function has a deduced return type and has already been
3696       // defined, copy the deduced value from the old declaration.
3697       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3698       if (OldAT && OldAT->isDeduced()) {
3699         QualType DT = OldAT->getDeducedType();
3700         if (DT.isNull()) {
3701           New->setType(SubstAutoTypeDependent(New->getType()));
3702           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3703         } else {
3704           New->setType(SubstAutoType(New->getType(), DT));
3705           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3706         }
3707       }
3708     }
3709 
3710     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3711     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3712     if (OldMethod && NewMethod) {
3713       // Preserve triviality.
3714       NewMethod->setTrivial(OldMethod->isTrivial());
3715 
3716       // MSVC allows explicit template specialization at class scope:
3717       // 2 CXXMethodDecls referring to the same function will be injected.
3718       // We don't want a redeclaration error.
3719       bool IsClassScopeExplicitSpecialization =
3720                               OldMethod->isFunctionTemplateSpecialization() &&
3721                               NewMethod->isFunctionTemplateSpecialization();
3722       bool isFriend = NewMethod->getFriendObjectKind();
3723 
3724       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3725           !IsClassScopeExplicitSpecialization) {
3726         //    -- Member function declarations with the same name and the
3727         //       same parameter types cannot be overloaded if any of them
3728         //       is a static member function declaration.
3729         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3730           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3731           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3732           return true;
3733         }
3734 
3735         // C++ [class.mem]p1:
3736         //   [...] A member shall not be declared twice in the
3737         //   member-specification, except that a nested class or member
3738         //   class template can be declared and then later defined.
3739         if (!inTemplateInstantiation()) {
3740           unsigned NewDiag;
3741           if (isa<CXXConstructorDecl>(OldMethod))
3742             NewDiag = diag::err_constructor_redeclared;
3743           else if (isa<CXXDestructorDecl>(NewMethod))
3744             NewDiag = diag::err_destructor_redeclared;
3745           else if (isa<CXXConversionDecl>(NewMethod))
3746             NewDiag = diag::err_conv_function_redeclared;
3747           else
3748             NewDiag = diag::err_member_redeclared;
3749 
3750           Diag(New->getLocation(), NewDiag);
3751         } else {
3752           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3753             << New << New->getType();
3754         }
3755         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3756         return true;
3757 
3758       // Complain if this is an explicit declaration of a special
3759       // member that was initially declared implicitly.
3760       //
3761       // As an exception, it's okay to befriend such methods in order
3762       // to permit the implicit constructor/destructor/operator calls.
3763       } else if (OldMethod->isImplicit()) {
3764         if (isFriend) {
3765           NewMethod->setImplicit();
3766         } else {
3767           Diag(NewMethod->getLocation(),
3768                diag::err_definition_of_implicitly_declared_member)
3769             << New << getSpecialMember(OldMethod);
3770           return true;
3771         }
3772       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3773         Diag(NewMethod->getLocation(),
3774              diag::err_definition_of_explicitly_defaulted_member)
3775           << getSpecialMember(OldMethod);
3776         return true;
3777       }
3778     }
3779 
3780     // C++11 [dcl.attr.noreturn]p1:
3781     //   The first declaration of a function shall specify the noreturn
3782     //   attribute if any declaration of that function specifies the noreturn
3783     //   attribute.
3784     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3785       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3786         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3787             << NRA;
3788         Diag(Old->getLocation(), diag::note_previous_declaration);
3789       }
3790 
3791     // C++11 [dcl.attr.depend]p2:
3792     //   The first declaration of a function shall specify the
3793     //   carries_dependency attribute for its declarator-id if any declaration
3794     //   of the function specifies the carries_dependency attribute.
3795     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3796     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3797       Diag(CDA->getLocation(),
3798            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3799       Diag(Old->getFirstDecl()->getLocation(),
3800            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3801     }
3802 
3803     // (C++98 8.3.5p3):
3804     //   All declarations for a function shall agree exactly in both the
3805     //   return type and the parameter-type-list.
3806     // We also want to respect all the extended bits except noreturn.
3807 
3808     // noreturn should now match unless the old type info didn't have it.
3809     QualType OldQTypeForComparison = OldQType;
3810     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3811       auto *OldType = OldQType->castAs<FunctionProtoType>();
3812       const FunctionType *OldTypeForComparison
3813         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3814       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3815       assert(OldQTypeForComparison.isCanonical());
3816     }
3817 
3818     if (haveIncompatibleLanguageLinkages(Old, New)) {
3819       // As a special case, retain the language linkage from previous
3820       // declarations of a friend function as an extension.
3821       //
3822       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3823       // and is useful because there's otherwise no way to specify language
3824       // linkage within class scope.
3825       //
3826       // Check cautiously as the friend object kind isn't yet complete.
3827       if (New->getFriendObjectKind() != Decl::FOK_None) {
3828         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3829         Diag(OldLocation, PrevDiag);
3830       } else {
3831         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3832         Diag(OldLocation, PrevDiag);
3833         return true;
3834       }
3835     }
3836 
3837     // If the function types are compatible, merge the declarations. Ignore the
3838     // exception specifier because it was already checked above in
3839     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3840     // about incompatible types under -fms-compatibility.
3841     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3842                                                          NewQType))
3843       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3844 
3845     // If the types are imprecise (due to dependent constructs in friends or
3846     // local extern declarations), it's OK if they differ. We'll check again
3847     // during instantiation.
3848     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3849       return false;
3850 
3851     // Fall through for conflicting redeclarations and redefinitions.
3852   }
3853 
3854   // C: Function types need to be compatible, not identical. This handles
3855   // duplicate function decls like "void f(int); void f(enum X);" properly.
3856   if (!getLangOpts().CPlusPlus &&
3857       Context.typesAreCompatible(OldQType, NewQType)) {
3858     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3859     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3860     const FunctionProtoType *OldProto = nullptr;
3861     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3862         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3863       // The old declaration provided a function prototype, but the
3864       // new declaration does not. Merge in the prototype.
3865       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3866       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3867       NewQType =
3868           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3869                                   OldProto->getExtProtoInfo());
3870       New->setType(NewQType);
3871       New->setHasInheritedPrototype();
3872 
3873       // Synthesize parameters with the same types.
3874       SmallVector<ParmVarDecl*, 16> Params;
3875       for (const auto &ParamType : OldProto->param_types()) {
3876         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3877                                                  SourceLocation(), nullptr,
3878                                                  ParamType, /*TInfo=*/nullptr,
3879                                                  SC_None, nullptr);
3880         Param->setScopeInfo(0, Params.size());
3881         Param->setImplicit();
3882         Params.push_back(Param);
3883       }
3884 
3885       New->setParams(Params);
3886     }
3887 
3888     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3889   }
3890 
3891   // Check if the function types are compatible when pointer size address
3892   // spaces are ignored.
3893   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3894     return false;
3895 
3896   // GNU C permits a K&R definition to follow a prototype declaration
3897   // if the declared types of the parameters in the K&R definition
3898   // match the types in the prototype declaration, even when the
3899   // promoted types of the parameters from the K&R definition differ
3900   // from the types in the prototype. GCC then keeps the types from
3901   // the prototype.
3902   //
3903   // If a variadic prototype is followed by a non-variadic K&R definition,
3904   // the K&R definition becomes variadic.  This is sort of an edge case, but
3905   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3906   // C99 6.9.1p8.
3907   if (!getLangOpts().CPlusPlus &&
3908       Old->hasPrototype() && !New->hasPrototype() &&
3909       New->getType()->getAs<FunctionProtoType>() &&
3910       Old->getNumParams() == New->getNumParams()) {
3911     SmallVector<QualType, 16> ArgTypes;
3912     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3913     const FunctionProtoType *OldProto
3914       = Old->getType()->getAs<FunctionProtoType>();
3915     const FunctionProtoType *NewProto
3916       = New->getType()->getAs<FunctionProtoType>();
3917 
3918     // Determine whether this is the GNU C extension.
3919     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3920                                                NewProto->getReturnType());
3921     bool LooseCompatible = !MergedReturn.isNull();
3922     for (unsigned Idx = 0, End = Old->getNumParams();
3923          LooseCompatible && Idx != End; ++Idx) {
3924       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3925       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3926       if (Context.typesAreCompatible(OldParm->getType(),
3927                                      NewProto->getParamType(Idx))) {
3928         ArgTypes.push_back(NewParm->getType());
3929       } else if (Context.typesAreCompatible(OldParm->getType(),
3930                                             NewParm->getType(),
3931                                             /*CompareUnqualified=*/true)) {
3932         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3933                                            NewProto->getParamType(Idx) };
3934         Warnings.push_back(Warn);
3935         ArgTypes.push_back(NewParm->getType());
3936       } else
3937         LooseCompatible = false;
3938     }
3939 
3940     if (LooseCompatible) {
3941       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3942         Diag(Warnings[Warn].NewParm->getLocation(),
3943              diag::ext_param_promoted_not_compatible_with_prototype)
3944           << Warnings[Warn].PromotedType
3945           << Warnings[Warn].OldParm->getType();
3946         if (Warnings[Warn].OldParm->getLocation().isValid())
3947           Diag(Warnings[Warn].OldParm->getLocation(),
3948                diag::note_previous_declaration);
3949       }
3950 
3951       if (MergeTypeWithOld)
3952         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3953                                              OldProto->getExtProtoInfo()));
3954       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3955     }
3956 
3957     // Fall through to diagnose conflicting types.
3958   }
3959 
3960   // A function that has already been declared has been redeclared or
3961   // defined with a different type; show an appropriate diagnostic.
3962 
3963   // If the previous declaration was an implicitly-generated builtin
3964   // declaration, then at the very least we should use a specialized note.
3965   unsigned BuiltinID;
3966   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3967     // If it's actually a library-defined builtin function like 'malloc'
3968     // or 'printf', just warn about the incompatible redeclaration.
3969     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3970       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3971       Diag(OldLocation, diag::note_previous_builtin_declaration)
3972         << Old << Old->getType();
3973       return false;
3974     }
3975 
3976     PrevDiag = diag::note_previous_builtin_declaration;
3977   }
3978 
3979   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3980   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3981   return true;
3982 }
3983 
3984 /// Completes the merge of two function declarations that are
3985 /// known to be compatible.
3986 ///
3987 /// This routine handles the merging of attributes and other
3988 /// properties of function declarations from the old declaration to
3989 /// the new declaration, once we know that New is in fact a
3990 /// redeclaration of Old.
3991 ///
3992 /// \returns false
3993 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3994                                         Scope *S, bool MergeTypeWithOld) {
3995   // Merge the attributes
3996   mergeDeclAttributes(New, Old);
3997 
3998   // Merge "pure" flag.
3999   if (Old->isPure())
4000     New->setPure();
4001 
4002   // Merge "used" flag.
4003   if (Old->getMostRecentDecl()->isUsed(false))
4004     New->setIsUsed();
4005 
4006   // Merge attributes from the parameters.  These can mismatch with K&R
4007   // declarations.
4008   if (New->getNumParams() == Old->getNumParams())
4009       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4010         ParmVarDecl *NewParam = New->getParamDecl(i);
4011         ParmVarDecl *OldParam = Old->getParamDecl(i);
4012         mergeParamDeclAttributes(NewParam, OldParam, *this);
4013         mergeParamDeclTypes(NewParam, OldParam, *this);
4014       }
4015 
4016   if (getLangOpts().CPlusPlus)
4017     return MergeCXXFunctionDecl(New, Old, S);
4018 
4019   // Merge the function types so the we get the composite types for the return
4020   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4021   // was visible.
4022   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4023   if (!Merged.isNull() && MergeTypeWithOld)
4024     New->setType(Merged);
4025 
4026   return false;
4027 }
4028 
4029 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4030                                 ObjCMethodDecl *oldMethod) {
4031   // Merge the attributes, including deprecated/unavailable
4032   AvailabilityMergeKind MergeKind =
4033       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4034           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4035                                      : AMK_ProtocolImplementation)
4036           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4037                                                            : AMK_Override;
4038 
4039   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4040 
4041   // Merge attributes from the parameters.
4042   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4043                                        oe = oldMethod->param_end();
4044   for (ObjCMethodDecl::param_iterator
4045          ni = newMethod->param_begin(), ne = newMethod->param_end();
4046        ni != ne && oi != oe; ++ni, ++oi)
4047     mergeParamDeclAttributes(*ni, *oi, *this);
4048 
4049   CheckObjCMethodOverride(newMethod, oldMethod);
4050 }
4051 
4052 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4053   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4054 
4055   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4056          ? diag::err_redefinition_different_type
4057          : diag::err_redeclaration_different_type)
4058     << New->getDeclName() << New->getType() << Old->getType();
4059 
4060   diag::kind PrevDiag;
4061   SourceLocation OldLocation;
4062   std::tie(PrevDiag, OldLocation)
4063     = getNoteDiagForInvalidRedeclaration(Old, New);
4064   S.Diag(OldLocation, PrevDiag);
4065   New->setInvalidDecl();
4066 }
4067 
4068 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4069 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4070 /// emitting diagnostics as appropriate.
4071 ///
4072 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4073 /// to here in AddInitializerToDecl. We can't check them before the initializer
4074 /// is attached.
4075 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4076                              bool MergeTypeWithOld) {
4077   if (New->isInvalidDecl() || Old->isInvalidDecl())
4078     return;
4079 
4080   QualType MergedT;
4081   if (getLangOpts().CPlusPlus) {
4082     if (New->getType()->isUndeducedType()) {
4083       // We don't know what the new type is until the initializer is attached.
4084       return;
4085     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4086       // These could still be something that needs exception specs checked.
4087       return MergeVarDeclExceptionSpecs(New, Old);
4088     }
4089     // C++ [basic.link]p10:
4090     //   [...] the types specified by all declarations referring to a given
4091     //   object or function shall be identical, except that declarations for an
4092     //   array object can specify array types that differ by the presence or
4093     //   absence of a major array bound (8.3.4).
4094     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4095       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4096       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4097 
4098       // We are merging a variable declaration New into Old. If it has an array
4099       // bound, and that bound differs from Old's bound, we should diagnose the
4100       // mismatch.
4101       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4102         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4103              PrevVD = PrevVD->getPreviousDecl()) {
4104           QualType PrevVDTy = PrevVD->getType();
4105           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4106             continue;
4107 
4108           if (!Context.hasSameType(New->getType(), PrevVDTy))
4109             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4110         }
4111       }
4112 
4113       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4114         if (Context.hasSameType(OldArray->getElementType(),
4115                                 NewArray->getElementType()))
4116           MergedT = New->getType();
4117       }
4118       // FIXME: Check visibility. New is hidden but has a complete type. If New
4119       // has no array bound, it should not inherit one from Old, if Old is not
4120       // visible.
4121       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4122         if (Context.hasSameType(OldArray->getElementType(),
4123                                 NewArray->getElementType()))
4124           MergedT = Old->getType();
4125       }
4126     }
4127     else if (New->getType()->isObjCObjectPointerType() &&
4128                Old->getType()->isObjCObjectPointerType()) {
4129       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4130                                               Old->getType());
4131     }
4132   } else {
4133     // C 6.2.7p2:
4134     //   All declarations that refer to the same object or function shall have
4135     //   compatible type.
4136     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4137   }
4138   if (MergedT.isNull()) {
4139     // It's OK if we couldn't merge types if either type is dependent, for a
4140     // block-scope variable. In other cases (static data members of class
4141     // templates, variable templates, ...), we require the types to be
4142     // equivalent.
4143     // FIXME: The C++ standard doesn't say anything about this.
4144     if ((New->getType()->isDependentType() ||
4145          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4146       // If the old type was dependent, we can't merge with it, so the new type
4147       // becomes dependent for now. We'll reproduce the original type when we
4148       // instantiate the TypeSourceInfo for the variable.
4149       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4150         New->setType(Context.DependentTy);
4151       return;
4152     }
4153     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4154   }
4155 
4156   // Don't actually update the type on the new declaration if the old
4157   // declaration was an extern declaration in a different scope.
4158   if (MergeTypeWithOld)
4159     New->setType(MergedT);
4160 }
4161 
4162 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4163                                   LookupResult &Previous) {
4164   // C11 6.2.7p4:
4165   //   For an identifier with internal or external linkage declared
4166   //   in a scope in which a prior declaration of that identifier is
4167   //   visible, if the prior declaration specifies internal or
4168   //   external linkage, the type of the identifier at the later
4169   //   declaration becomes the composite type.
4170   //
4171   // If the variable isn't visible, we do not merge with its type.
4172   if (Previous.isShadowed())
4173     return false;
4174 
4175   if (S.getLangOpts().CPlusPlus) {
4176     // C++11 [dcl.array]p3:
4177     //   If there is a preceding declaration of the entity in the same
4178     //   scope in which the bound was specified, an omitted array bound
4179     //   is taken to be the same as in that earlier declaration.
4180     return NewVD->isPreviousDeclInSameBlockScope() ||
4181            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4182             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4183   } else {
4184     // If the old declaration was function-local, don't merge with its
4185     // type unless we're in the same function.
4186     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4187            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4188   }
4189 }
4190 
4191 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4192 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4193 /// situation, merging decls or emitting diagnostics as appropriate.
4194 ///
4195 /// Tentative definition rules (C99 6.9.2p2) are checked by
4196 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4197 /// definitions here, since the initializer hasn't been attached.
4198 ///
4199 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4200   // If the new decl is already invalid, don't do any other checking.
4201   if (New->isInvalidDecl())
4202     return;
4203 
4204   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4205     return;
4206 
4207   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4208 
4209   // Verify the old decl was also a variable or variable template.
4210   VarDecl *Old = nullptr;
4211   VarTemplateDecl *OldTemplate = nullptr;
4212   if (Previous.isSingleResult()) {
4213     if (NewTemplate) {
4214       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4215       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4216 
4217       if (auto *Shadow =
4218               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4219         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4220           return New->setInvalidDecl();
4221     } else {
4222       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4223 
4224       if (auto *Shadow =
4225               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4226         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4227           return New->setInvalidDecl();
4228     }
4229   }
4230   if (!Old) {
4231     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4232         << New->getDeclName();
4233     notePreviousDefinition(Previous.getRepresentativeDecl(),
4234                            New->getLocation());
4235     return New->setInvalidDecl();
4236   }
4237 
4238   // If the old declaration was found in an inline namespace and the new
4239   // declaration was qualified, update the DeclContext to match.
4240   adjustDeclContextForDeclaratorDecl(New, Old);
4241 
4242   // Ensure the template parameters are compatible.
4243   if (NewTemplate &&
4244       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4245                                       OldTemplate->getTemplateParameters(),
4246                                       /*Complain=*/true, TPL_TemplateMatch))
4247     return New->setInvalidDecl();
4248 
4249   // C++ [class.mem]p1:
4250   //   A member shall not be declared twice in the member-specification [...]
4251   //
4252   // Here, we need only consider static data members.
4253   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4254     Diag(New->getLocation(), diag::err_duplicate_member)
4255       << New->getIdentifier();
4256     Diag(Old->getLocation(), diag::note_previous_declaration);
4257     New->setInvalidDecl();
4258   }
4259 
4260   mergeDeclAttributes(New, Old);
4261   // Warn if an already-declared variable is made a weak_import in a subsequent
4262   // declaration
4263   if (New->hasAttr<WeakImportAttr>() &&
4264       Old->getStorageClass() == SC_None &&
4265       !Old->hasAttr<WeakImportAttr>()) {
4266     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4267     Diag(Old->getLocation(), diag::note_previous_declaration);
4268     // Remove weak_import attribute on new declaration.
4269     New->dropAttr<WeakImportAttr>();
4270   }
4271 
4272   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4273     if (!Old->hasAttr<InternalLinkageAttr>()) {
4274       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4275           << ILA;
4276       Diag(Old->getLocation(), diag::note_previous_declaration);
4277       New->dropAttr<InternalLinkageAttr>();
4278     }
4279 
4280   // Merge the types.
4281   VarDecl *MostRecent = Old->getMostRecentDecl();
4282   if (MostRecent != Old) {
4283     MergeVarDeclTypes(New, MostRecent,
4284                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4285     if (New->isInvalidDecl())
4286       return;
4287   }
4288 
4289   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4290   if (New->isInvalidDecl())
4291     return;
4292 
4293   diag::kind PrevDiag;
4294   SourceLocation OldLocation;
4295   std::tie(PrevDiag, OldLocation) =
4296       getNoteDiagForInvalidRedeclaration(Old, New);
4297 
4298   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4299   if (New->getStorageClass() == SC_Static &&
4300       !New->isStaticDataMember() &&
4301       Old->hasExternalFormalLinkage()) {
4302     if (getLangOpts().MicrosoftExt) {
4303       Diag(New->getLocation(), diag::ext_static_non_static)
4304           << New->getDeclName();
4305       Diag(OldLocation, PrevDiag);
4306     } else {
4307       Diag(New->getLocation(), diag::err_static_non_static)
4308           << New->getDeclName();
4309       Diag(OldLocation, PrevDiag);
4310       return New->setInvalidDecl();
4311     }
4312   }
4313   // C99 6.2.2p4:
4314   //   For an identifier declared with the storage-class specifier
4315   //   extern in a scope in which a prior declaration of that
4316   //   identifier is visible,23) if the prior declaration specifies
4317   //   internal or external linkage, the linkage of the identifier at
4318   //   the later declaration is the same as the linkage specified at
4319   //   the prior declaration. If no prior declaration is visible, or
4320   //   if the prior declaration specifies no linkage, then the
4321   //   identifier has external linkage.
4322   if (New->hasExternalStorage() && Old->hasLinkage())
4323     /* Okay */;
4324   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4325            !New->isStaticDataMember() &&
4326            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4327     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4328     Diag(OldLocation, PrevDiag);
4329     return New->setInvalidDecl();
4330   }
4331 
4332   // Check if extern is followed by non-extern and vice-versa.
4333   if (New->hasExternalStorage() &&
4334       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4335     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4336     Diag(OldLocation, PrevDiag);
4337     return New->setInvalidDecl();
4338   }
4339   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4340       !New->hasExternalStorage()) {
4341     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4342     Diag(OldLocation, PrevDiag);
4343     return New->setInvalidDecl();
4344   }
4345 
4346   if (CheckRedeclarationInModule(New, Old))
4347     return;
4348 
4349   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4350 
4351   // FIXME: The test for external storage here seems wrong? We still
4352   // need to check for mismatches.
4353   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4354       // Don't complain about out-of-line definitions of static members.
4355       !(Old->getLexicalDeclContext()->isRecord() &&
4356         !New->getLexicalDeclContext()->isRecord())) {
4357     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4358     Diag(OldLocation, PrevDiag);
4359     return New->setInvalidDecl();
4360   }
4361 
4362   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4363     if (VarDecl *Def = Old->getDefinition()) {
4364       // C++1z [dcl.fcn.spec]p4:
4365       //   If the definition of a variable appears in a translation unit before
4366       //   its first declaration as inline, the program is ill-formed.
4367       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4368       Diag(Def->getLocation(), diag::note_previous_definition);
4369     }
4370   }
4371 
4372   // If this redeclaration makes the variable inline, we may need to add it to
4373   // UndefinedButUsed.
4374   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4375       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4376     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4377                                            SourceLocation()));
4378 
4379   if (New->getTLSKind() != Old->getTLSKind()) {
4380     if (!Old->getTLSKind()) {
4381       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4382       Diag(OldLocation, PrevDiag);
4383     } else if (!New->getTLSKind()) {
4384       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4385       Diag(OldLocation, PrevDiag);
4386     } else {
4387       // Do not allow redeclaration to change the variable between requiring
4388       // static and dynamic initialization.
4389       // FIXME: GCC allows this, but uses the TLS keyword on the first
4390       // declaration to determine the kind. Do we need to be compatible here?
4391       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4392         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4393       Diag(OldLocation, PrevDiag);
4394     }
4395   }
4396 
4397   // C++ doesn't have tentative definitions, so go right ahead and check here.
4398   if (getLangOpts().CPlusPlus &&
4399       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4400     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4401         Old->getCanonicalDecl()->isConstexpr()) {
4402       // This definition won't be a definition any more once it's been merged.
4403       Diag(New->getLocation(),
4404            diag::warn_deprecated_redundant_constexpr_static_def);
4405     } else if (VarDecl *Def = Old->getDefinition()) {
4406       if (checkVarDeclRedefinition(Def, New))
4407         return;
4408     }
4409   }
4410 
4411   if (haveIncompatibleLanguageLinkages(Old, New)) {
4412     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4413     Diag(OldLocation, PrevDiag);
4414     New->setInvalidDecl();
4415     return;
4416   }
4417 
4418   // Merge "used" flag.
4419   if (Old->getMostRecentDecl()->isUsed(false))
4420     New->setIsUsed();
4421 
4422   // Keep a chain of previous declarations.
4423   New->setPreviousDecl(Old);
4424   if (NewTemplate)
4425     NewTemplate->setPreviousDecl(OldTemplate);
4426 
4427   // Inherit access appropriately.
4428   New->setAccess(Old->getAccess());
4429   if (NewTemplate)
4430     NewTemplate->setAccess(New->getAccess());
4431 
4432   if (Old->isInline())
4433     New->setImplicitlyInline();
4434 }
4435 
4436 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4437   SourceManager &SrcMgr = getSourceManager();
4438   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4439   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4440   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4441   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4442   auto &HSI = PP.getHeaderSearchInfo();
4443   StringRef HdrFilename =
4444       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4445 
4446   auto noteFromModuleOrInclude = [&](Module *Mod,
4447                                      SourceLocation IncLoc) -> bool {
4448     // Redefinition errors with modules are common with non modular mapped
4449     // headers, example: a non-modular header H in module A that also gets
4450     // included directly in a TU. Pointing twice to the same header/definition
4451     // is confusing, try to get better diagnostics when modules is on.
4452     if (IncLoc.isValid()) {
4453       if (Mod) {
4454         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4455             << HdrFilename.str() << Mod->getFullModuleName();
4456         if (!Mod->DefinitionLoc.isInvalid())
4457           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4458               << Mod->getFullModuleName();
4459       } else {
4460         Diag(IncLoc, diag::note_redefinition_include_same_file)
4461             << HdrFilename.str();
4462       }
4463       return true;
4464     }
4465 
4466     return false;
4467   };
4468 
4469   // Is it the same file and same offset? Provide more information on why
4470   // this leads to a redefinition error.
4471   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4472     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4473     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4474     bool EmittedDiag =
4475         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4476     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4477 
4478     // If the header has no guards, emit a note suggesting one.
4479     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4480       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4481 
4482     if (EmittedDiag)
4483       return;
4484   }
4485 
4486   // Redefinition coming from different files or couldn't do better above.
4487   if (Old->getLocation().isValid())
4488     Diag(Old->getLocation(), diag::note_previous_definition);
4489 }
4490 
4491 /// We've just determined that \p Old and \p New both appear to be definitions
4492 /// of the same variable. Either diagnose or fix the problem.
4493 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4494   if (!hasVisibleDefinition(Old) &&
4495       (New->getFormalLinkage() == InternalLinkage ||
4496        New->isInline() ||
4497        New->getDescribedVarTemplate() ||
4498        New->getNumTemplateParameterLists() ||
4499        New->getDeclContext()->isDependentContext())) {
4500     // The previous definition is hidden, and multiple definitions are
4501     // permitted (in separate TUs). Demote this to a declaration.
4502     New->demoteThisDefinitionToDeclaration();
4503 
4504     // Make the canonical definition visible.
4505     if (auto *OldTD = Old->getDescribedVarTemplate())
4506       makeMergedDefinitionVisible(OldTD);
4507     makeMergedDefinitionVisible(Old);
4508     return false;
4509   } else {
4510     Diag(New->getLocation(), diag::err_redefinition) << New;
4511     notePreviousDefinition(Old, New->getLocation());
4512     New->setInvalidDecl();
4513     return true;
4514   }
4515 }
4516 
4517 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4518 /// no declarator (e.g. "struct foo;") is parsed.
4519 Decl *
4520 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4521                                  RecordDecl *&AnonRecord) {
4522   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4523                                     AnonRecord);
4524 }
4525 
4526 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4527 // disambiguate entities defined in different scopes.
4528 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4529 // compatibility.
4530 // We will pick our mangling number depending on which version of MSVC is being
4531 // targeted.
4532 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4533   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4534              ? S->getMSCurManglingNumber()
4535              : S->getMSLastManglingNumber();
4536 }
4537 
4538 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4539   if (!Context.getLangOpts().CPlusPlus)
4540     return;
4541 
4542   if (isa<CXXRecordDecl>(Tag->getParent())) {
4543     // If this tag is the direct child of a class, number it if
4544     // it is anonymous.
4545     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4546       return;
4547     MangleNumberingContext &MCtx =
4548         Context.getManglingNumberContext(Tag->getParent());
4549     Context.setManglingNumber(
4550         Tag, MCtx.getManglingNumber(
4551                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4552     return;
4553   }
4554 
4555   // If this tag isn't a direct child of a class, number it if it is local.
4556   MangleNumberingContext *MCtx;
4557   Decl *ManglingContextDecl;
4558   std::tie(MCtx, ManglingContextDecl) =
4559       getCurrentMangleNumberContext(Tag->getDeclContext());
4560   if (MCtx) {
4561     Context.setManglingNumber(
4562         Tag, MCtx->getManglingNumber(
4563                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4564   }
4565 }
4566 
4567 namespace {
4568 struct NonCLikeKind {
4569   enum {
4570     None,
4571     BaseClass,
4572     DefaultMemberInit,
4573     Lambda,
4574     Friend,
4575     OtherMember,
4576     Invalid,
4577   } Kind = None;
4578   SourceRange Range;
4579 
4580   explicit operator bool() { return Kind != None; }
4581 };
4582 }
4583 
4584 /// Determine whether a class is C-like, according to the rules of C++
4585 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4586 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4587   if (RD->isInvalidDecl())
4588     return {NonCLikeKind::Invalid, {}};
4589 
4590   // C++ [dcl.typedef]p9: [P1766R1]
4591   //   An unnamed class with a typedef name for linkage purposes shall not
4592   //
4593   //    -- have any base classes
4594   if (RD->getNumBases())
4595     return {NonCLikeKind::BaseClass,
4596             SourceRange(RD->bases_begin()->getBeginLoc(),
4597                         RD->bases_end()[-1].getEndLoc())};
4598   bool Invalid = false;
4599   for (Decl *D : RD->decls()) {
4600     // Don't complain about things we already diagnosed.
4601     if (D->isInvalidDecl()) {
4602       Invalid = true;
4603       continue;
4604     }
4605 
4606     //  -- have any [...] default member initializers
4607     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4608       if (FD->hasInClassInitializer()) {
4609         auto *Init = FD->getInClassInitializer();
4610         return {NonCLikeKind::DefaultMemberInit,
4611                 Init ? Init->getSourceRange() : D->getSourceRange()};
4612       }
4613       continue;
4614     }
4615 
4616     // FIXME: We don't allow friend declarations. This violates the wording of
4617     // P1766, but not the intent.
4618     if (isa<FriendDecl>(D))
4619       return {NonCLikeKind::Friend, D->getSourceRange()};
4620 
4621     //  -- declare any members other than non-static data members, member
4622     //     enumerations, or member classes,
4623     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4624         isa<EnumDecl>(D))
4625       continue;
4626     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4627     if (!MemberRD) {
4628       if (D->isImplicit())
4629         continue;
4630       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4631     }
4632 
4633     //  -- contain a lambda-expression,
4634     if (MemberRD->isLambda())
4635       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4636 
4637     //  and all member classes shall also satisfy these requirements
4638     //  (recursively).
4639     if (MemberRD->isThisDeclarationADefinition()) {
4640       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4641         return Kind;
4642     }
4643   }
4644 
4645   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4646 }
4647 
4648 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4649                                         TypedefNameDecl *NewTD) {
4650   if (TagFromDeclSpec->isInvalidDecl())
4651     return;
4652 
4653   // Do nothing if the tag already has a name for linkage purposes.
4654   if (TagFromDeclSpec->hasNameForLinkage())
4655     return;
4656 
4657   // A well-formed anonymous tag must always be a TUK_Definition.
4658   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4659 
4660   // The type must match the tag exactly;  no qualifiers allowed.
4661   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4662                            Context.getTagDeclType(TagFromDeclSpec))) {
4663     if (getLangOpts().CPlusPlus)
4664       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4665     return;
4666   }
4667 
4668   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4669   //   An unnamed class with a typedef name for linkage purposes shall [be
4670   //   C-like].
4671   //
4672   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4673   // shouldn't happen, but there are constructs that the language rule doesn't
4674   // disallow for which we can't reasonably avoid computing linkage early.
4675   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4676   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4677                              : NonCLikeKind();
4678   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4679   if (NonCLike || ChangesLinkage) {
4680     if (NonCLike.Kind == NonCLikeKind::Invalid)
4681       return;
4682 
4683     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4684     if (ChangesLinkage) {
4685       // If the linkage changes, we can't accept this as an extension.
4686       if (NonCLike.Kind == NonCLikeKind::None)
4687         DiagID = diag::err_typedef_changes_linkage;
4688       else
4689         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4690     }
4691 
4692     SourceLocation FixitLoc =
4693         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4694     llvm::SmallString<40> TextToInsert;
4695     TextToInsert += ' ';
4696     TextToInsert += NewTD->getIdentifier()->getName();
4697 
4698     Diag(FixitLoc, DiagID)
4699       << isa<TypeAliasDecl>(NewTD)
4700       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4701     if (NonCLike.Kind != NonCLikeKind::None) {
4702       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4703         << NonCLike.Kind - 1 << NonCLike.Range;
4704     }
4705     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4706       << NewTD << isa<TypeAliasDecl>(NewTD);
4707 
4708     if (ChangesLinkage)
4709       return;
4710   }
4711 
4712   // Otherwise, set this as the anon-decl typedef for the tag.
4713   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4714 }
4715 
4716 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4717   switch (T) {
4718   case DeclSpec::TST_class:
4719     return 0;
4720   case DeclSpec::TST_struct:
4721     return 1;
4722   case DeclSpec::TST_interface:
4723     return 2;
4724   case DeclSpec::TST_union:
4725     return 3;
4726   case DeclSpec::TST_enum:
4727     return 4;
4728   default:
4729     llvm_unreachable("unexpected type specifier");
4730   }
4731 }
4732 
4733 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4734 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4735 /// parameters to cope with template friend declarations.
4736 Decl *
4737 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4738                                  MultiTemplateParamsArg TemplateParams,
4739                                  bool IsExplicitInstantiation,
4740                                  RecordDecl *&AnonRecord) {
4741   Decl *TagD = nullptr;
4742   TagDecl *Tag = nullptr;
4743   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4744       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4745       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4746       DS.getTypeSpecType() == DeclSpec::TST_union ||
4747       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4748     TagD = DS.getRepAsDecl();
4749 
4750     if (!TagD) // We probably had an error
4751       return nullptr;
4752 
4753     // Note that the above type specs guarantee that the
4754     // type rep is a Decl, whereas in many of the others
4755     // it's a Type.
4756     if (isa<TagDecl>(TagD))
4757       Tag = cast<TagDecl>(TagD);
4758     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4759       Tag = CTD->getTemplatedDecl();
4760   }
4761 
4762   if (Tag) {
4763     handleTagNumbering(Tag, S);
4764     Tag->setFreeStanding();
4765     if (Tag->isInvalidDecl())
4766       return Tag;
4767   }
4768 
4769   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4770     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4771     // or incomplete types shall not be restrict-qualified."
4772     if (TypeQuals & DeclSpec::TQ_restrict)
4773       Diag(DS.getRestrictSpecLoc(),
4774            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4775            << DS.getSourceRange();
4776   }
4777 
4778   if (DS.isInlineSpecified())
4779     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4780         << getLangOpts().CPlusPlus17;
4781 
4782   if (DS.hasConstexprSpecifier()) {
4783     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4784     // and definitions of functions and variables.
4785     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4786     // the declaration of a function or function template
4787     if (Tag)
4788       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4789           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4790           << static_cast<int>(DS.getConstexprSpecifier());
4791     else
4792       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4793           << static_cast<int>(DS.getConstexprSpecifier());
4794     // Don't emit warnings after this error.
4795     return TagD;
4796   }
4797 
4798   DiagnoseFunctionSpecifiers(DS);
4799 
4800   if (DS.isFriendSpecified()) {
4801     // If we're dealing with a decl but not a TagDecl, assume that
4802     // whatever routines created it handled the friendship aspect.
4803     if (TagD && !Tag)
4804       return nullptr;
4805     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4806   }
4807 
4808   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4809   bool IsExplicitSpecialization =
4810     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4811   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4812       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4813       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4814     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4815     // nested-name-specifier unless it is an explicit instantiation
4816     // or an explicit specialization.
4817     //
4818     // FIXME: We allow class template partial specializations here too, per the
4819     // obvious intent of DR1819.
4820     //
4821     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4822     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4823         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4824     return nullptr;
4825   }
4826 
4827   // Track whether this decl-specifier declares anything.
4828   bool DeclaresAnything = true;
4829 
4830   // Handle anonymous struct definitions.
4831   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4832     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4833         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4834       if (getLangOpts().CPlusPlus ||
4835           Record->getDeclContext()->isRecord()) {
4836         // If CurContext is a DeclContext that can contain statements,
4837         // RecursiveASTVisitor won't visit the decls that
4838         // BuildAnonymousStructOrUnion() will put into CurContext.
4839         // Also store them here so that they can be part of the
4840         // DeclStmt that gets created in this case.
4841         // FIXME: Also return the IndirectFieldDecls created by
4842         // BuildAnonymousStructOr union, for the same reason?
4843         if (CurContext->isFunctionOrMethod())
4844           AnonRecord = Record;
4845         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4846                                            Context.getPrintingPolicy());
4847       }
4848 
4849       DeclaresAnything = false;
4850     }
4851   }
4852 
4853   // C11 6.7.2.1p2:
4854   //   A struct-declaration that does not declare an anonymous structure or
4855   //   anonymous union shall contain a struct-declarator-list.
4856   //
4857   // This rule also existed in C89 and C99; the grammar for struct-declaration
4858   // did not permit a struct-declaration without a struct-declarator-list.
4859   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4860       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4861     // Check for Microsoft C extension: anonymous struct/union member.
4862     // Handle 2 kinds of anonymous struct/union:
4863     //   struct STRUCT;
4864     //   union UNION;
4865     // and
4866     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4867     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4868     if ((Tag && Tag->getDeclName()) ||
4869         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4870       RecordDecl *Record = nullptr;
4871       if (Tag)
4872         Record = dyn_cast<RecordDecl>(Tag);
4873       else if (const RecordType *RT =
4874                    DS.getRepAsType().get()->getAsStructureType())
4875         Record = RT->getDecl();
4876       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4877         Record = UT->getDecl();
4878 
4879       if (Record && getLangOpts().MicrosoftExt) {
4880         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4881             << Record->isUnion() << DS.getSourceRange();
4882         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4883       }
4884 
4885       DeclaresAnything = false;
4886     }
4887   }
4888 
4889   // Skip all the checks below if we have a type error.
4890   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4891       (TagD && TagD->isInvalidDecl()))
4892     return TagD;
4893 
4894   if (getLangOpts().CPlusPlus &&
4895       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4896     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4897       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4898           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4899         DeclaresAnything = false;
4900 
4901   if (!DS.isMissingDeclaratorOk()) {
4902     // Customize diagnostic for a typedef missing a name.
4903     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4904       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4905           << DS.getSourceRange();
4906     else
4907       DeclaresAnything = false;
4908   }
4909 
4910   if (DS.isModulePrivateSpecified() &&
4911       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4912     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4913       << Tag->getTagKind()
4914       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4915 
4916   ActOnDocumentableDecl(TagD);
4917 
4918   // C 6.7/2:
4919   //   A declaration [...] shall declare at least a declarator [...], a tag,
4920   //   or the members of an enumeration.
4921   // C++ [dcl.dcl]p3:
4922   //   [If there are no declarators], and except for the declaration of an
4923   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4924   //   names into the program, or shall redeclare a name introduced by a
4925   //   previous declaration.
4926   if (!DeclaresAnything) {
4927     // In C, we allow this as a (popular) extension / bug. Don't bother
4928     // producing further diagnostics for redundant qualifiers after this.
4929     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4930                                ? diag::err_no_declarators
4931                                : diag::ext_no_declarators)
4932         << DS.getSourceRange();
4933     return TagD;
4934   }
4935 
4936   // C++ [dcl.stc]p1:
4937   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4938   //   init-declarator-list of the declaration shall not be empty.
4939   // C++ [dcl.fct.spec]p1:
4940   //   If a cv-qualifier appears in a decl-specifier-seq, the
4941   //   init-declarator-list of the declaration shall not be empty.
4942   //
4943   // Spurious qualifiers here appear to be valid in C.
4944   unsigned DiagID = diag::warn_standalone_specifier;
4945   if (getLangOpts().CPlusPlus)
4946     DiagID = diag::ext_standalone_specifier;
4947 
4948   // Note that a linkage-specification sets a storage class, but
4949   // 'extern "C" struct foo;' is actually valid and not theoretically
4950   // useless.
4951   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4952     if (SCS == DeclSpec::SCS_mutable)
4953       // Since mutable is not a viable storage class specifier in C, there is
4954       // no reason to treat it as an extension. Instead, diagnose as an error.
4955       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4956     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4957       Diag(DS.getStorageClassSpecLoc(), DiagID)
4958         << DeclSpec::getSpecifierName(SCS);
4959   }
4960 
4961   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4962     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4963       << DeclSpec::getSpecifierName(TSCS);
4964   if (DS.getTypeQualifiers()) {
4965     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4966       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4967     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4968       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4969     // Restrict is covered above.
4970     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4971       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4972     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4973       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4974   }
4975 
4976   // Warn about ignored type attributes, for example:
4977   // __attribute__((aligned)) struct A;
4978   // Attributes should be placed after tag to apply to type declaration.
4979   if (!DS.getAttributes().empty()) {
4980     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4981     if (TypeSpecType == DeclSpec::TST_class ||
4982         TypeSpecType == DeclSpec::TST_struct ||
4983         TypeSpecType == DeclSpec::TST_interface ||
4984         TypeSpecType == DeclSpec::TST_union ||
4985         TypeSpecType == DeclSpec::TST_enum) {
4986       for (const ParsedAttr &AL : DS.getAttributes())
4987         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4988             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4989     }
4990   }
4991 
4992   return TagD;
4993 }
4994 
4995 /// We are trying to inject an anonymous member into the given scope;
4996 /// check if there's an existing declaration that can't be overloaded.
4997 ///
4998 /// \return true if this is a forbidden redeclaration
4999 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5000                                          Scope *S,
5001                                          DeclContext *Owner,
5002                                          DeclarationName Name,
5003                                          SourceLocation NameLoc,
5004                                          bool IsUnion) {
5005   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5006                  Sema::ForVisibleRedeclaration);
5007   if (!SemaRef.LookupName(R, S)) return false;
5008 
5009   // Pick a representative declaration.
5010   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5011   assert(PrevDecl && "Expected a non-null Decl");
5012 
5013   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5014     return false;
5015 
5016   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5017     << IsUnion << Name;
5018   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5019 
5020   return true;
5021 }
5022 
5023 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5024 /// anonymous struct or union AnonRecord into the owning context Owner
5025 /// and scope S. This routine will be invoked just after we realize
5026 /// that an unnamed union or struct is actually an anonymous union or
5027 /// struct, e.g.,
5028 ///
5029 /// @code
5030 /// union {
5031 ///   int i;
5032 ///   float f;
5033 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5034 ///    // f into the surrounding scope.x
5035 /// @endcode
5036 ///
5037 /// This routine is recursive, injecting the names of nested anonymous
5038 /// structs/unions into the owning context and scope as well.
5039 static bool
5040 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5041                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5042                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5043   bool Invalid = false;
5044 
5045   // Look every FieldDecl and IndirectFieldDecl with a name.
5046   for (auto *D : AnonRecord->decls()) {
5047     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5048         cast<NamedDecl>(D)->getDeclName()) {
5049       ValueDecl *VD = cast<ValueDecl>(D);
5050       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5051                                        VD->getLocation(),
5052                                        AnonRecord->isUnion())) {
5053         // C++ [class.union]p2:
5054         //   The names of the members of an anonymous union shall be
5055         //   distinct from the names of any other entity in the
5056         //   scope in which the anonymous union is declared.
5057         Invalid = true;
5058       } else {
5059         // C++ [class.union]p2:
5060         //   For the purpose of name lookup, after the anonymous union
5061         //   definition, the members of the anonymous union are
5062         //   considered to have been defined in the scope in which the
5063         //   anonymous union is declared.
5064         unsigned OldChainingSize = Chaining.size();
5065         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5066           Chaining.append(IF->chain_begin(), IF->chain_end());
5067         else
5068           Chaining.push_back(VD);
5069 
5070         assert(Chaining.size() >= 2);
5071         NamedDecl **NamedChain =
5072           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5073         for (unsigned i = 0; i < Chaining.size(); i++)
5074           NamedChain[i] = Chaining[i];
5075 
5076         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5077             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5078             VD->getType(), {NamedChain, Chaining.size()});
5079 
5080         for (const auto *Attr : VD->attrs())
5081           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5082 
5083         IndirectField->setAccess(AS);
5084         IndirectField->setImplicit();
5085         SemaRef.PushOnScopeChains(IndirectField, S);
5086 
5087         // That includes picking up the appropriate access specifier.
5088         if (AS != AS_none) IndirectField->setAccess(AS);
5089 
5090         Chaining.resize(OldChainingSize);
5091       }
5092     }
5093   }
5094 
5095   return Invalid;
5096 }
5097 
5098 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5099 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5100 /// illegal input values are mapped to SC_None.
5101 static StorageClass
5102 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5103   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5104   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5105          "Parser allowed 'typedef' as storage class VarDecl.");
5106   switch (StorageClassSpec) {
5107   case DeclSpec::SCS_unspecified:    return SC_None;
5108   case DeclSpec::SCS_extern:
5109     if (DS.isExternInLinkageSpec())
5110       return SC_None;
5111     return SC_Extern;
5112   case DeclSpec::SCS_static:         return SC_Static;
5113   case DeclSpec::SCS_auto:           return SC_Auto;
5114   case DeclSpec::SCS_register:       return SC_Register;
5115   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5116     // Illegal SCSs map to None: error reporting is up to the caller.
5117   case DeclSpec::SCS_mutable:        // Fall through.
5118   case DeclSpec::SCS_typedef:        return SC_None;
5119   }
5120   llvm_unreachable("unknown storage class specifier");
5121 }
5122 
5123 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5124   assert(Record->hasInClassInitializer());
5125 
5126   for (const auto *I : Record->decls()) {
5127     const auto *FD = dyn_cast<FieldDecl>(I);
5128     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5129       FD = IFD->getAnonField();
5130     if (FD && FD->hasInClassInitializer())
5131       return FD->getLocation();
5132   }
5133 
5134   llvm_unreachable("couldn't find in-class initializer");
5135 }
5136 
5137 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5138                                       SourceLocation DefaultInitLoc) {
5139   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5140     return;
5141 
5142   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5143   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5144 }
5145 
5146 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5147                                       CXXRecordDecl *AnonUnion) {
5148   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5149     return;
5150 
5151   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5152 }
5153 
5154 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5155 /// anonymous structure or union. Anonymous unions are a C++ feature
5156 /// (C++ [class.union]) and a C11 feature; anonymous structures
5157 /// are a C11 feature and GNU C++ extension.
5158 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5159                                         AccessSpecifier AS,
5160                                         RecordDecl *Record,
5161                                         const PrintingPolicy &Policy) {
5162   DeclContext *Owner = Record->getDeclContext();
5163 
5164   // Diagnose whether this anonymous struct/union is an extension.
5165   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5166     Diag(Record->getLocation(), diag::ext_anonymous_union);
5167   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5168     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5169   else if (!Record->isUnion() && !getLangOpts().C11)
5170     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5171 
5172   // C and C++ require different kinds of checks for anonymous
5173   // structs/unions.
5174   bool Invalid = false;
5175   if (getLangOpts().CPlusPlus) {
5176     const char *PrevSpec = nullptr;
5177     if (Record->isUnion()) {
5178       // C++ [class.union]p6:
5179       // C++17 [class.union.anon]p2:
5180       //   Anonymous unions declared in a named namespace or in the
5181       //   global namespace shall be declared static.
5182       unsigned DiagID;
5183       DeclContext *OwnerScope = Owner->getRedeclContext();
5184       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5185           (OwnerScope->isTranslationUnit() ||
5186            (OwnerScope->isNamespace() &&
5187             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5188         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5189           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5190 
5191         // Recover by adding 'static'.
5192         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5193                                PrevSpec, DiagID, Policy);
5194       }
5195       // C++ [class.union]p6:
5196       //   A storage class is not allowed in a declaration of an
5197       //   anonymous union in a class scope.
5198       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5199                isa<RecordDecl>(Owner)) {
5200         Diag(DS.getStorageClassSpecLoc(),
5201              diag::err_anonymous_union_with_storage_spec)
5202           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5203 
5204         // Recover by removing the storage specifier.
5205         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5206                                SourceLocation(),
5207                                PrevSpec, DiagID, Context.getPrintingPolicy());
5208       }
5209     }
5210 
5211     // Ignore const/volatile/restrict qualifiers.
5212     if (DS.getTypeQualifiers()) {
5213       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5214         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5215           << Record->isUnion() << "const"
5216           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5217       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5218         Diag(DS.getVolatileSpecLoc(),
5219              diag::ext_anonymous_struct_union_qualified)
5220           << Record->isUnion() << "volatile"
5221           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5222       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5223         Diag(DS.getRestrictSpecLoc(),
5224              diag::ext_anonymous_struct_union_qualified)
5225           << Record->isUnion() << "restrict"
5226           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5227       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5228         Diag(DS.getAtomicSpecLoc(),
5229              diag::ext_anonymous_struct_union_qualified)
5230           << Record->isUnion() << "_Atomic"
5231           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5232       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5233         Diag(DS.getUnalignedSpecLoc(),
5234              diag::ext_anonymous_struct_union_qualified)
5235           << Record->isUnion() << "__unaligned"
5236           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5237 
5238       DS.ClearTypeQualifiers();
5239     }
5240 
5241     // C++ [class.union]p2:
5242     //   The member-specification of an anonymous union shall only
5243     //   define non-static data members. [Note: nested types and
5244     //   functions cannot be declared within an anonymous union. ]
5245     for (auto *Mem : Record->decls()) {
5246       // Ignore invalid declarations; we already diagnosed them.
5247       if (Mem->isInvalidDecl())
5248         continue;
5249 
5250       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5251         // C++ [class.union]p3:
5252         //   An anonymous union shall not have private or protected
5253         //   members (clause 11).
5254         assert(FD->getAccess() != AS_none);
5255         if (FD->getAccess() != AS_public) {
5256           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5257             << Record->isUnion() << (FD->getAccess() == AS_protected);
5258           Invalid = true;
5259         }
5260 
5261         // C++ [class.union]p1
5262         //   An object of a class with a non-trivial constructor, a non-trivial
5263         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5264         //   assignment operator cannot be a member of a union, nor can an
5265         //   array of such objects.
5266         if (CheckNontrivialField(FD))
5267           Invalid = true;
5268       } else if (Mem->isImplicit()) {
5269         // Any implicit members are fine.
5270       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5271         // This is a type that showed up in an
5272         // elaborated-type-specifier inside the anonymous struct or
5273         // union, but which actually declares a type outside of the
5274         // anonymous struct or union. It's okay.
5275       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5276         if (!MemRecord->isAnonymousStructOrUnion() &&
5277             MemRecord->getDeclName()) {
5278           // Visual C++ allows type definition in anonymous struct or union.
5279           if (getLangOpts().MicrosoftExt)
5280             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5281               << Record->isUnion();
5282           else {
5283             // This is a nested type declaration.
5284             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5285               << Record->isUnion();
5286             Invalid = true;
5287           }
5288         } else {
5289           // This is an anonymous type definition within another anonymous type.
5290           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5291           // not part of standard C++.
5292           Diag(MemRecord->getLocation(),
5293                diag::ext_anonymous_record_with_anonymous_type)
5294             << Record->isUnion();
5295         }
5296       } else if (isa<AccessSpecDecl>(Mem)) {
5297         // Any access specifier is fine.
5298       } else if (isa<StaticAssertDecl>(Mem)) {
5299         // In C++1z, static_assert declarations are also fine.
5300       } else {
5301         // We have something that isn't a non-static data
5302         // member. Complain about it.
5303         unsigned DK = diag::err_anonymous_record_bad_member;
5304         if (isa<TypeDecl>(Mem))
5305           DK = diag::err_anonymous_record_with_type;
5306         else if (isa<FunctionDecl>(Mem))
5307           DK = diag::err_anonymous_record_with_function;
5308         else if (isa<VarDecl>(Mem))
5309           DK = diag::err_anonymous_record_with_static;
5310 
5311         // Visual C++ allows type definition in anonymous struct or union.
5312         if (getLangOpts().MicrosoftExt &&
5313             DK == diag::err_anonymous_record_with_type)
5314           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5315             << Record->isUnion();
5316         else {
5317           Diag(Mem->getLocation(), DK) << Record->isUnion();
5318           Invalid = true;
5319         }
5320       }
5321     }
5322 
5323     // C++11 [class.union]p8 (DR1460):
5324     //   At most one variant member of a union may have a
5325     //   brace-or-equal-initializer.
5326     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5327         Owner->isRecord())
5328       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5329                                 cast<CXXRecordDecl>(Record));
5330   }
5331 
5332   if (!Record->isUnion() && !Owner->isRecord()) {
5333     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5334       << getLangOpts().CPlusPlus;
5335     Invalid = true;
5336   }
5337 
5338   // C++ [dcl.dcl]p3:
5339   //   [If there are no declarators], and except for the declaration of an
5340   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5341   //   names into the program
5342   // C++ [class.mem]p2:
5343   //   each such member-declaration shall either declare at least one member
5344   //   name of the class or declare at least one unnamed bit-field
5345   //
5346   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5347   if (getLangOpts().CPlusPlus && Record->field_empty())
5348     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5349 
5350   // Mock up a declarator.
5351   Declarator Dc(DS, DeclaratorContext::Member);
5352   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5353   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5354 
5355   // Create a declaration for this anonymous struct/union.
5356   NamedDecl *Anon = nullptr;
5357   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5358     Anon = FieldDecl::Create(
5359         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5360         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5361         /*BitWidth=*/nullptr, /*Mutable=*/false,
5362         /*InitStyle=*/ICIS_NoInit);
5363     Anon->setAccess(AS);
5364     ProcessDeclAttributes(S, Anon, Dc);
5365 
5366     if (getLangOpts().CPlusPlus)
5367       FieldCollector->Add(cast<FieldDecl>(Anon));
5368   } else {
5369     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5370     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5371     if (SCSpec == DeclSpec::SCS_mutable) {
5372       // mutable can only appear on non-static class members, so it's always
5373       // an error here
5374       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5375       Invalid = true;
5376       SC = SC_None;
5377     }
5378 
5379     assert(DS.getAttributes().empty() && "No attribute expected");
5380     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5381                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5382                            Context.getTypeDeclType(Record), TInfo, SC);
5383 
5384     // Default-initialize the implicit variable. This initialization will be
5385     // trivial in almost all cases, except if a union member has an in-class
5386     // initializer:
5387     //   union { int n = 0; };
5388     ActOnUninitializedDecl(Anon);
5389   }
5390   Anon->setImplicit();
5391 
5392   // Mark this as an anonymous struct/union type.
5393   Record->setAnonymousStructOrUnion(true);
5394 
5395   // Add the anonymous struct/union object to the current
5396   // context. We'll be referencing this object when we refer to one of
5397   // its members.
5398   Owner->addDecl(Anon);
5399 
5400   // Inject the members of the anonymous struct/union into the owning
5401   // context and into the identifier resolver chain for name lookup
5402   // purposes.
5403   SmallVector<NamedDecl*, 2> Chain;
5404   Chain.push_back(Anon);
5405 
5406   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5407     Invalid = true;
5408 
5409   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5410     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5411       MangleNumberingContext *MCtx;
5412       Decl *ManglingContextDecl;
5413       std::tie(MCtx, ManglingContextDecl) =
5414           getCurrentMangleNumberContext(NewVD->getDeclContext());
5415       if (MCtx) {
5416         Context.setManglingNumber(
5417             NewVD, MCtx->getManglingNumber(
5418                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5419         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5420       }
5421     }
5422   }
5423 
5424   if (Invalid)
5425     Anon->setInvalidDecl();
5426 
5427   return Anon;
5428 }
5429 
5430 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5431 /// Microsoft C anonymous structure.
5432 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5433 /// Example:
5434 ///
5435 /// struct A { int a; };
5436 /// struct B { struct A; int b; };
5437 ///
5438 /// void foo() {
5439 ///   B var;
5440 ///   var.a = 3;
5441 /// }
5442 ///
5443 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5444                                            RecordDecl *Record) {
5445   assert(Record && "expected a record!");
5446 
5447   // Mock up a declarator.
5448   Declarator Dc(DS, DeclaratorContext::TypeName);
5449   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5450   assert(TInfo && "couldn't build declarator info for anonymous struct");
5451 
5452   auto *ParentDecl = cast<RecordDecl>(CurContext);
5453   QualType RecTy = Context.getTypeDeclType(Record);
5454 
5455   // Create a declaration for this anonymous struct.
5456   NamedDecl *Anon =
5457       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5458                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5459                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5460                         /*InitStyle=*/ICIS_NoInit);
5461   Anon->setImplicit();
5462 
5463   // Add the anonymous struct object to the current context.
5464   CurContext->addDecl(Anon);
5465 
5466   // Inject the members of the anonymous struct into the current
5467   // context and into the identifier resolver chain for name lookup
5468   // purposes.
5469   SmallVector<NamedDecl*, 2> Chain;
5470   Chain.push_back(Anon);
5471 
5472   RecordDecl *RecordDef = Record->getDefinition();
5473   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5474                                diag::err_field_incomplete_or_sizeless) ||
5475       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5476                                           AS_none, Chain)) {
5477     Anon->setInvalidDecl();
5478     ParentDecl->setInvalidDecl();
5479   }
5480 
5481   return Anon;
5482 }
5483 
5484 /// GetNameForDeclarator - Determine the full declaration name for the
5485 /// given Declarator.
5486 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5487   return GetNameFromUnqualifiedId(D.getName());
5488 }
5489 
5490 /// Retrieves the declaration name from a parsed unqualified-id.
5491 DeclarationNameInfo
5492 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5493   DeclarationNameInfo NameInfo;
5494   NameInfo.setLoc(Name.StartLocation);
5495 
5496   switch (Name.getKind()) {
5497 
5498   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5499   case UnqualifiedIdKind::IK_Identifier:
5500     NameInfo.setName(Name.Identifier);
5501     return NameInfo;
5502 
5503   case UnqualifiedIdKind::IK_DeductionGuideName: {
5504     // C++ [temp.deduct.guide]p3:
5505     //   The simple-template-id shall name a class template specialization.
5506     //   The template-name shall be the same identifier as the template-name
5507     //   of the simple-template-id.
5508     // These together intend to imply that the template-name shall name a
5509     // class template.
5510     // FIXME: template<typename T> struct X {};
5511     //        template<typename T> using Y = X<T>;
5512     //        Y(int) -> Y<int>;
5513     //   satisfies these rules but does not name a class template.
5514     TemplateName TN = Name.TemplateName.get().get();
5515     auto *Template = TN.getAsTemplateDecl();
5516     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5517       Diag(Name.StartLocation,
5518            diag::err_deduction_guide_name_not_class_template)
5519         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5520       if (Template)
5521         Diag(Template->getLocation(), diag::note_template_decl_here);
5522       return DeclarationNameInfo();
5523     }
5524 
5525     NameInfo.setName(
5526         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5527     return NameInfo;
5528   }
5529 
5530   case UnqualifiedIdKind::IK_OperatorFunctionId:
5531     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5532                                            Name.OperatorFunctionId.Operator));
5533     NameInfo.setCXXOperatorNameRange(SourceRange(
5534         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5535     return NameInfo;
5536 
5537   case UnqualifiedIdKind::IK_LiteralOperatorId:
5538     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5539                                                            Name.Identifier));
5540     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5541     return NameInfo;
5542 
5543   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5544     TypeSourceInfo *TInfo;
5545     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5546     if (Ty.isNull())
5547       return DeclarationNameInfo();
5548     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5549                                                Context.getCanonicalType(Ty)));
5550     NameInfo.setNamedTypeInfo(TInfo);
5551     return NameInfo;
5552   }
5553 
5554   case UnqualifiedIdKind::IK_ConstructorName: {
5555     TypeSourceInfo *TInfo;
5556     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5557     if (Ty.isNull())
5558       return DeclarationNameInfo();
5559     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5560                                               Context.getCanonicalType(Ty)));
5561     NameInfo.setNamedTypeInfo(TInfo);
5562     return NameInfo;
5563   }
5564 
5565   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5566     // In well-formed code, we can only have a constructor
5567     // template-id that refers to the current context, so go there
5568     // to find the actual type being constructed.
5569     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5570     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5571       return DeclarationNameInfo();
5572 
5573     // Determine the type of the class being constructed.
5574     QualType CurClassType = Context.getTypeDeclType(CurClass);
5575 
5576     // FIXME: Check two things: that the template-id names the same type as
5577     // CurClassType, and that the template-id does not occur when the name
5578     // was qualified.
5579 
5580     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5581                                     Context.getCanonicalType(CurClassType)));
5582     // FIXME: should we retrieve TypeSourceInfo?
5583     NameInfo.setNamedTypeInfo(nullptr);
5584     return NameInfo;
5585   }
5586 
5587   case UnqualifiedIdKind::IK_DestructorName: {
5588     TypeSourceInfo *TInfo;
5589     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5590     if (Ty.isNull())
5591       return DeclarationNameInfo();
5592     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5593                                               Context.getCanonicalType(Ty)));
5594     NameInfo.setNamedTypeInfo(TInfo);
5595     return NameInfo;
5596   }
5597 
5598   case UnqualifiedIdKind::IK_TemplateId: {
5599     TemplateName TName = Name.TemplateId->Template.get();
5600     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5601     return Context.getNameForTemplate(TName, TNameLoc);
5602   }
5603 
5604   } // switch (Name.getKind())
5605 
5606   llvm_unreachable("Unknown name kind");
5607 }
5608 
5609 static QualType getCoreType(QualType Ty) {
5610   do {
5611     if (Ty->isPointerType() || Ty->isReferenceType())
5612       Ty = Ty->getPointeeType();
5613     else if (Ty->isArrayType())
5614       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5615     else
5616       return Ty.withoutLocalFastQualifiers();
5617   } while (true);
5618 }
5619 
5620 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5621 /// and Definition have "nearly" matching parameters. This heuristic is
5622 /// used to improve diagnostics in the case where an out-of-line function
5623 /// definition doesn't match any declaration within the class or namespace.
5624 /// Also sets Params to the list of indices to the parameters that differ
5625 /// between the declaration and the definition. If hasSimilarParameters
5626 /// returns true and Params is empty, then all of the parameters match.
5627 static bool hasSimilarParameters(ASTContext &Context,
5628                                      FunctionDecl *Declaration,
5629                                      FunctionDecl *Definition,
5630                                      SmallVectorImpl<unsigned> &Params) {
5631   Params.clear();
5632   if (Declaration->param_size() != Definition->param_size())
5633     return false;
5634   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5635     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5636     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5637 
5638     // The parameter types are identical
5639     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5640       continue;
5641 
5642     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5643     QualType DefParamBaseTy = getCoreType(DefParamTy);
5644     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5645     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5646 
5647     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5648         (DeclTyName && DeclTyName == DefTyName))
5649       Params.push_back(Idx);
5650     else  // The two parameters aren't even close
5651       return false;
5652   }
5653 
5654   return true;
5655 }
5656 
5657 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5658 /// declarator needs to be rebuilt in the current instantiation.
5659 /// Any bits of declarator which appear before the name are valid for
5660 /// consideration here.  That's specifically the type in the decl spec
5661 /// and the base type in any member-pointer chunks.
5662 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5663                                                     DeclarationName Name) {
5664   // The types we specifically need to rebuild are:
5665   //   - typenames, typeofs, and decltypes
5666   //   - types which will become injected class names
5667   // Of course, we also need to rebuild any type referencing such a
5668   // type.  It's safest to just say "dependent", but we call out a
5669   // few cases here.
5670 
5671   DeclSpec &DS = D.getMutableDeclSpec();
5672   switch (DS.getTypeSpecType()) {
5673   case DeclSpec::TST_typename:
5674   case DeclSpec::TST_typeofType:
5675   case DeclSpec::TST_underlyingType:
5676   case DeclSpec::TST_atomic: {
5677     // Grab the type from the parser.
5678     TypeSourceInfo *TSI = nullptr;
5679     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5680     if (T.isNull() || !T->isInstantiationDependentType()) break;
5681 
5682     // Make sure there's a type source info.  This isn't really much
5683     // of a waste; most dependent types should have type source info
5684     // attached already.
5685     if (!TSI)
5686       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5687 
5688     // Rebuild the type in the current instantiation.
5689     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5690     if (!TSI) return true;
5691 
5692     // Store the new type back in the decl spec.
5693     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5694     DS.UpdateTypeRep(LocType);
5695     break;
5696   }
5697 
5698   case DeclSpec::TST_decltype:
5699   case DeclSpec::TST_typeofExpr: {
5700     Expr *E = DS.getRepAsExpr();
5701     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5702     if (Result.isInvalid()) return true;
5703     DS.UpdateExprRep(Result.get());
5704     break;
5705   }
5706 
5707   default:
5708     // Nothing to do for these decl specs.
5709     break;
5710   }
5711 
5712   // It doesn't matter what order we do this in.
5713   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5714     DeclaratorChunk &Chunk = D.getTypeObject(I);
5715 
5716     // The only type information in the declarator which can come
5717     // before the declaration name is the base type of a member
5718     // pointer.
5719     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5720       continue;
5721 
5722     // Rebuild the scope specifier in-place.
5723     CXXScopeSpec &SS = Chunk.Mem.Scope();
5724     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5725       return true;
5726   }
5727 
5728   return false;
5729 }
5730 
5731 /// Returns true if the declaration is declared in a system header or from a
5732 /// system macro.
5733 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5734   return SM.isInSystemHeader(D->getLocation()) ||
5735          SM.isInSystemMacro(D->getLocation());
5736 }
5737 
5738 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5739   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5740   // of system decl.
5741   if (D->getPreviousDecl() || D->isImplicit())
5742     return;
5743   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5744   if (Status != ReservedIdentifierStatus::NotReserved &&
5745       !isFromSystemHeader(Context.getSourceManager(), D)) {
5746     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5747         << D << static_cast<int>(Status);
5748   }
5749 }
5750 
5751 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5752   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5753   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5754 
5755   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5756       Dcl && Dcl->getDeclContext()->isFileContext())
5757     Dcl->setTopLevelDeclInObjCContainer();
5758 
5759   return Dcl;
5760 }
5761 
5762 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5763 ///   If T is the name of a class, then each of the following shall have a
5764 ///   name different from T:
5765 ///     - every static data member of class T;
5766 ///     - every member function of class T
5767 ///     - every member of class T that is itself a type;
5768 /// \returns true if the declaration name violates these rules.
5769 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5770                                    DeclarationNameInfo NameInfo) {
5771   DeclarationName Name = NameInfo.getName();
5772 
5773   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5774   while (Record && Record->isAnonymousStructOrUnion())
5775     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5776   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5777     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5778     return true;
5779   }
5780 
5781   return false;
5782 }
5783 
5784 /// Diagnose a declaration whose declarator-id has the given
5785 /// nested-name-specifier.
5786 ///
5787 /// \param SS The nested-name-specifier of the declarator-id.
5788 ///
5789 /// \param DC The declaration context to which the nested-name-specifier
5790 /// resolves.
5791 ///
5792 /// \param Name The name of the entity being declared.
5793 ///
5794 /// \param Loc The location of the name of the entity being declared.
5795 ///
5796 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5797 /// we're declaring an explicit / partial specialization / instantiation.
5798 ///
5799 /// \returns true if we cannot safely recover from this error, false otherwise.
5800 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5801                                         DeclarationName Name,
5802                                         SourceLocation Loc, bool IsTemplateId) {
5803   DeclContext *Cur = CurContext;
5804   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5805     Cur = Cur->getParent();
5806 
5807   // If the user provided a superfluous scope specifier that refers back to the
5808   // class in which the entity is already declared, diagnose and ignore it.
5809   //
5810   // class X {
5811   //   void X::f();
5812   // };
5813   //
5814   // Note, it was once ill-formed to give redundant qualification in all
5815   // contexts, but that rule was removed by DR482.
5816   if (Cur->Equals(DC)) {
5817     if (Cur->isRecord()) {
5818       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5819                                       : diag::err_member_extra_qualification)
5820         << Name << FixItHint::CreateRemoval(SS.getRange());
5821       SS.clear();
5822     } else {
5823       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5824     }
5825     return false;
5826   }
5827 
5828   // Check whether the qualifying scope encloses the scope of the original
5829   // declaration. For a template-id, we perform the checks in
5830   // CheckTemplateSpecializationScope.
5831   if (!Cur->Encloses(DC) && !IsTemplateId) {
5832     if (Cur->isRecord())
5833       Diag(Loc, diag::err_member_qualification)
5834         << Name << SS.getRange();
5835     else if (isa<TranslationUnitDecl>(DC))
5836       Diag(Loc, diag::err_invalid_declarator_global_scope)
5837         << Name << SS.getRange();
5838     else if (isa<FunctionDecl>(Cur))
5839       Diag(Loc, diag::err_invalid_declarator_in_function)
5840         << Name << SS.getRange();
5841     else if (isa<BlockDecl>(Cur))
5842       Diag(Loc, diag::err_invalid_declarator_in_block)
5843         << Name << SS.getRange();
5844     else if (isa<ExportDecl>(Cur)) {
5845       if (!isa<NamespaceDecl>(DC))
5846         Diag(Loc, diag::err_export_non_namespace_scope_name)
5847             << Name << SS.getRange();
5848       else
5849         // The cases that DC is not NamespaceDecl should be handled in
5850         // CheckRedeclarationExported.
5851         return false;
5852     } else
5853       Diag(Loc, diag::err_invalid_declarator_scope)
5854       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5855 
5856     return true;
5857   }
5858 
5859   if (Cur->isRecord()) {
5860     // Cannot qualify members within a class.
5861     Diag(Loc, diag::err_member_qualification)
5862       << Name << SS.getRange();
5863     SS.clear();
5864 
5865     // C++ constructors and destructors with incorrect scopes can break
5866     // our AST invariants by having the wrong underlying types. If
5867     // that's the case, then drop this declaration entirely.
5868     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5869          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5870         !Context.hasSameType(Name.getCXXNameType(),
5871                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5872       return true;
5873 
5874     return false;
5875   }
5876 
5877   // C++11 [dcl.meaning]p1:
5878   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5879   //   not begin with a decltype-specifer"
5880   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5881   while (SpecLoc.getPrefix())
5882     SpecLoc = SpecLoc.getPrefix();
5883   if (isa_and_nonnull<DecltypeType>(
5884           SpecLoc.getNestedNameSpecifier()->getAsType()))
5885     Diag(Loc, diag::err_decltype_in_declarator)
5886       << SpecLoc.getTypeLoc().getSourceRange();
5887 
5888   return false;
5889 }
5890 
5891 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5892                                   MultiTemplateParamsArg TemplateParamLists) {
5893   // TODO: consider using NameInfo for diagnostic.
5894   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5895   DeclarationName Name = NameInfo.getName();
5896 
5897   // All of these full declarators require an identifier.  If it doesn't have
5898   // one, the ParsedFreeStandingDeclSpec action should be used.
5899   if (D.isDecompositionDeclarator()) {
5900     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5901   } else if (!Name) {
5902     if (!D.isInvalidType())  // Reject this if we think it is valid.
5903       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5904           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5905     return nullptr;
5906   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5907     return nullptr;
5908 
5909   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5910   // we find one that is.
5911   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5912          (S->getFlags() & Scope::TemplateParamScope) != 0)
5913     S = S->getParent();
5914 
5915   DeclContext *DC = CurContext;
5916   if (D.getCXXScopeSpec().isInvalid())
5917     D.setInvalidType();
5918   else if (D.getCXXScopeSpec().isSet()) {
5919     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5920                                         UPPC_DeclarationQualifier))
5921       return nullptr;
5922 
5923     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5924     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5925     if (!DC || isa<EnumDecl>(DC)) {
5926       // If we could not compute the declaration context, it's because the
5927       // declaration context is dependent but does not refer to a class,
5928       // class template, or class template partial specialization. Complain
5929       // and return early, to avoid the coming semantic disaster.
5930       Diag(D.getIdentifierLoc(),
5931            diag::err_template_qualified_declarator_no_match)
5932         << D.getCXXScopeSpec().getScopeRep()
5933         << D.getCXXScopeSpec().getRange();
5934       return nullptr;
5935     }
5936     bool IsDependentContext = DC->isDependentContext();
5937 
5938     if (!IsDependentContext &&
5939         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5940       return nullptr;
5941 
5942     // If a class is incomplete, do not parse entities inside it.
5943     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5944       Diag(D.getIdentifierLoc(),
5945            diag::err_member_def_undefined_record)
5946         << Name << DC << D.getCXXScopeSpec().getRange();
5947       return nullptr;
5948     }
5949     if (!D.getDeclSpec().isFriendSpecified()) {
5950       if (diagnoseQualifiedDeclaration(
5951               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5952               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5953         if (DC->isRecord())
5954           return nullptr;
5955 
5956         D.setInvalidType();
5957       }
5958     }
5959 
5960     // Check whether we need to rebuild the type of the given
5961     // declaration in the current instantiation.
5962     if (EnteringContext && IsDependentContext &&
5963         TemplateParamLists.size() != 0) {
5964       ContextRAII SavedContext(*this, DC);
5965       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5966         D.setInvalidType();
5967     }
5968   }
5969 
5970   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5971   QualType R = TInfo->getType();
5972 
5973   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5974                                       UPPC_DeclarationType))
5975     D.setInvalidType();
5976 
5977   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5978                         forRedeclarationInCurContext());
5979 
5980   // See if this is a redefinition of a variable in the same scope.
5981   if (!D.getCXXScopeSpec().isSet()) {
5982     bool IsLinkageLookup = false;
5983     bool CreateBuiltins = false;
5984 
5985     // If the declaration we're planning to build will be a function
5986     // or object with linkage, then look for another declaration with
5987     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5988     //
5989     // If the declaration we're planning to build will be declared with
5990     // external linkage in the translation unit, create any builtin with
5991     // the same name.
5992     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5993       /* Do nothing*/;
5994     else if (CurContext->isFunctionOrMethod() &&
5995              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5996               R->isFunctionType())) {
5997       IsLinkageLookup = true;
5998       CreateBuiltins =
5999           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6000     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6001                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6002       CreateBuiltins = true;
6003 
6004     if (IsLinkageLookup) {
6005       Previous.clear(LookupRedeclarationWithLinkage);
6006       Previous.setRedeclarationKind(ForExternalRedeclaration);
6007     }
6008 
6009     LookupName(Previous, S, CreateBuiltins);
6010   } else { // Something like "int foo::x;"
6011     LookupQualifiedName(Previous, DC);
6012 
6013     // C++ [dcl.meaning]p1:
6014     //   When the declarator-id is qualified, the declaration shall refer to a
6015     //  previously declared member of the class or namespace to which the
6016     //  qualifier refers (or, in the case of a namespace, of an element of the
6017     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6018     //  thereof; [...]
6019     //
6020     // Note that we already checked the context above, and that we do not have
6021     // enough information to make sure that Previous contains the declaration
6022     // we want to match. For example, given:
6023     //
6024     //   class X {
6025     //     void f();
6026     //     void f(float);
6027     //   };
6028     //
6029     //   void X::f(int) { } // ill-formed
6030     //
6031     // In this case, Previous will point to the overload set
6032     // containing the two f's declared in X, but neither of them
6033     // matches.
6034 
6035     // C++ [dcl.meaning]p1:
6036     //   [...] the member shall not merely have been introduced by a
6037     //   using-declaration in the scope of the class or namespace nominated by
6038     //   the nested-name-specifier of the declarator-id.
6039     RemoveUsingDecls(Previous);
6040   }
6041 
6042   if (Previous.isSingleResult() &&
6043       Previous.getFoundDecl()->isTemplateParameter()) {
6044     // Maybe we will complain about the shadowed template parameter.
6045     if (!D.isInvalidType())
6046       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6047                                       Previous.getFoundDecl());
6048 
6049     // Just pretend that we didn't see the previous declaration.
6050     Previous.clear();
6051   }
6052 
6053   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6054     // Forget that the previous declaration is the injected-class-name.
6055     Previous.clear();
6056 
6057   // In C++, the previous declaration we find might be a tag type
6058   // (class or enum). In this case, the new declaration will hide the
6059   // tag type. Note that this applies to functions, function templates, and
6060   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6061   if (Previous.isSingleTagDecl() &&
6062       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6063       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6064     Previous.clear();
6065 
6066   // Check that there are no default arguments other than in the parameters
6067   // of a function declaration (C++ only).
6068   if (getLangOpts().CPlusPlus)
6069     CheckExtraCXXDefaultArguments(D);
6070 
6071   NamedDecl *New;
6072 
6073   bool AddToScope = true;
6074   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6075     if (TemplateParamLists.size()) {
6076       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6077       return nullptr;
6078     }
6079 
6080     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6081   } else if (R->isFunctionType()) {
6082     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6083                                   TemplateParamLists,
6084                                   AddToScope);
6085   } else {
6086     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6087                                   AddToScope);
6088   }
6089 
6090   if (!New)
6091     return nullptr;
6092 
6093   // If this has an identifier and is not a function template specialization,
6094   // add it to the scope stack.
6095   if (New->getDeclName() && AddToScope)
6096     PushOnScopeChains(New, S);
6097 
6098   if (isInOpenMPDeclareTargetContext())
6099     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6100 
6101   return New;
6102 }
6103 
6104 /// Helper method to turn variable array types into constant array
6105 /// types in certain situations which would otherwise be errors (for
6106 /// GCC compatibility).
6107 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6108                                                     ASTContext &Context,
6109                                                     bool &SizeIsNegative,
6110                                                     llvm::APSInt &Oversized) {
6111   // This method tries to turn a variable array into a constant
6112   // array even when the size isn't an ICE.  This is necessary
6113   // for compatibility with code that depends on gcc's buggy
6114   // constant expression folding, like struct {char x[(int)(char*)2];}
6115   SizeIsNegative = false;
6116   Oversized = 0;
6117 
6118   if (T->isDependentType())
6119     return QualType();
6120 
6121   QualifierCollector Qs;
6122   const Type *Ty = Qs.strip(T);
6123 
6124   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6125     QualType Pointee = PTy->getPointeeType();
6126     QualType FixedType =
6127         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6128                                             Oversized);
6129     if (FixedType.isNull()) return FixedType;
6130     FixedType = Context.getPointerType(FixedType);
6131     return Qs.apply(Context, FixedType);
6132   }
6133   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6134     QualType Inner = PTy->getInnerType();
6135     QualType FixedType =
6136         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6137                                             Oversized);
6138     if (FixedType.isNull()) return FixedType;
6139     FixedType = Context.getParenType(FixedType);
6140     return Qs.apply(Context, FixedType);
6141   }
6142 
6143   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6144   if (!VLATy)
6145     return QualType();
6146 
6147   QualType ElemTy = VLATy->getElementType();
6148   if (ElemTy->isVariablyModifiedType()) {
6149     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6150                                                  SizeIsNegative, Oversized);
6151     if (ElemTy.isNull())
6152       return QualType();
6153   }
6154 
6155   Expr::EvalResult Result;
6156   if (!VLATy->getSizeExpr() ||
6157       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6158     return QualType();
6159 
6160   llvm::APSInt Res = Result.Val.getInt();
6161 
6162   // Check whether the array size is negative.
6163   if (Res.isSigned() && Res.isNegative()) {
6164     SizeIsNegative = true;
6165     return QualType();
6166   }
6167 
6168   // Check whether the array is too large to be addressed.
6169   unsigned ActiveSizeBits =
6170       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6171        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6172           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6173           : Res.getActiveBits();
6174   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6175     Oversized = Res;
6176     return QualType();
6177   }
6178 
6179   QualType FoldedArrayType = Context.getConstantArrayType(
6180       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6181   return Qs.apply(Context, FoldedArrayType);
6182 }
6183 
6184 static void
6185 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6186   SrcTL = SrcTL.getUnqualifiedLoc();
6187   DstTL = DstTL.getUnqualifiedLoc();
6188   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6189     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6190     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6191                                       DstPTL.getPointeeLoc());
6192     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6193     return;
6194   }
6195   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6196     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6197     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6198                                       DstPTL.getInnerLoc());
6199     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6200     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6201     return;
6202   }
6203   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6204   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6205   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6206   TypeLoc DstElemTL = DstATL.getElementLoc();
6207   if (VariableArrayTypeLoc SrcElemATL =
6208           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6209     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6210     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6211   } else {
6212     DstElemTL.initializeFullCopy(SrcElemTL);
6213   }
6214   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6215   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6216   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6217 }
6218 
6219 /// Helper method to turn variable array types into constant array
6220 /// types in certain situations which would otherwise be errors (for
6221 /// GCC compatibility).
6222 static TypeSourceInfo*
6223 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6224                                               ASTContext &Context,
6225                                               bool &SizeIsNegative,
6226                                               llvm::APSInt &Oversized) {
6227   QualType FixedTy
6228     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6229                                           SizeIsNegative, Oversized);
6230   if (FixedTy.isNull())
6231     return nullptr;
6232   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6233   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6234                                     FixedTInfo->getTypeLoc());
6235   return FixedTInfo;
6236 }
6237 
6238 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6239 /// true if we were successful.
6240 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6241                                            QualType &T, SourceLocation Loc,
6242                                            unsigned FailedFoldDiagID) {
6243   bool SizeIsNegative;
6244   llvm::APSInt Oversized;
6245   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6246       TInfo, Context, SizeIsNegative, Oversized);
6247   if (FixedTInfo) {
6248     Diag(Loc, diag::ext_vla_folded_to_constant);
6249     TInfo = FixedTInfo;
6250     T = FixedTInfo->getType();
6251     return true;
6252   }
6253 
6254   if (SizeIsNegative)
6255     Diag(Loc, diag::err_typecheck_negative_array_size);
6256   else if (Oversized.getBoolValue())
6257     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6258   else if (FailedFoldDiagID)
6259     Diag(Loc, FailedFoldDiagID);
6260   return false;
6261 }
6262 
6263 /// Register the given locally-scoped extern "C" declaration so
6264 /// that it can be found later for redeclarations. We include any extern "C"
6265 /// declaration that is not visible in the translation unit here, not just
6266 /// function-scope declarations.
6267 void
6268 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6269   if (!getLangOpts().CPlusPlus &&
6270       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6271     // Don't need to track declarations in the TU in C.
6272     return;
6273 
6274   // Note that we have a locally-scoped external with this name.
6275   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6276 }
6277 
6278 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6279   // FIXME: We can have multiple results via __attribute__((overloadable)).
6280   auto Result = Context.getExternCContextDecl()->lookup(Name);
6281   return Result.empty() ? nullptr : *Result.begin();
6282 }
6283 
6284 /// Diagnose function specifiers on a declaration of an identifier that
6285 /// does not identify a function.
6286 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6287   // FIXME: We should probably indicate the identifier in question to avoid
6288   // confusion for constructs like "virtual int a(), b;"
6289   if (DS.isVirtualSpecified())
6290     Diag(DS.getVirtualSpecLoc(),
6291          diag::err_virtual_non_function);
6292 
6293   if (DS.hasExplicitSpecifier())
6294     Diag(DS.getExplicitSpecLoc(),
6295          diag::err_explicit_non_function);
6296 
6297   if (DS.isNoreturnSpecified())
6298     Diag(DS.getNoreturnSpecLoc(),
6299          diag::err_noreturn_non_function);
6300 }
6301 
6302 NamedDecl*
6303 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6304                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6305   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6306   if (D.getCXXScopeSpec().isSet()) {
6307     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6308       << D.getCXXScopeSpec().getRange();
6309     D.setInvalidType();
6310     // Pretend we didn't see the scope specifier.
6311     DC = CurContext;
6312     Previous.clear();
6313   }
6314 
6315   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6316 
6317   if (D.getDeclSpec().isInlineSpecified())
6318     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6319         << getLangOpts().CPlusPlus17;
6320   if (D.getDeclSpec().hasConstexprSpecifier())
6321     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6322         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6323 
6324   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6325     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6326       Diag(D.getName().StartLocation,
6327            diag::err_deduction_guide_invalid_specifier)
6328           << "typedef";
6329     else
6330       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6331           << D.getName().getSourceRange();
6332     return nullptr;
6333   }
6334 
6335   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6336   if (!NewTD) return nullptr;
6337 
6338   // Handle attributes prior to checking for duplicates in MergeVarDecl
6339   ProcessDeclAttributes(S, NewTD, D);
6340 
6341   CheckTypedefForVariablyModifiedType(S, NewTD);
6342 
6343   bool Redeclaration = D.isRedeclaration();
6344   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6345   D.setRedeclaration(Redeclaration);
6346   return ND;
6347 }
6348 
6349 void
6350 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6351   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6352   // then it shall have block scope.
6353   // Note that variably modified types must be fixed before merging the decl so
6354   // that redeclarations will match.
6355   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6356   QualType T = TInfo->getType();
6357   if (T->isVariablyModifiedType()) {
6358     setFunctionHasBranchProtectedScope();
6359 
6360     if (S->getFnParent() == nullptr) {
6361       bool SizeIsNegative;
6362       llvm::APSInt Oversized;
6363       TypeSourceInfo *FixedTInfo =
6364         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6365                                                       SizeIsNegative,
6366                                                       Oversized);
6367       if (FixedTInfo) {
6368         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6369         NewTD->setTypeSourceInfo(FixedTInfo);
6370       } else {
6371         if (SizeIsNegative)
6372           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6373         else if (T->isVariableArrayType())
6374           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6375         else if (Oversized.getBoolValue())
6376           Diag(NewTD->getLocation(), diag::err_array_too_large)
6377             << toString(Oversized, 10);
6378         else
6379           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6380         NewTD->setInvalidDecl();
6381       }
6382     }
6383   }
6384 }
6385 
6386 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6387 /// declares a typedef-name, either using the 'typedef' type specifier or via
6388 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6389 NamedDecl*
6390 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6391                            LookupResult &Previous, bool &Redeclaration) {
6392 
6393   // Find the shadowed declaration before filtering for scope.
6394   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6395 
6396   // Merge the decl with the existing one if appropriate. If the decl is
6397   // in an outer scope, it isn't the same thing.
6398   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6399                        /*AllowInlineNamespace*/false);
6400   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6401   if (!Previous.empty()) {
6402     Redeclaration = true;
6403     MergeTypedefNameDecl(S, NewTD, Previous);
6404   } else {
6405     inferGslPointerAttribute(NewTD);
6406   }
6407 
6408   if (ShadowedDecl && !Redeclaration)
6409     CheckShadow(NewTD, ShadowedDecl, Previous);
6410 
6411   // If this is the C FILE type, notify the AST context.
6412   if (IdentifierInfo *II = NewTD->getIdentifier())
6413     if (!NewTD->isInvalidDecl() &&
6414         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6415       if (II->isStr("FILE"))
6416         Context.setFILEDecl(NewTD);
6417       else if (II->isStr("jmp_buf"))
6418         Context.setjmp_bufDecl(NewTD);
6419       else if (II->isStr("sigjmp_buf"))
6420         Context.setsigjmp_bufDecl(NewTD);
6421       else if (II->isStr("ucontext_t"))
6422         Context.setucontext_tDecl(NewTD);
6423     }
6424 
6425   return NewTD;
6426 }
6427 
6428 /// Determines whether the given declaration is an out-of-scope
6429 /// previous declaration.
6430 ///
6431 /// This routine should be invoked when name lookup has found a
6432 /// previous declaration (PrevDecl) that is not in the scope where a
6433 /// new declaration by the same name is being introduced. If the new
6434 /// declaration occurs in a local scope, previous declarations with
6435 /// linkage may still be considered previous declarations (C99
6436 /// 6.2.2p4-5, C++ [basic.link]p6).
6437 ///
6438 /// \param PrevDecl the previous declaration found by name
6439 /// lookup
6440 ///
6441 /// \param DC the context in which the new declaration is being
6442 /// declared.
6443 ///
6444 /// \returns true if PrevDecl is an out-of-scope previous declaration
6445 /// for a new delcaration with the same name.
6446 static bool
6447 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6448                                 ASTContext &Context) {
6449   if (!PrevDecl)
6450     return false;
6451 
6452   if (!PrevDecl->hasLinkage())
6453     return false;
6454 
6455   if (Context.getLangOpts().CPlusPlus) {
6456     // C++ [basic.link]p6:
6457     //   If there is a visible declaration of an entity with linkage
6458     //   having the same name and type, ignoring entities declared
6459     //   outside the innermost enclosing namespace scope, the block
6460     //   scope declaration declares that same entity and receives the
6461     //   linkage of the previous declaration.
6462     DeclContext *OuterContext = DC->getRedeclContext();
6463     if (!OuterContext->isFunctionOrMethod())
6464       // This rule only applies to block-scope declarations.
6465       return false;
6466 
6467     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6468     if (PrevOuterContext->isRecord())
6469       // We found a member function: ignore it.
6470       return false;
6471 
6472     // Find the innermost enclosing namespace for the new and
6473     // previous declarations.
6474     OuterContext = OuterContext->getEnclosingNamespaceContext();
6475     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6476 
6477     // The previous declaration is in a different namespace, so it
6478     // isn't the same function.
6479     if (!OuterContext->Equals(PrevOuterContext))
6480       return false;
6481   }
6482 
6483   return true;
6484 }
6485 
6486 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6487   CXXScopeSpec &SS = D.getCXXScopeSpec();
6488   if (!SS.isSet()) return;
6489   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6490 }
6491 
6492 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6493   QualType type = decl->getType();
6494   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6495   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6496     // Various kinds of declaration aren't allowed to be __autoreleasing.
6497     unsigned kind = -1U;
6498     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6499       if (var->hasAttr<BlocksAttr>())
6500         kind = 0; // __block
6501       else if (!var->hasLocalStorage())
6502         kind = 1; // global
6503     } else if (isa<ObjCIvarDecl>(decl)) {
6504       kind = 3; // ivar
6505     } else if (isa<FieldDecl>(decl)) {
6506       kind = 2; // field
6507     }
6508 
6509     if (kind != -1U) {
6510       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6511         << kind;
6512     }
6513   } else if (lifetime == Qualifiers::OCL_None) {
6514     // Try to infer lifetime.
6515     if (!type->isObjCLifetimeType())
6516       return false;
6517 
6518     lifetime = type->getObjCARCImplicitLifetime();
6519     type = Context.getLifetimeQualifiedType(type, lifetime);
6520     decl->setType(type);
6521   }
6522 
6523   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6524     // Thread-local variables cannot have lifetime.
6525     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6526         var->getTLSKind()) {
6527       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6528         << var->getType();
6529       return true;
6530     }
6531   }
6532 
6533   return false;
6534 }
6535 
6536 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6537   if (Decl->getType().hasAddressSpace())
6538     return;
6539   if (Decl->getType()->isDependentType())
6540     return;
6541   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6542     QualType Type = Var->getType();
6543     if (Type->isSamplerT() || Type->isVoidType())
6544       return;
6545     LangAS ImplAS = LangAS::opencl_private;
6546     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6547     // __opencl_c_program_scope_global_variables feature, the address space
6548     // for a variable at program scope or a static or extern variable inside
6549     // a function are inferred to be __global.
6550     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6551         Var->hasGlobalStorage())
6552       ImplAS = LangAS::opencl_global;
6553     // If the original type from a decayed type is an array type and that array
6554     // type has no address space yet, deduce it now.
6555     if (auto DT = dyn_cast<DecayedType>(Type)) {
6556       auto OrigTy = DT->getOriginalType();
6557       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6558         // Add the address space to the original array type and then propagate
6559         // that to the element type through `getAsArrayType`.
6560         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6561         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6562         // Re-generate the decayed type.
6563         Type = Context.getDecayedType(OrigTy);
6564       }
6565     }
6566     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6567     // Apply any qualifiers (including address space) from the array type to
6568     // the element type. This implements C99 6.7.3p8: "If the specification of
6569     // an array type includes any type qualifiers, the element type is so
6570     // qualified, not the array type."
6571     if (Type->isArrayType())
6572       Type = QualType(Context.getAsArrayType(Type), 0);
6573     Decl->setType(Type);
6574   }
6575 }
6576 
6577 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6578   // Ensure that an auto decl is deduced otherwise the checks below might cache
6579   // the wrong linkage.
6580   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6581 
6582   // 'weak' only applies to declarations with external linkage.
6583   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6584     if (!ND.isExternallyVisible()) {
6585       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6586       ND.dropAttr<WeakAttr>();
6587     }
6588   }
6589   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6590     if (ND.isExternallyVisible()) {
6591       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6592       ND.dropAttr<WeakRefAttr>();
6593       ND.dropAttr<AliasAttr>();
6594     }
6595   }
6596 
6597   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6598     if (VD->hasInit()) {
6599       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6600         assert(VD->isThisDeclarationADefinition() &&
6601                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6602         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6603         VD->dropAttr<AliasAttr>();
6604       }
6605     }
6606   }
6607 
6608   // 'selectany' only applies to externally visible variable declarations.
6609   // It does not apply to functions.
6610   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6611     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6612       S.Diag(Attr->getLocation(),
6613              diag::err_attribute_selectany_non_extern_data);
6614       ND.dropAttr<SelectAnyAttr>();
6615     }
6616   }
6617 
6618   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6619     auto *VD = dyn_cast<VarDecl>(&ND);
6620     bool IsAnonymousNS = false;
6621     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6622     if (VD) {
6623       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6624       while (NS && !IsAnonymousNS) {
6625         IsAnonymousNS = NS->isAnonymousNamespace();
6626         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6627       }
6628     }
6629     // dll attributes require external linkage. Static locals may have external
6630     // linkage but still cannot be explicitly imported or exported.
6631     // In Microsoft mode, a variable defined in anonymous namespace must have
6632     // external linkage in order to be exported.
6633     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6634     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6635         (!AnonNSInMicrosoftMode &&
6636          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6637       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6638         << &ND << Attr;
6639       ND.setInvalidDecl();
6640     }
6641   }
6642 
6643   // Check the attributes on the function type, if any.
6644   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6645     // Don't declare this variable in the second operand of the for-statement;
6646     // GCC miscompiles that by ending its lifetime before evaluating the
6647     // third operand. See gcc.gnu.org/PR86769.
6648     AttributedTypeLoc ATL;
6649     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6650          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6651          TL = ATL.getModifiedLoc()) {
6652       // The [[lifetimebound]] attribute can be applied to the implicit object
6653       // parameter of a non-static member function (other than a ctor or dtor)
6654       // by applying it to the function type.
6655       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6656         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6657         if (!MD || MD->isStatic()) {
6658           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6659               << !MD << A->getRange();
6660         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6661           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6662               << isa<CXXDestructorDecl>(MD) << A->getRange();
6663         }
6664       }
6665     }
6666   }
6667 }
6668 
6669 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6670                                            NamedDecl *NewDecl,
6671                                            bool IsSpecialization,
6672                                            bool IsDefinition) {
6673   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6674     return;
6675 
6676   bool IsTemplate = false;
6677   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6678     OldDecl = OldTD->getTemplatedDecl();
6679     IsTemplate = true;
6680     if (!IsSpecialization)
6681       IsDefinition = false;
6682   }
6683   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6684     NewDecl = NewTD->getTemplatedDecl();
6685     IsTemplate = true;
6686   }
6687 
6688   if (!OldDecl || !NewDecl)
6689     return;
6690 
6691   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6692   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6693   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6694   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6695 
6696   // dllimport and dllexport are inheritable attributes so we have to exclude
6697   // inherited attribute instances.
6698   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6699                     (NewExportAttr && !NewExportAttr->isInherited());
6700 
6701   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6702   // the only exception being explicit specializations.
6703   // Implicitly generated declarations are also excluded for now because there
6704   // is no other way to switch these to use dllimport or dllexport.
6705   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6706 
6707   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6708     // Allow with a warning for free functions and global variables.
6709     bool JustWarn = false;
6710     if (!OldDecl->isCXXClassMember()) {
6711       auto *VD = dyn_cast<VarDecl>(OldDecl);
6712       if (VD && !VD->getDescribedVarTemplate())
6713         JustWarn = true;
6714       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6715       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6716         JustWarn = true;
6717     }
6718 
6719     // We cannot change a declaration that's been used because IR has already
6720     // been emitted. Dllimported functions will still work though (modulo
6721     // address equality) as they can use the thunk.
6722     if (OldDecl->isUsed())
6723       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6724         JustWarn = false;
6725 
6726     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6727                                : diag::err_attribute_dll_redeclaration;
6728     S.Diag(NewDecl->getLocation(), DiagID)
6729         << NewDecl
6730         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6731     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6732     if (!JustWarn) {
6733       NewDecl->setInvalidDecl();
6734       return;
6735     }
6736   }
6737 
6738   // A redeclaration is not allowed to drop a dllimport attribute, the only
6739   // exceptions being inline function definitions (except for function
6740   // templates), local extern declarations, qualified friend declarations or
6741   // special MSVC extension: in the last case, the declaration is treated as if
6742   // it were marked dllexport.
6743   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6744   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6745   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6746     // Ignore static data because out-of-line definitions are diagnosed
6747     // separately.
6748     IsStaticDataMember = VD->isStaticDataMember();
6749     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6750                    VarDecl::DeclarationOnly;
6751   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6752     IsInline = FD->isInlined();
6753     IsQualifiedFriend = FD->getQualifier() &&
6754                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6755   }
6756 
6757   if (OldImportAttr && !HasNewAttr &&
6758       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6759       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6760     if (IsMicrosoftABI && IsDefinition) {
6761       S.Diag(NewDecl->getLocation(),
6762              diag::warn_redeclaration_without_import_attribute)
6763           << NewDecl;
6764       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6765       NewDecl->dropAttr<DLLImportAttr>();
6766       NewDecl->addAttr(
6767           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6768     } else {
6769       S.Diag(NewDecl->getLocation(),
6770              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6771           << NewDecl << OldImportAttr;
6772       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6773       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6774       OldDecl->dropAttr<DLLImportAttr>();
6775       NewDecl->dropAttr<DLLImportAttr>();
6776     }
6777   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6778     // In MinGW, seeing a function declared inline drops the dllimport
6779     // attribute.
6780     OldDecl->dropAttr<DLLImportAttr>();
6781     NewDecl->dropAttr<DLLImportAttr>();
6782     S.Diag(NewDecl->getLocation(),
6783            diag::warn_dllimport_dropped_from_inline_function)
6784         << NewDecl << OldImportAttr;
6785   }
6786 
6787   // A specialization of a class template member function is processed here
6788   // since it's a redeclaration. If the parent class is dllexport, the
6789   // specialization inherits that attribute. This doesn't happen automatically
6790   // since the parent class isn't instantiated until later.
6791   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6792     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6793         !NewImportAttr && !NewExportAttr) {
6794       if (const DLLExportAttr *ParentExportAttr =
6795               MD->getParent()->getAttr<DLLExportAttr>()) {
6796         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6797         NewAttr->setInherited(true);
6798         NewDecl->addAttr(NewAttr);
6799       }
6800     }
6801   }
6802 }
6803 
6804 /// Given that we are within the definition of the given function,
6805 /// will that definition behave like C99's 'inline', where the
6806 /// definition is discarded except for optimization purposes?
6807 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6808   // Try to avoid calling GetGVALinkageForFunction.
6809 
6810   // All cases of this require the 'inline' keyword.
6811   if (!FD->isInlined()) return false;
6812 
6813   // This is only possible in C++ with the gnu_inline attribute.
6814   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6815     return false;
6816 
6817   // Okay, go ahead and call the relatively-more-expensive function.
6818   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6819 }
6820 
6821 /// Determine whether a variable is extern "C" prior to attaching
6822 /// an initializer. We can't just call isExternC() here, because that
6823 /// will also compute and cache whether the declaration is externally
6824 /// visible, which might change when we attach the initializer.
6825 ///
6826 /// This can only be used if the declaration is known to not be a
6827 /// redeclaration of an internal linkage declaration.
6828 ///
6829 /// For instance:
6830 ///
6831 ///   auto x = []{};
6832 ///
6833 /// Attaching the initializer here makes this declaration not externally
6834 /// visible, because its type has internal linkage.
6835 ///
6836 /// FIXME: This is a hack.
6837 template<typename T>
6838 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6839   if (S.getLangOpts().CPlusPlus) {
6840     // In C++, the overloadable attribute negates the effects of extern "C".
6841     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6842       return false;
6843 
6844     // So do CUDA's host/device attributes.
6845     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6846                                  D->template hasAttr<CUDAHostAttr>()))
6847       return false;
6848   }
6849   return D->isExternC();
6850 }
6851 
6852 static bool shouldConsiderLinkage(const VarDecl *VD) {
6853   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6854   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6855       isa<OMPDeclareMapperDecl>(DC))
6856     return VD->hasExternalStorage();
6857   if (DC->isFileContext())
6858     return true;
6859   if (DC->isRecord())
6860     return false;
6861   if (isa<RequiresExprBodyDecl>(DC))
6862     return false;
6863   llvm_unreachable("Unexpected context");
6864 }
6865 
6866 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6867   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6868   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6869       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6870     return true;
6871   if (DC->isRecord())
6872     return false;
6873   llvm_unreachable("Unexpected context");
6874 }
6875 
6876 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6877                           ParsedAttr::Kind Kind) {
6878   // Check decl attributes on the DeclSpec.
6879   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6880     return true;
6881 
6882   // Walk the declarator structure, checking decl attributes that were in a type
6883   // position to the decl itself.
6884   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6885     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6886       return true;
6887   }
6888 
6889   // Finally, check attributes on the decl itself.
6890   return PD.getAttributes().hasAttribute(Kind);
6891 }
6892 
6893 /// Adjust the \c DeclContext for a function or variable that might be a
6894 /// function-local external declaration.
6895 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6896   if (!DC->isFunctionOrMethod())
6897     return false;
6898 
6899   // If this is a local extern function or variable declared within a function
6900   // template, don't add it into the enclosing namespace scope until it is
6901   // instantiated; it might have a dependent type right now.
6902   if (DC->isDependentContext())
6903     return true;
6904 
6905   // C++11 [basic.link]p7:
6906   //   When a block scope declaration of an entity with linkage is not found to
6907   //   refer to some other declaration, then that entity is a member of the
6908   //   innermost enclosing namespace.
6909   //
6910   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6911   // semantically-enclosing namespace, not a lexically-enclosing one.
6912   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6913     DC = DC->getParent();
6914   return true;
6915 }
6916 
6917 /// Returns true if given declaration has external C language linkage.
6918 static bool isDeclExternC(const Decl *D) {
6919   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6920     return FD->isExternC();
6921   if (const auto *VD = dyn_cast<VarDecl>(D))
6922     return VD->isExternC();
6923 
6924   llvm_unreachable("Unknown type of decl!");
6925 }
6926 
6927 /// Returns true if there hasn't been any invalid type diagnosed.
6928 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6929   DeclContext *DC = NewVD->getDeclContext();
6930   QualType R = NewVD->getType();
6931 
6932   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6933   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6934   // argument.
6935   if (R->isImageType() || R->isPipeType()) {
6936     Se.Diag(NewVD->getLocation(),
6937             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6938         << R;
6939     NewVD->setInvalidDecl();
6940     return false;
6941   }
6942 
6943   // OpenCL v1.2 s6.9.r:
6944   // The event type cannot be used to declare a program scope variable.
6945   // OpenCL v2.0 s6.9.q:
6946   // The clk_event_t and reserve_id_t types cannot be declared in program
6947   // scope.
6948   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6949     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6950       Se.Diag(NewVD->getLocation(),
6951               diag::err_invalid_type_for_program_scope_var)
6952           << R;
6953       NewVD->setInvalidDecl();
6954       return false;
6955     }
6956   }
6957 
6958   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6959   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6960                                                Se.getLangOpts())) {
6961     QualType NR = R.getCanonicalType();
6962     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6963            NR->isReferenceType()) {
6964       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6965           NR->isFunctionReferenceType()) {
6966         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6967             << NR->isReferenceType();
6968         NewVD->setInvalidDecl();
6969         return false;
6970       }
6971       NR = NR->getPointeeType();
6972     }
6973   }
6974 
6975   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6976                                                Se.getLangOpts())) {
6977     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6978     // half array type (unless the cl_khr_fp16 extension is enabled).
6979     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6980       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6981       NewVD->setInvalidDecl();
6982       return false;
6983     }
6984   }
6985 
6986   // OpenCL v1.2 s6.9.r:
6987   // The event type cannot be used with the __local, __constant and __global
6988   // address space qualifiers.
6989   if (R->isEventT()) {
6990     if (R.getAddressSpace() != LangAS::opencl_private) {
6991       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6992       NewVD->setInvalidDecl();
6993       return false;
6994     }
6995   }
6996 
6997   if (R->isSamplerT()) {
6998     // OpenCL v1.2 s6.9.b p4:
6999     // The sampler type cannot be used with the __local and __global address
7000     // space qualifiers.
7001     if (R.getAddressSpace() == LangAS::opencl_local ||
7002         R.getAddressSpace() == LangAS::opencl_global) {
7003       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7004       NewVD->setInvalidDecl();
7005     }
7006 
7007     // OpenCL v1.2 s6.12.14.1:
7008     // A global sampler must be declared with either the constant address
7009     // space qualifier or with the const qualifier.
7010     if (DC->isTranslationUnit() &&
7011         !(R.getAddressSpace() == LangAS::opencl_constant ||
7012           R.isConstQualified())) {
7013       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7014       NewVD->setInvalidDecl();
7015     }
7016     if (NewVD->isInvalidDecl())
7017       return false;
7018   }
7019 
7020   return true;
7021 }
7022 
7023 template <typename AttrTy>
7024 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7025   const TypedefNameDecl *TND = TT->getDecl();
7026   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7027     AttrTy *Clone = Attribute->clone(S.Context);
7028     Clone->setInherited(true);
7029     D->addAttr(Clone);
7030   }
7031 }
7032 
7033 NamedDecl *Sema::ActOnVariableDeclarator(
7034     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7035     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7036     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7037   QualType R = TInfo->getType();
7038   DeclarationName Name = GetNameForDeclarator(D).getName();
7039 
7040   IdentifierInfo *II = Name.getAsIdentifierInfo();
7041 
7042   if (D.isDecompositionDeclarator()) {
7043     // Take the name of the first declarator as our name for diagnostic
7044     // purposes.
7045     auto &Decomp = D.getDecompositionDeclarator();
7046     if (!Decomp.bindings().empty()) {
7047       II = Decomp.bindings()[0].Name;
7048       Name = II;
7049     }
7050   } else if (!II) {
7051     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7052     return nullptr;
7053   }
7054 
7055 
7056   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7057   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7058 
7059   // dllimport globals without explicit storage class are treated as extern. We
7060   // have to change the storage class this early to get the right DeclContext.
7061   if (SC == SC_None && !DC->isRecord() &&
7062       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7063       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7064     SC = SC_Extern;
7065 
7066   DeclContext *OriginalDC = DC;
7067   bool IsLocalExternDecl = SC == SC_Extern &&
7068                            adjustContextForLocalExternDecl(DC);
7069 
7070   if (SCSpec == DeclSpec::SCS_mutable) {
7071     // mutable can only appear on non-static class members, so it's always
7072     // an error here
7073     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7074     D.setInvalidType();
7075     SC = SC_None;
7076   }
7077 
7078   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7079       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7080                               D.getDeclSpec().getStorageClassSpecLoc())) {
7081     // In C++11, the 'register' storage class specifier is deprecated.
7082     // Suppress the warning in system macros, it's used in macros in some
7083     // popular C system headers, such as in glibc's htonl() macro.
7084     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7085          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7086                                    : diag::warn_deprecated_register)
7087       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7088   }
7089 
7090   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7091 
7092   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7093     // C99 6.9p2: The storage-class specifiers auto and register shall not
7094     // appear in the declaration specifiers in an external declaration.
7095     // Global Register+Asm is a GNU extension we support.
7096     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7097       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7098       D.setInvalidType();
7099     }
7100   }
7101 
7102   // If this variable has a VLA type and an initializer, try to
7103   // fold to a constant-sized type. This is otherwise invalid.
7104   if (D.hasInitializer() && R->isVariableArrayType())
7105     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7106                                     /*DiagID=*/0);
7107 
7108   bool IsMemberSpecialization = false;
7109   bool IsVariableTemplateSpecialization = false;
7110   bool IsPartialSpecialization = false;
7111   bool IsVariableTemplate = false;
7112   VarDecl *NewVD = nullptr;
7113   VarTemplateDecl *NewTemplate = nullptr;
7114   TemplateParameterList *TemplateParams = nullptr;
7115   if (!getLangOpts().CPlusPlus) {
7116     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7117                             II, R, TInfo, SC);
7118 
7119     if (R->getContainedDeducedType())
7120       ParsingInitForAutoVars.insert(NewVD);
7121 
7122     if (D.isInvalidType())
7123       NewVD->setInvalidDecl();
7124 
7125     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7126         NewVD->hasLocalStorage())
7127       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7128                             NTCUC_AutoVar, NTCUK_Destruct);
7129   } else {
7130     bool Invalid = false;
7131 
7132     if (DC->isRecord() && !CurContext->isRecord()) {
7133       // This is an out-of-line definition of a static data member.
7134       switch (SC) {
7135       case SC_None:
7136         break;
7137       case SC_Static:
7138         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7139              diag::err_static_out_of_line)
7140           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7141         break;
7142       case SC_Auto:
7143       case SC_Register:
7144       case SC_Extern:
7145         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7146         // to names of variables declared in a block or to function parameters.
7147         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7148         // of class members
7149 
7150         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7151              diag::err_storage_class_for_static_member)
7152           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7153         break;
7154       case SC_PrivateExtern:
7155         llvm_unreachable("C storage class in c++!");
7156       }
7157     }
7158 
7159     if (SC == SC_Static && CurContext->isRecord()) {
7160       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7161         // Walk up the enclosing DeclContexts to check for any that are
7162         // incompatible with static data members.
7163         const DeclContext *FunctionOrMethod = nullptr;
7164         const CXXRecordDecl *AnonStruct = nullptr;
7165         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7166           if (Ctxt->isFunctionOrMethod()) {
7167             FunctionOrMethod = Ctxt;
7168             break;
7169           }
7170           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7171           if (ParentDecl && !ParentDecl->getDeclName()) {
7172             AnonStruct = ParentDecl;
7173             break;
7174           }
7175         }
7176         if (FunctionOrMethod) {
7177           // C++ [class.static.data]p5: A local class shall not have static data
7178           // members.
7179           Diag(D.getIdentifierLoc(),
7180                diag::err_static_data_member_not_allowed_in_local_class)
7181             << Name << RD->getDeclName() << RD->getTagKind();
7182         } else if (AnonStruct) {
7183           // C++ [class.static.data]p4: Unnamed classes and classes contained
7184           // directly or indirectly within unnamed classes shall not contain
7185           // static data members.
7186           Diag(D.getIdentifierLoc(),
7187                diag::err_static_data_member_not_allowed_in_anon_struct)
7188             << Name << AnonStruct->getTagKind();
7189           Invalid = true;
7190         } else if (RD->isUnion()) {
7191           // C++98 [class.union]p1: If a union contains a static data member,
7192           // the program is ill-formed. C++11 drops this restriction.
7193           Diag(D.getIdentifierLoc(),
7194                getLangOpts().CPlusPlus11
7195                  ? diag::warn_cxx98_compat_static_data_member_in_union
7196                  : diag::ext_static_data_member_in_union) << Name;
7197         }
7198       }
7199     }
7200 
7201     // Match up the template parameter lists with the scope specifier, then
7202     // determine whether we have a template or a template specialization.
7203     bool InvalidScope = false;
7204     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7205         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7206         D.getCXXScopeSpec(),
7207         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7208             ? D.getName().TemplateId
7209             : nullptr,
7210         TemplateParamLists,
7211         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7212     Invalid |= InvalidScope;
7213 
7214     if (TemplateParams) {
7215       if (!TemplateParams->size() &&
7216           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7217         // There is an extraneous 'template<>' for this variable. Complain
7218         // about it, but allow the declaration of the variable.
7219         Diag(TemplateParams->getTemplateLoc(),
7220              diag::err_template_variable_noparams)
7221           << II
7222           << SourceRange(TemplateParams->getTemplateLoc(),
7223                          TemplateParams->getRAngleLoc());
7224         TemplateParams = nullptr;
7225       } else {
7226         // Check that we can declare a template here.
7227         if (CheckTemplateDeclScope(S, TemplateParams))
7228           return nullptr;
7229 
7230         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7231           // This is an explicit specialization or a partial specialization.
7232           IsVariableTemplateSpecialization = true;
7233           IsPartialSpecialization = TemplateParams->size() > 0;
7234         } else { // if (TemplateParams->size() > 0)
7235           // This is a template declaration.
7236           IsVariableTemplate = true;
7237 
7238           // Only C++1y supports variable templates (N3651).
7239           Diag(D.getIdentifierLoc(),
7240                getLangOpts().CPlusPlus14
7241                    ? diag::warn_cxx11_compat_variable_template
7242                    : diag::ext_variable_template);
7243         }
7244       }
7245     } else {
7246       // Check that we can declare a member specialization here.
7247       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7248           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7249         return nullptr;
7250       assert((Invalid ||
7251               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7252              "should have a 'template<>' for this decl");
7253     }
7254 
7255     if (IsVariableTemplateSpecialization) {
7256       SourceLocation TemplateKWLoc =
7257           TemplateParamLists.size() > 0
7258               ? TemplateParamLists[0]->getTemplateLoc()
7259               : SourceLocation();
7260       DeclResult Res = ActOnVarTemplateSpecialization(
7261           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7262           IsPartialSpecialization);
7263       if (Res.isInvalid())
7264         return nullptr;
7265       NewVD = cast<VarDecl>(Res.get());
7266       AddToScope = false;
7267     } else if (D.isDecompositionDeclarator()) {
7268       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7269                                         D.getIdentifierLoc(), R, TInfo, SC,
7270                                         Bindings);
7271     } else
7272       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7273                               D.getIdentifierLoc(), II, R, TInfo, SC);
7274 
7275     // If this is supposed to be a variable template, create it as such.
7276     if (IsVariableTemplate) {
7277       NewTemplate =
7278           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7279                                   TemplateParams, NewVD);
7280       NewVD->setDescribedVarTemplate(NewTemplate);
7281     }
7282 
7283     // If this decl has an auto type in need of deduction, make a note of the
7284     // Decl so we can diagnose uses of it in its own initializer.
7285     if (R->getContainedDeducedType())
7286       ParsingInitForAutoVars.insert(NewVD);
7287 
7288     if (D.isInvalidType() || Invalid) {
7289       NewVD->setInvalidDecl();
7290       if (NewTemplate)
7291         NewTemplate->setInvalidDecl();
7292     }
7293 
7294     SetNestedNameSpecifier(*this, NewVD, D);
7295 
7296     // If we have any template parameter lists that don't directly belong to
7297     // the variable (matching the scope specifier), store them.
7298     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7299     if (TemplateParamLists.size() > VDTemplateParamLists)
7300       NewVD->setTemplateParameterListsInfo(
7301           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7302   }
7303 
7304   if (D.getDeclSpec().isInlineSpecified()) {
7305     if (!getLangOpts().CPlusPlus) {
7306       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7307           << 0;
7308     } else if (CurContext->isFunctionOrMethod()) {
7309       // 'inline' is not allowed on block scope variable declaration.
7310       Diag(D.getDeclSpec().getInlineSpecLoc(),
7311            diag::err_inline_declaration_block_scope) << Name
7312         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7313     } else {
7314       Diag(D.getDeclSpec().getInlineSpecLoc(),
7315            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7316                                      : diag::ext_inline_variable);
7317       NewVD->setInlineSpecified();
7318     }
7319   }
7320 
7321   // Set the lexical context. If the declarator has a C++ scope specifier, the
7322   // lexical context will be different from the semantic context.
7323   NewVD->setLexicalDeclContext(CurContext);
7324   if (NewTemplate)
7325     NewTemplate->setLexicalDeclContext(CurContext);
7326 
7327   if (IsLocalExternDecl) {
7328     if (D.isDecompositionDeclarator())
7329       for (auto *B : Bindings)
7330         B->setLocalExternDecl();
7331     else
7332       NewVD->setLocalExternDecl();
7333   }
7334 
7335   bool EmitTLSUnsupportedError = false;
7336   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7337     // C++11 [dcl.stc]p4:
7338     //   When thread_local is applied to a variable of block scope the
7339     //   storage-class-specifier static is implied if it does not appear
7340     //   explicitly.
7341     // Core issue: 'static' is not implied if the variable is declared
7342     //   'extern'.
7343     if (NewVD->hasLocalStorage() &&
7344         (SCSpec != DeclSpec::SCS_unspecified ||
7345          TSCS != DeclSpec::TSCS_thread_local ||
7346          !DC->isFunctionOrMethod()))
7347       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7348            diag::err_thread_non_global)
7349         << DeclSpec::getSpecifierName(TSCS);
7350     else if (!Context.getTargetInfo().isTLSSupported()) {
7351       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7352           getLangOpts().SYCLIsDevice) {
7353         // Postpone error emission until we've collected attributes required to
7354         // figure out whether it's a host or device variable and whether the
7355         // error should be ignored.
7356         EmitTLSUnsupportedError = true;
7357         // We still need to mark the variable as TLS so it shows up in AST with
7358         // proper storage class for other tools to use even if we're not going
7359         // to emit any code for it.
7360         NewVD->setTSCSpec(TSCS);
7361       } else
7362         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7363              diag::err_thread_unsupported);
7364     } else
7365       NewVD->setTSCSpec(TSCS);
7366   }
7367 
7368   switch (D.getDeclSpec().getConstexprSpecifier()) {
7369   case ConstexprSpecKind::Unspecified:
7370     break;
7371 
7372   case ConstexprSpecKind::Consteval:
7373     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7374          diag::err_constexpr_wrong_decl_kind)
7375         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7376     LLVM_FALLTHROUGH;
7377 
7378   case ConstexprSpecKind::Constexpr:
7379     NewVD->setConstexpr(true);
7380     // C++1z [dcl.spec.constexpr]p1:
7381     //   A static data member declared with the constexpr specifier is
7382     //   implicitly an inline variable.
7383     if (NewVD->isStaticDataMember() &&
7384         (getLangOpts().CPlusPlus17 ||
7385          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7386       NewVD->setImplicitlyInline();
7387     break;
7388 
7389   case ConstexprSpecKind::Constinit:
7390     if (!NewVD->hasGlobalStorage())
7391       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7392            diag::err_constinit_local_variable);
7393     else
7394       NewVD->addAttr(ConstInitAttr::Create(
7395           Context, D.getDeclSpec().getConstexprSpecLoc(),
7396           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7397     break;
7398   }
7399 
7400   // C99 6.7.4p3
7401   //   An inline definition of a function with external linkage shall
7402   //   not contain a definition of a modifiable object with static or
7403   //   thread storage duration...
7404   // We only apply this when the function is required to be defined
7405   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7406   // that a local variable with thread storage duration still has to
7407   // be marked 'static'.  Also note that it's possible to get these
7408   // semantics in C++ using __attribute__((gnu_inline)).
7409   if (SC == SC_Static && S->getFnParent() != nullptr &&
7410       !NewVD->getType().isConstQualified()) {
7411     FunctionDecl *CurFD = getCurFunctionDecl();
7412     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7413       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7414            diag::warn_static_local_in_extern_inline);
7415       MaybeSuggestAddingStaticToDecl(CurFD);
7416     }
7417   }
7418 
7419   if (D.getDeclSpec().isModulePrivateSpecified()) {
7420     if (IsVariableTemplateSpecialization)
7421       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7422           << (IsPartialSpecialization ? 1 : 0)
7423           << FixItHint::CreateRemoval(
7424                  D.getDeclSpec().getModulePrivateSpecLoc());
7425     else if (IsMemberSpecialization)
7426       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7427         << 2
7428         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7429     else if (NewVD->hasLocalStorage())
7430       Diag(NewVD->getLocation(), diag::err_module_private_local)
7431           << 0 << NewVD
7432           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7433           << FixItHint::CreateRemoval(
7434                  D.getDeclSpec().getModulePrivateSpecLoc());
7435     else {
7436       NewVD->setModulePrivate();
7437       if (NewTemplate)
7438         NewTemplate->setModulePrivate();
7439       for (auto *B : Bindings)
7440         B->setModulePrivate();
7441     }
7442   }
7443 
7444   if (getLangOpts().OpenCL) {
7445     deduceOpenCLAddressSpace(NewVD);
7446 
7447     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7448     if (TSC != TSCS_unspecified) {
7449       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7450            diag::err_opencl_unknown_type_specifier)
7451           << getLangOpts().getOpenCLVersionString()
7452           << DeclSpec::getSpecifierName(TSC) << 1;
7453       NewVD->setInvalidDecl();
7454     }
7455   }
7456 
7457   // Handle attributes prior to checking for duplicates in MergeVarDecl
7458   ProcessDeclAttributes(S, NewVD, D);
7459 
7460   // FIXME: This is probably the wrong location to be doing this and we should
7461   // probably be doing this for more attributes (especially for function
7462   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7463   // the code to copy attributes would be generated by TableGen.
7464   if (R->isFunctionPointerType())
7465     if (const auto *TT = R->getAs<TypedefType>())
7466       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7467 
7468   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7469       getLangOpts().SYCLIsDevice) {
7470     if (EmitTLSUnsupportedError &&
7471         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7472          (getLangOpts().OpenMPIsDevice &&
7473           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7474       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7475            diag::err_thread_unsupported);
7476 
7477     if (EmitTLSUnsupportedError &&
7478         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7479       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7480     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7481     // storage [duration]."
7482     if (SC == SC_None && S->getFnParent() != nullptr &&
7483         (NewVD->hasAttr<CUDASharedAttr>() ||
7484          NewVD->hasAttr<CUDAConstantAttr>())) {
7485       NewVD->setStorageClass(SC_Static);
7486     }
7487   }
7488 
7489   // Ensure that dllimport globals without explicit storage class are treated as
7490   // extern. The storage class is set above using parsed attributes. Now we can
7491   // check the VarDecl itself.
7492   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7493          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7494          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7495 
7496   // In auto-retain/release, infer strong retension for variables of
7497   // retainable type.
7498   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7499     NewVD->setInvalidDecl();
7500 
7501   // Handle GNU asm-label extension (encoded as an attribute).
7502   if (Expr *E = (Expr*)D.getAsmLabel()) {
7503     // The parser guarantees this is a string.
7504     StringLiteral *SE = cast<StringLiteral>(E);
7505     StringRef Label = SE->getString();
7506     if (S->getFnParent() != nullptr) {
7507       switch (SC) {
7508       case SC_None:
7509       case SC_Auto:
7510         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7511         break;
7512       case SC_Register:
7513         // Local Named register
7514         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7515             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7516           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7517         break;
7518       case SC_Static:
7519       case SC_Extern:
7520       case SC_PrivateExtern:
7521         break;
7522       }
7523     } else if (SC == SC_Register) {
7524       // Global Named register
7525       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7526         const auto &TI = Context.getTargetInfo();
7527         bool HasSizeMismatch;
7528 
7529         if (!TI.isValidGCCRegisterName(Label))
7530           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7531         else if (!TI.validateGlobalRegisterVariable(Label,
7532                                                     Context.getTypeSize(R),
7533                                                     HasSizeMismatch))
7534           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7535         else if (HasSizeMismatch)
7536           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7537       }
7538 
7539       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7540         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7541         NewVD->setInvalidDecl(true);
7542       }
7543     }
7544 
7545     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7546                                         /*IsLiteralLabel=*/true,
7547                                         SE->getStrTokenLoc(0)));
7548   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7549     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7550       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7551     if (I != ExtnameUndeclaredIdentifiers.end()) {
7552       if (isDeclExternC(NewVD)) {
7553         NewVD->addAttr(I->second);
7554         ExtnameUndeclaredIdentifiers.erase(I);
7555       } else
7556         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7557             << /*Variable*/1 << NewVD;
7558     }
7559   }
7560 
7561   // Find the shadowed declaration before filtering for scope.
7562   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7563                                 ? getShadowedDeclaration(NewVD, Previous)
7564                                 : nullptr;
7565 
7566   // Don't consider existing declarations that are in a different
7567   // scope and are out-of-semantic-context declarations (if the new
7568   // declaration has linkage).
7569   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7570                        D.getCXXScopeSpec().isNotEmpty() ||
7571                        IsMemberSpecialization ||
7572                        IsVariableTemplateSpecialization);
7573 
7574   // Check whether the previous declaration is in the same block scope. This
7575   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7576   if (getLangOpts().CPlusPlus &&
7577       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7578     NewVD->setPreviousDeclInSameBlockScope(
7579         Previous.isSingleResult() && !Previous.isShadowed() &&
7580         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7581 
7582   if (!getLangOpts().CPlusPlus) {
7583     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7584   } else {
7585     // If this is an explicit specialization of a static data member, check it.
7586     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7587         CheckMemberSpecialization(NewVD, Previous))
7588       NewVD->setInvalidDecl();
7589 
7590     // Merge the decl with the existing one if appropriate.
7591     if (!Previous.empty()) {
7592       if (Previous.isSingleResult() &&
7593           isa<FieldDecl>(Previous.getFoundDecl()) &&
7594           D.getCXXScopeSpec().isSet()) {
7595         // The user tried to define a non-static data member
7596         // out-of-line (C++ [dcl.meaning]p1).
7597         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7598           << D.getCXXScopeSpec().getRange();
7599         Previous.clear();
7600         NewVD->setInvalidDecl();
7601       }
7602     } else if (D.getCXXScopeSpec().isSet()) {
7603       // No previous declaration in the qualifying scope.
7604       Diag(D.getIdentifierLoc(), diag::err_no_member)
7605         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7606         << D.getCXXScopeSpec().getRange();
7607       NewVD->setInvalidDecl();
7608     }
7609 
7610     if (!IsVariableTemplateSpecialization)
7611       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7612 
7613     if (NewTemplate) {
7614       VarTemplateDecl *PrevVarTemplate =
7615           NewVD->getPreviousDecl()
7616               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7617               : nullptr;
7618 
7619       // Check the template parameter list of this declaration, possibly
7620       // merging in the template parameter list from the previous variable
7621       // template declaration.
7622       if (CheckTemplateParameterList(
7623               TemplateParams,
7624               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7625                               : nullptr,
7626               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7627                DC->isDependentContext())
7628                   ? TPC_ClassTemplateMember
7629                   : TPC_VarTemplate))
7630         NewVD->setInvalidDecl();
7631 
7632       // If we are providing an explicit specialization of a static variable
7633       // template, make a note of that.
7634       if (PrevVarTemplate &&
7635           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7636         PrevVarTemplate->setMemberSpecialization();
7637     }
7638   }
7639 
7640   // Diagnose shadowed variables iff this isn't a redeclaration.
7641   if (ShadowedDecl && !D.isRedeclaration())
7642     CheckShadow(NewVD, ShadowedDecl, Previous);
7643 
7644   ProcessPragmaWeak(S, NewVD);
7645 
7646   // If this is the first declaration of an extern C variable, update
7647   // the map of such variables.
7648   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7649       isIncompleteDeclExternC(*this, NewVD))
7650     RegisterLocallyScopedExternCDecl(NewVD, S);
7651 
7652   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7653     MangleNumberingContext *MCtx;
7654     Decl *ManglingContextDecl;
7655     std::tie(MCtx, ManglingContextDecl) =
7656         getCurrentMangleNumberContext(NewVD->getDeclContext());
7657     if (MCtx) {
7658       Context.setManglingNumber(
7659           NewVD, MCtx->getManglingNumber(
7660                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7661       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7662     }
7663   }
7664 
7665   // Special handling of variable named 'main'.
7666   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7667       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7668       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7669 
7670     // C++ [basic.start.main]p3
7671     // A program that declares a variable main at global scope is ill-formed.
7672     if (getLangOpts().CPlusPlus)
7673       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7674 
7675     // In C, and external-linkage variable named main results in undefined
7676     // behavior.
7677     else if (NewVD->hasExternalFormalLinkage())
7678       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7679   }
7680 
7681   if (D.isRedeclaration() && !Previous.empty()) {
7682     NamedDecl *Prev = Previous.getRepresentativeDecl();
7683     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7684                                    D.isFunctionDefinition());
7685   }
7686 
7687   if (NewTemplate) {
7688     if (NewVD->isInvalidDecl())
7689       NewTemplate->setInvalidDecl();
7690     ActOnDocumentableDecl(NewTemplate);
7691     return NewTemplate;
7692   }
7693 
7694   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7695     CompleteMemberSpecialization(NewVD, Previous);
7696 
7697   return NewVD;
7698 }
7699 
7700 /// Enum describing the %select options in diag::warn_decl_shadow.
7701 enum ShadowedDeclKind {
7702   SDK_Local,
7703   SDK_Global,
7704   SDK_StaticMember,
7705   SDK_Field,
7706   SDK_Typedef,
7707   SDK_Using,
7708   SDK_StructuredBinding
7709 };
7710 
7711 /// Determine what kind of declaration we're shadowing.
7712 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7713                                                 const DeclContext *OldDC) {
7714   if (isa<TypeAliasDecl>(ShadowedDecl))
7715     return SDK_Using;
7716   else if (isa<TypedefDecl>(ShadowedDecl))
7717     return SDK_Typedef;
7718   else if (isa<BindingDecl>(ShadowedDecl))
7719     return SDK_StructuredBinding;
7720   else if (isa<RecordDecl>(OldDC))
7721     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7722 
7723   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7724 }
7725 
7726 /// Return the location of the capture if the given lambda captures the given
7727 /// variable \p VD, or an invalid source location otherwise.
7728 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7729                                          const VarDecl *VD) {
7730   for (const Capture &Capture : LSI->Captures) {
7731     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7732       return Capture.getLocation();
7733   }
7734   return SourceLocation();
7735 }
7736 
7737 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7738                                      const LookupResult &R) {
7739   // Only diagnose if we're shadowing an unambiguous field or variable.
7740   if (R.getResultKind() != LookupResult::Found)
7741     return false;
7742 
7743   // Return false if warning is ignored.
7744   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7745 }
7746 
7747 /// Return the declaration shadowed by the given variable \p D, or null
7748 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7749 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7750                                         const LookupResult &R) {
7751   if (!shouldWarnIfShadowedDecl(Diags, R))
7752     return nullptr;
7753 
7754   // Don't diagnose declarations at file scope.
7755   if (D->hasGlobalStorage())
7756     return nullptr;
7757 
7758   NamedDecl *ShadowedDecl = R.getFoundDecl();
7759   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7760                                                             : nullptr;
7761 }
7762 
7763 /// Return the declaration shadowed by the given typedef \p D, or null
7764 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7765 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7766                                         const LookupResult &R) {
7767   // Don't warn if typedef declaration is part of a class
7768   if (D->getDeclContext()->isRecord())
7769     return nullptr;
7770 
7771   if (!shouldWarnIfShadowedDecl(Diags, R))
7772     return nullptr;
7773 
7774   NamedDecl *ShadowedDecl = R.getFoundDecl();
7775   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7776 }
7777 
7778 /// Return the declaration shadowed by the given variable \p D, or null
7779 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7780 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7781                                         const LookupResult &R) {
7782   if (!shouldWarnIfShadowedDecl(Diags, R))
7783     return nullptr;
7784 
7785   NamedDecl *ShadowedDecl = R.getFoundDecl();
7786   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7787                                                             : nullptr;
7788 }
7789 
7790 /// Diagnose variable or built-in function shadowing.  Implements
7791 /// -Wshadow.
7792 ///
7793 /// This method is called whenever a VarDecl is added to a "useful"
7794 /// scope.
7795 ///
7796 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7797 /// \param R the lookup of the name
7798 ///
7799 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7800                        const LookupResult &R) {
7801   DeclContext *NewDC = D->getDeclContext();
7802 
7803   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7804     // Fields are not shadowed by variables in C++ static methods.
7805     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7806       if (MD->isStatic())
7807         return;
7808 
7809     // Fields shadowed by constructor parameters are a special case. Usually
7810     // the constructor initializes the field with the parameter.
7811     if (isa<CXXConstructorDecl>(NewDC))
7812       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7813         // Remember that this was shadowed so we can either warn about its
7814         // modification or its existence depending on warning settings.
7815         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7816         return;
7817       }
7818   }
7819 
7820   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7821     if (shadowedVar->isExternC()) {
7822       // For shadowing external vars, make sure that we point to the global
7823       // declaration, not a locally scoped extern declaration.
7824       for (auto I : shadowedVar->redecls())
7825         if (I->isFileVarDecl()) {
7826           ShadowedDecl = I;
7827           break;
7828         }
7829     }
7830 
7831   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7832 
7833   unsigned WarningDiag = diag::warn_decl_shadow;
7834   SourceLocation CaptureLoc;
7835   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7836       isa<CXXMethodDecl>(NewDC)) {
7837     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7838       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7839         if (RD->getLambdaCaptureDefault() == LCD_None) {
7840           // Try to avoid warnings for lambdas with an explicit capture list.
7841           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7842           // Warn only when the lambda captures the shadowed decl explicitly.
7843           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7844           if (CaptureLoc.isInvalid())
7845             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7846         } else {
7847           // Remember that this was shadowed so we can avoid the warning if the
7848           // shadowed decl isn't captured and the warning settings allow it.
7849           cast<LambdaScopeInfo>(getCurFunction())
7850               ->ShadowingDecls.push_back(
7851                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7852           return;
7853         }
7854       }
7855 
7856       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7857         // A variable can't shadow a local variable in an enclosing scope, if
7858         // they are separated by a non-capturing declaration context.
7859         for (DeclContext *ParentDC = NewDC;
7860              ParentDC && !ParentDC->Equals(OldDC);
7861              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7862           // Only block literals, captured statements, and lambda expressions
7863           // can capture; other scopes don't.
7864           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7865               !isLambdaCallOperator(ParentDC)) {
7866             return;
7867           }
7868         }
7869       }
7870     }
7871   }
7872 
7873   // Only warn about certain kinds of shadowing for class members.
7874   if (NewDC && NewDC->isRecord()) {
7875     // In particular, don't warn about shadowing non-class members.
7876     if (!OldDC->isRecord())
7877       return;
7878 
7879     // TODO: should we warn about static data members shadowing
7880     // static data members from base classes?
7881 
7882     // TODO: don't diagnose for inaccessible shadowed members.
7883     // This is hard to do perfectly because we might friend the
7884     // shadowing context, but that's just a false negative.
7885   }
7886 
7887 
7888   DeclarationName Name = R.getLookupName();
7889 
7890   // Emit warning and note.
7891   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7892   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7893   if (!CaptureLoc.isInvalid())
7894     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7895         << Name << /*explicitly*/ 1;
7896   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7897 }
7898 
7899 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7900 /// when these variables are captured by the lambda.
7901 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7902   for (const auto &Shadow : LSI->ShadowingDecls) {
7903     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7904     // Try to avoid the warning when the shadowed decl isn't captured.
7905     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7906     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7907     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7908                                        ? diag::warn_decl_shadow_uncaptured_local
7909                                        : diag::warn_decl_shadow)
7910         << Shadow.VD->getDeclName()
7911         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7912     if (!CaptureLoc.isInvalid())
7913       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7914           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7915     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7916   }
7917 }
7918 
7919 /// Check -Wshadow without the advantage of a previous lookup.
7920 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7921   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7922     return;
7923 
7924   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7925                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7926   LookupName(R, S);
7927   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7928     CheckShadow(D, ShadowedDecl, R);
7929 }
7930 
7931 /// Check if 'E', which is an expression that is about to be modified, refers
7932 /// to a constructor parameter that shadows a field.
7933 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7934   // Quickly ignore expressions that can't be shadowing ctor parameters.
7935   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7936     return;
7937   E = E->IgnoreParenImpCasts();
7938   auto *DRE = dyn_cast<DeclRefExpr>(E);
7939   if (!DRE)
7940     return;
7941   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7942   auto I = ShadowingDecls.find(D);
7943   if (I == ShadowingDecls.end())
7944     return;
7945   const NamedDecl *ShadowedDecl = I->second;
7946   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7947   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7948   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7949   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7950 
7951   // Avoid issuing multiple warnings about the same decl.
7952   ShadowingDecls.erase(I);
7953 }
7954 
7955 /// Check for conflict between this global or extern "C" declaration and
7956 /// previous global or extern "C" declarations. This is only used in C++.
7957 template<typename T>
7958 static bool checkGlobalOrExternCConflict(
7959     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7960   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7961   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7962 
7963   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7964     // The common case: this global doesn't conflict with any extern "C"
7965     // declaration.
7966     return false;
7967   }
7968 
7969   if (Prev) {
7970     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7971       // Both the old and new declarations have C language linkage. This is a
7972       // redeclaration.
7973       Previous.clear();
7974       Previous.addDecl(Prev);
7975       return true;
7976     }
7977 
7978     // This is a global, non-extern "C" declaration, and there is a previous
7979     // non-global extern "C" declaration. Diagnose if this is a variable
7980     // declaration.
7981     if (!isa<VarDecl>(ND))
7982       return false;
7983   } else {
7984     // The declaration is extern "C". Check for any declaration in the
7985     // translation unit which might conflict.
7986     if (IsGlobal) {
7987       // We have already performed the lookup into the translation unit.
7988       IsGlobal = false;
7989       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7990            I != E; ++I) {
7991         if (isa<VarDecl>(*I)) {
7992           Prev = *I;
7993           break;
7994         }
7995       }
7996     } else {
7997       DeclContext::lookup_result R =
7998           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7999       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8000            I != E; ++I) {
8001         if (isa<VarDecl>(*I)) {
8002           Prev = *I;
8003           break;
8004         }
8005         // FIXME: If we have any other entity with this name in global scope,
8006         // the declaration is ill-formed, but that is a defect: it breaks the
8007         // 'stat' hack, for instance. Only variables can have mangled name
8008         // clashes with extern "C" declarations, so only they deserve a
8009         // diagnostic.
8010       }
8011     }
8012 
8013     if (!Prev)
8014       return false;
8015   }
8016 
8017   // Use the first declaration's location to ensure we point at something which
8018   // is lexically inside an extern "C" linkage-spec.
8019   assert(Prev && "should have found a previous declaration to diagnose");
8020   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8021     Prev = FD->getFirstDecl();
8022   else
8023     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8024 
8025   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8026     << IsGlobal << ND;
8027   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8028     << IsGlobal;
8029   return false;
8030 }
8031 
8032 /// Apply special rules for handling extern "C" declarations. Returns \c true
8033 /// if we have found that this is a redeclaration of some prior entity.
8034 ///
8035 /// Per C++ [dcl.link]p6:
8036 ///   Two declarations [for a function or variable] with C language linkage
8037 ///   with the same name that appear in different scopes refer to the same
8038 ///   [entity]. An entity with C language linkage shall not be declared with
8039 ///   the same name as an entity in global scope.
8040 template<typename T>
8041 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8042                                                   LookupResult &Previous) {
8043   if (!S.getLangOpts().CPlusPlus) {
8044     // In C, when declaring a global variable, look for a corresponding 'extern'
8045     // variable declared in function scope. We don't need this in C++, because
8046     // we find local extern decls in the surrounding file-scope DeclContext.
8047     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8048       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8049         Previous.clear();
8050         Previous.addDecl(Prev);
8051         return true;
8052       }
8053     }
8054     return false;
8055   }
8056 
8057   // A declaration in the translation unit can conflict with an extern "C"
8058   // declaration.
8059   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8060     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8061 
8062   // An extern "C" declaration can conflict with a declaration in the
8063   // translation unit or can be a redeclaration of an extern "C" declaration
8064   // in another scope.
8065   if (isIncompleteDeclExternC(S,ND))
8066     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8067 
8068   // Neither global nor extern "C": nothing to do.
8069   return false;
8070 }
8071 
8072 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8073   // If the decl is already known invalid, don't check it.
8074   if (NewVD->isInvalidDecl())
8075     return;
8076 
8077   QualType T = NewVD->getType();
8078 
8079   // Defer checking an 'auto' type until its initializer is attached.
8080   if (T->isUndeducedType())
8081     return;
8082 
8083   if (NewVD->hasAttrs())
8084     CheckAlignasUnderalignment(NewVD);
8085 
8086   if (T->isObjCObjectType()) {
8087     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8088       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8089     T = Context.getObjCObjectPointerType(T);
8090     NewVD->setType(T);
8091   }
8092 
8093   // Emit an error if an address space was applied to decl with local storage.
8094   // This includes arrays of objects with address space qualifiers, but not
8095   // automatic variables that point to other address spaces.
8096   // ISO/IEC TR 18037 S5.1.2
8097   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8098       T.getAddressSpace() != LangAS::Default) {
8099     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8100     NewVD->setInvalidDecl();
8101     return;
8102   }
8103 
8104   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8105   // scope.
8106   if (getLangOpts().OpenCLVersion == 120 &&
8107       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8108                                             getLangOpts()) &&
8109       NewVD->isStaticLocal()) {
8110     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8111     NewVD->setInvalidDecl();
8112     return;
8113   }
8114 
8115   if (getLangOpts().OpenCL) {
8116     if (!diagnoseOpenCLTypes(*this, NewVD))
8117       return;
8118 
8119     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8120     if (NewVD->hasAttr<BlocksAttr>()) {
8121       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8122       return;
8123     }
8124 
8125     if (T->isBlockPointerType()) {
8126       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8127       // can't use 'extern' storage class.
8128       if (!T.isConstQualified()) {
8129         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8130             << 0 /*const*/;
8131         NewVD->setInvalidDecl();
8132         return;
8133       }
8134       if (NewVD->hasExternalStorage()) {
8135         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8136         NewVD->setInvalidDecl();
8137         return;
8138       }
8139     }
8140 
8141     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8142     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8143         NewVD->hasExternalStorage()) {
8144       if (!T->isSamplerT() && !T->isDependentType() &&
8145           !(T.getAddressSpace() == LangAS::opencl_constant ||
8146             (T.getAddressSpace() == LangAS::opencl_global &&
8147              getOpenCLOptions().areProgramScopeVariablesSupported(
8148                  getLangOpts())))) {
8149         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8150         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8151           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8152               << Scope << "global or constant";
8153         else
8154           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8155               << Scope << "constant";
8156         NewVD->setInvalidDecl();
8157         return;
8158       }
8159     } else {
8160       if (T.getAddressSpace() == LangAS::opencl_global) {
8161         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8162             << 1 /*is any function*/ << "global";
8163         NewVD->setInvalidDecl();
8164         return;
8165       }
8166       if (T.getAddressSpace() == LangAS::opencl_constant ||
8167           T.getAddressSpace() == LangAS::opencl_local) {
8168         FunctionDecl *FD = getCurFunctionDecl();
8169         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8170         // in functions.
8171         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8172           if (T.getAddressSpace() == LangAS::opencl_constant)
8173             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8174                 << 0 /*non-kernel only*/ << "constant";
8175           else
8176             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8177                 << 0 /*non-kernel only*/ << "local";
8178           NewVD->setInvalidDecl();
8179           return;
8180         }
8181         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8182         // in the outermost scope of a kernel function.
8183         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8184           if (!getCurScope()->isFunctionScope()) {
8185             if (T.getAddressSpace() == LangAS::opencl_constant)
8186               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8187                   << "constant";
8188             else
8189               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8190                   << "local";
8191             NewVD->setInvalidDecl();
8192             return;
8193           }
8194         }
8195       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8196                  // If we are parsing a template we didn't deduce an addr
8197                  // space yet.
8198                  T.getAddressSpace() != LangAS::Default) {
8199         // Do not allow other address spaces on automatic variable.
8200         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8201         NewVD->setInvalidDecl();
8202         return;
8203       }
8204     }
8205   }
8206 
8207   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8208       && !NewVD->hasAttr<BlocksAttr>()) {
8209     if (getLangOpts().getGC() != LangOptions::NonGC)
8210       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8211     else {
8212       assert(!getLangOpts().ObjCAutoRefCount);
8213       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8214     }
8215   }
8216 
8217   bool isVM = T->isVariablyModifiedType();
8218   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8219       NewVD->hasAttr<BlocksAttr>())
8220     setFunctionHasBranchProtectedScope();
8221 
8222   if ((isVM && NewVD->hasLinkage()) ||
8223       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8224     bool SizeIsNegative;
8225     llvm::APSInt Oversized;
8226     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8227         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8228     QualType FixedT;
8229     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8230       FixedT = FixedTInfo->getType();
8231     else if (FixedTInfo) {
8232       // Type and type-as-written are canonically different. We need to fix up
8233       // both types separately.
8234       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8235                                                    Oversized);
8236     }
8237     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8238       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8239       // FIXME: This won't give the correct result for
8240       // int a[10][n];
8241       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8242 
8243       if (NewVD->isFileVarDecl())
8244         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8245         << SizeRange;
8246       else if (NewVD->isStaticLocal())
8247         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8248         << SizeRange;
8249       else
8250         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8251         << SizeRange;
8252       NewVD->setInvalidDecl();
8253       return;
8254     }
8255 
8256     if (!FixedTInfo) {
8257       if (NewVD->isFileVarDecl())
8258         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8259       else
8260         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8261       NewVD->setInvalidDecl();
8262       return;
8263     }
8264 
8265     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8266     NewVD->setType(FixedT);
8267     NewVD->setTypeSourceInfo(FixedTInfo);
8268   }
8269 
8270   if (T->isVoidType()) {
8271     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8272     //                    of objects and functions.
8273     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8274       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8275         << T;
8276       NewVD->setInvalidDecl();
8277       return;
8278     }
8279   }
8280 
8281   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8282     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8283     NewVD->setInvalidDecl();
8284     return;
8285   }
8286 
8287   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8288     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8289     NewVD->setInvalidDecl();
8290     return;
8291   }
8292 
8293   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8294     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8295     NewVD->setInvalidDecl();
8296     return;
8297   }
8298 
8299   if (NewVD->isConstexpr() && !T->isDependentType() &&
8300       RequireLiteralType(NewVD->getLocation(), T,
8301                          diag::err_constexpr_var_non_literal)) {
8302     NewVD->setInvalidDecl();
8303     return;
8304   }
8305 
8306   // PPC MMA non-pointer types are not allowed as non-local variable types.
8307   if (Context.getTargetInfo().getTriple().isPPC64() &&
8308       !NewVD->isLocalVarDecl() &&
8309       CheckPPCMMAType(T, NewVD->getLocation())) {
8310     NewVD->setInvalidDecl();
8311     return;
8312   }
8313 }
8314 
8315 /// Perform semantic checking on a newly-created variable
8316 /// declaration.
8317 ///
8318 /// This routine performs all of the type-checking required for a
8319 /// variable declaration once it has been built. It is used both to
8320 /// check variables after they have been parsed and their declarators
8321 /// have been translated into a declaration, and to check variables
8322 /// that have been instantiated from a template.
8323 ///
8324 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8325 ///
8326 /// Returns true if the variable declaration is a redeclaration.
8327 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8328   CheckVariableDeclarationType(NewVD);
8329 
8330   // If the decl is already known invalid, don't check it.
8331   if (NewVD->isInvalidDecl())
8332     return false;
8333 
8334   // If we did not find anything by this name, look for a non-visible
8335   // extern "C" declaration with the same name.
8336   if (Previous.empty() &&
8337       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8338     Previous.setShadowed();
8339 
8340   if (!Previous.empty()) {
8341     MergeVarDecl(NewVD, Previous);
8342     return true;
8343   }
8344   return false;
8345 }
8346 
8347 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8348 /// and if so, check that it's a valid override and remember it.
8349 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8350   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8351 
8352   // Look for methods in base classes that this method might override.
8353   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8354                      /*DetectVirtual=*/false);
8355   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8356     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8357     DeclarationName Name = MD->getDeclName();
8358 
8359     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8360       // We really want to find the base class destructor here.
8361       QualType T = Context.getTypeDeclType(BaseRecord);
8362       CanQualType CT = Context.getCanonicalType(T);
8363       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8364     }
8365 
8366     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8367       CXXMethodDecl *BaseMD =
8368           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8369       if (!BaseMD || !BaseMD->isVirtual() ||
8370           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8371                      /*ConsiderCudaAttrs=*/true,
8372                      // C++2a [class.virtual]p2 does not consider requires
8373                      // clauses when overriding.
8374                      /*ConsiderRequiresClauses=*/false))
8375         continue;
8376 
8377       if (Overridden.insert(BaseMD).second) {
8378         MD->addOverriddenMethod(BaseMD);
8379         CheckOverridingFunctionReturnType(MD, BaseMD);
8380         CheckOverridingFunctionAttributes(MD, BaseMD);
8381         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8382         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8383       }
8384 
8385       // A method can only override one function from each base class. We
8386       // don't track indirectly overridden methods from bases of bases.
8387       return true;
8388     }
8389 
8390     return false;
8391   };
8392 
8393   DC->lookupInBases(VisitBase, Paths);
8394   return !Overridden.empty();
8395 }
8396 
8397 namespace {
8398   // Struct for holding all of the extra arguments needed by
8399   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8400   struct ActOnFDArgs {
8401     Scope *S;
8402     Declarator &D;
8403     MultiTemplateParamsArg TemplateParamLists;
8404     bool AddToScope;
8405   };
8406 } // end anonymous namespace
8407 
8408 namespace {
8409 
8410 // Callback to only accept typo corrections that have a non-zero edit distance.
8411 // Also only accept corrections that have the same parent decl.
8412 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8413  public:
8414   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8415                             CXXRecordDecl *Parent)
8416       : Context(Context), OriginalFD(TypoFD),
8417         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8418 
8419   bool ValidateCandidate(const TypoCorrection &candidate) override {
8420     if (candidate.getEditDistance() == 0)
8421       return false;
8422 
8423     SmallVector<unsigned, 1> MismatchedParams;
8424     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8425                                           CDeclEnd = candidate.end();
8426          CDecl != CDeclEnd; ++CDecl) {
8427       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8428 
8429       if (FD && !FD->hasBody() &&
8430           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8431         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8432           CXXRecordDecl *Parent = MD->getParent();
8433           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8434             return true;
8435         } else if (!ExpectedParent) {
8436           return true;
8437         }
8438       }
8439     }
8440 
8441     return false;
8442   }
8443 
8444   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8445     return std::make_unique<DifferentNameValidatorCCC>(*this);
8446   }
8447 
8448  private:
8449   ASTContext &Context;
8450   FunctionDecl *OriginalFD;
8451   CXXRecordDecl *ExpectedParent;
8452 };
8453 
8454 } // end anonymous namespace
8455 
8456 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8457   TypoCorrectedFunctionDefinitions.insert(F);
8458 }
8459 
8460 /// Generate diagnostics for an invalid function redeclaration.
8461 ///
8462 /// This routine handles generating the diagnostic messages for an invalid
8463 /// function redeclaration, including finding possible similar declarations
8464 /// or performing typo correction if there are no previous declarations with
8465 /// the same name.
8466 ///
8467 /// Returns a NamedDecl iff typo correction was performed and substituting in
8468 /// the new declaration name does not cause new errors.
8469 static NamedDecl *DiagnoseInvalidRedeclaration(
8470     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8471     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8472   DeclarationName Name = NewFD->getDeclName();
8473   DeclContext *NewDC = NewFD->getDeclContext();
8474   SmallVector<unsigned, 1> MismatchedParams;
8475   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8476   TypoCorrection Correction;
8477   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8478   unsigned DiagMsg =
8479     IsLocalFriend ? diag::err_no_matching_local_friend :
8480     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8481     diag::err_member_decl_does_not_match;
8482   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8483                     IsLocalFriend ? Sema::LookupLocalFriendName
8484                                   : Sema::LookupOrdinaryName,
8485                     Sema::ForVisibleRedeclaration);
8486 
8487   NewFD->setInvalidDecl();
8488   if (IsLocalFriend)
8489     SemaRef.LookupName(Prev, S);
8490   else
8491     SemaRef.LookupQualifiedName(Prev, NewDC);
8492   assert(!Prev.isAmbiguous() &&
8493          "Cannot have an ambiguity in previous-declaration lookup");
8494   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8495   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8496                                 MD ? MD->getParent() : nullptr);
8497   if (!Prev.empty()) {
8498     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8499          Func != FuncEnd; ++Func) {
8500       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8501       if (FD &&
8502           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8503         // Add 1 to the index so that 0 can mean the mismatch didn't
8504         // involve a parameter
8505         unsigned ParamNum =
8506             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8507         NearMatches.push_back(std::make_pair(FD, ParamNum));
8508       }
8509     }
8510   // If the qualified name lookup yielded nothing, try typo correction
8511   } else if ((Correction = SemaRef.CorrectTypo(
8512                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8513                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8514                   IsLocalFriend ? nullptr : NewDC))) {
8515     // Set up everything for the call to ActOnFunctionDeclarator
8516     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8517                               ExtraArgs.D.getIdentifierLoc());
8518     Previous.clear();
8519     Previous.setLookupName(Correction.getCorrection());
8520     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8521                                     CDeclEnd = Correction.end();
8522          CDecl != CDeclEnd; ++CDecl) {
8523       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8524       if (FD && !FD->hasBody() &&
8525           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8526         Previous.addDecl(FD);
8527       }
8528     }
8529     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8530 
8531     NamedDecl *Result;
8532     // Retry building the function declaration with the new previous
8533     // declarations, and with errors suppressed.
8534     {
8535       // Trap errors.
8536       Sema::SFINAETrap Trap(SemaRef);
8537 
8538       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8539       // pieces need to verify the typo-corrected C++ declaration and hopefully
8540       // eliminate the need for the parameter pack ExtraArgs.
8541       Result = SemaRef.ActOnFunctionDeclarator(
8542           ExtraArgs.S, ExtraArgs.D,
8543           Correction.getCorrectionDecl()->getDeclContext(),
8544           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8545           ExtraArgs.AddToScope);
8546 
8547       if (Trap.hasErrorOccurred())
8548         Result = nullptr;
8549     }
8550 
8551     if (Result) {
8552       // Determine which correction we picked.
8553       Decl *Canonical = Result->getCanonicalDecl();
8554       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8555            I != E; ++I)
8556         if ((*I)->getCanonicalDecl() == Canonical)
8557           Correction.setCorrectionDecl(*I);
8558 
8559       // Let Sema know about the correction.
8560       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8561       SemaRef.diagnoseTypo(
8562           Correction,
8563           SemaRef.PDiag(IsLocalFriend
8564                           ? diag::err_no_matching_local_friend_suggest
8565                           : diag::err_member_decl_does_not_match_suggest)
8566             << Name << NewDC << IsDefinition);
8567       return Result;
8568     }
8569 
8570     // Pretend the typo correction never occurred
8571     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8572                               ExtraArgs.D.getIdentifierLoc());
8573     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8574     Previous.clear();
8575     Previous.setLookupName(Name);
8576   }
8577 
8578   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8579       << Name << NewDC << IsDefinition << NewFD->getLocation();
8580 
8581   bool NewFDisConst = false;
8582   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8583     NewFDisConst = NewMD->isConst();
8584 
8585   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8586        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8587        NearMatch != NearMatchEnd; ++NearMatch) {
8588     FunctionDecl *FD = NearMatch->first;
8589     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8590     bool FDisConst = MD && MD->isConst();
8591     bool IsMember = MD || !IsLocalFriend;
8592 
8593     // FIXME: These notes are poorly worded for the local friend case.
8594     if (unsigned Idx = NearMatch->second) {
8595       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8596       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8597       if (Loc.isInvalid()) Loc = FD->getLocation();
8598       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8599                                  : diag::note_local_decl_close_param_match)
8600         << Idx << FDParam->getType()
8601         << NewFD->getParamDecl(Idx - 1)->getType();
8602     } else if (FDisConst != NewFDisConst) {
8603       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8604           << NewFDisConst << FD->getSourceRange().getEnd()
8605           << (NewFDisConst
8606                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8607                                                  .getConstQualifierLoc())
8608                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8609                                                    .getRParenLoc()
8610                                                    .getLocWithOffset(1),
8611                                                " const"));
8612     } else
8613       SemaRef.Diag(FD->getLocation(),
8614                    IsMember ? diag::note_member_def_close_match
8615                             : diag::note_local_decl_close_match);
8616   }
8617   return nullptr;
8618 }
8619 
8620 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8621   switch (D.getDeclSpec().getStorageClassSpec()) {
8622   default: llvm_unreachable("Unknown storage class!");
8623   case DeclSpec::SCS_auto:
8624   case DeclSpec::SCS_register:
8625   case DeclSpec::SCS_mutable:
8626     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8627                  diag::err_typecheck_sclass_func);
8628     D.getMutableDeclSpec().ClearStorageClassSpecs();
8629     D.setInvalidType();
8630     break;
8631   case DeclSpec::SCS_unspecified: break;
8632   case DeclSpec::SCS_extern:
8633     if (D.getDeclSpec().isExternInLinkageSpec())
8634       return SC_None;
8635     return SC_Extern;
8636   case DeclSpec::SCS_static: {
8637     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8638       // C99 6.7.1p5:
8639       //   The declaration of an identifier for a function that has
8640       //   block scope shall have no explicit storage-class specifier
8641       //   other than extern
8642       // See also (C++ [dcl.stc]p4).
8643       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8644                    diag::err_static_block_func);
8645       break;
8646     } else
8647       return SC_Static;
8648   }
8649   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8650   }
8651 
8652   // No explicit storage class has already been returned
8653   return SC_None;
8654 }
8655 
8656 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8657                                            DeclContext *DC, QualType &R,
8658                                            TypeSourceInfo *TInfo,
8659                                            StorageClass SC,
8660                                            bool &IsVirtualOkay) {
8661   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8662   DeclarationName Name = NameInfo.getName();
8663 
8664   FunctionDecl *NewFD = nullptr;
8665   bool isInline = D.getDeclSpec().isInlineSpecified();
8666 
8667   if (!SemaRef.getLangOpts().CPlusPlus) {
8668     // Determine whether the function was written with a
8669     // prototype. This true when:
8670     //   - there is a prototype in the declarator, or
8671     //   - the type R of the function is some kind of typedef or other non-
8672     //     attributed reference to a type name (which eventually refers to a
8673     //     function type).
8674     bool HasPrototype =
8675       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8676       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8677 
8678     NewFD = FunctionDecl::Create(
8679         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8680         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8681         ConstexprSpecKind::Unspecified,
8682         /*TrailingRequiresClause=*/nullptr);
8683     if (D.isInvalidType())
8684       NewFD->setInvalidDecl();
8685 
8686     return NewFD;
8687   }
8688 
8689   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8690 
8691   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8692   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8693     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8694                  diag::err_constexpr_wrong_decl_kind)
8695         << static_cast<int>(ConstexprKind);
8696     ConstexprKind = ConstexprSpecKind::Unspecified;
8697     D.getMutableDeclSpec().ClearConstexprSpec();
8698   }
8699   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8700 
8701   // Check that the return type is not an abstract class type.
8702   // For record types, this is done by the AbstractClassUsageDiagnoser once
8703   // the class has been completely parsed.
8704   if (!DC->isRecord() &&
8705       SemaRef.RequireNonAbstractType(
8706           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8707           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8708     D.setInvalidType();
8709 
8710   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8711     // This is a C++ constructor declaration.
8712     assert(DC->isRecord() &&
8713            "Constructors can only be declared in a member context");
8714 
8715     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8716     return CXXConstructorDecl::Create(
8717         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8718         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8719         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8720         InheritedConstructor(), TrailingRequiresClause);
8721 
8722   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8723     // This is a C++ destructor declaration.
8724     if (DC->isRecord()) {
8725       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8726       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8727       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8728           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8729           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8730           /*isImplicitlyDeclared=*/false, ConstexprKind,
8731           TrailingRequiresClause);
8732 
8733       // If the destructor needs an implicit exception specification, set it
8734       // now. FIXME: It'd be nice to be able to create the right type to start
8735       // with, but the type needs to reference the destructor declaration.
8736       if (SemaRef.getLangOpts().CPlusPlus11)
8737         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8738 
8739       IsVirtualOkay = true;
8740       return NewDD;
8741 
8742     } else {
8743       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8744       D.setInvalidType();
8745 
8746       // Create a FunctionDecl to satisfy the function definition parsing
8747       // code path.
8748       return FunctionDecl::Create(
8749           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8750           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8751           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8752     }
8753 
8754   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8755     if (!DC->isRecord()) {
8756       SemaRef.Diag(D.getIdentifierLoc(),
8757            diag::err_conv_function_not_member);
8758       return nullptr;
8759     }
8760 
8761     SemaRef.CheckConversionDeclarator(D, R, SC);
8762     if (D.isInvalidType())
8763       return nullptr;
8764 
8765     IsVirtualOkay = true;
8766     return CXXConversionDecl::Create(
8767         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8768         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8769         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8770         TrailingRequiresClause);
8771 
8772   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8773     if (TrailingRequiresClause)
8774       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8775                    diag::err_trailing_requires_clause_on_deduction_guide)
8776           << TrailingRequiresClause->getSourceRange();
8777     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8778 
8779     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8780                                          ExplicitSpecifier, NameInfo, R, TInfo,
8781                                          D.getEndLoc());
8782   } else if (DC->isRecord()) {
8783     // If the name of the function is the same as the name of the record,
8784     // then this must be an invalid constructor that has a return type.
8785     // (The parser checks for a return type and makes the declarator a
8786     // constructor if it has no return type).
8787     if (Name.getAsIdentifierInfo() &&
8788         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8789       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8790         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8791         << SourceRange(D.getIdentifierLoc());
8792       return nullptr;
8793     }
8794 
8795     // This is a C++ method declaration.
8796     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8797         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8798         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8799         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8800     IsVirtualOkay = !Ret->isStatic();
8801     return Ret;
8802   } else {
8803     bool isFriend =
8804         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8805     if (!isFriend && SemaRef.CurContext->isRecord())
8806       return nullptr;
8807 
8808     // Determine whether the function was written with a
8809     // prototype. This true when:
8810     //   - we're in C++ (where every function has a prototype),
8811     return FunctionDecl::Create(
8812         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8813         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8814         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8815   }
8816 }
8817 
8818 enum OpenCLParamType {
8819   ValidKernelParam,
8820   PtrPtrKernelParam,
8821   PtrKernelParam,
8822   InvalidAddrSpacePtrKernelParam,
8823   InvalidKernelParam,
8824   RecordKernelParam
8825 };
8826 
8827 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8828   // Size dependent types are just typedefs to normal integer types
8829   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8830   // integers other than by their names.
8831   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8832 
8833   // Remove typedefs one by one until we reach a typedef
8834   // for a size dependent type.
8835   QualType DesugaredTy = Ty;
8836   do {
8837     ArrayRef<StringRef> Names(SizeTypeNames);
8838     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8839     if (Names.end() != Match)
8840       return true;
8841 
8842     Ty = DesugaredTy;
8843     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8844   } while (DesugaredTy != Ty);
8845 
8846   return false;
8847 }
8848 
8849 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8850   if (PT->isDependentType())
8851     return InvalidKernelParam;
8852 
8853   if (PT->isPointerType() || PT->isReferenceType()) {
8854     QualType PointeeType = PT->getPointeeType();
8855     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8856         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8857         PointeeType.getAddressSpace() == LangAS::Default)
8858       return InvalidAddrSpacePtrKernelParam;
8859 
8860     if (PointeeType->isPointerType()) {
8861       // This is a pointer to pointer parameter.
8862       // Recursively check inner type.
8863       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8864       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8865           ParamKind == InvalidKernelParam)
8866         return ParamKind;
8867 
8868       return PtrPtrKernelParam;
8869     }
8870 
8871     // C++ for OpenCL v1.0 s2.4:
8872     // Moreover the types used in parameters of the kernel functions must be:
8873     // Standard layout types for pointer parameters. The same applies to
8874     // reference if an implementation supports them in kernel parameters.
8875     if (S.getLangOpts().OpenCLCPlusPlus &&
8876         !S.getOpenCLOptions().isAvailableOption(
8877             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8878         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8879         !PointeeType->isStandardLayoutType())
8880       return InvalidKernelParam;
8881 
8882     return PtrKernelParam;
8883   }
8884 
8885   // OpenCL v1.2 s6.9.k:
8886   // Arguments to kernel functions in a program cannot be declared with the
8887   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8888   // uintptr_t or a struct and/or union that contain fields declared to be one
8889   // of these built-in scalar types.
8890   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8891     return InvalidKernelParam;
8892 
8893   if (PT->isImageType())
8894     return PtrKernelParam;
8895 
8896   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8897     return InvalidKernelParam;
8898 
8899   // OpenCL extension spec v1.2 s9.5:
8900   // This extension adds support for half scalar and vector types as built-in
8901   // types that can be used for arithmetic operations, conversions etc.
8902   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8903       PT->isHalfType())
8904     return InvalidKernelParam;
8905 
8906   // Look into an array argument to check if it has a forbidden type.
8907   if (PT->isArrayType()) {
8908     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8909     // Call ourself to check an underlying type of an array. Since the
8910     // getPointeeOrArrayElementType returns an innermost type which is not an
8911     // array, this recursive call only happens once.
8912     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8913   }
8914 
8915   // C++ for OpenCL v1.0 s2.4:
8916   // Moreover the types used in parameters of the kernel functions must be:
8917   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8918   // types) for parameters passed by value;
8919   if (S.getLangOpts().OpenCLCPlusPlus &&
8920       !S.getOpenCLOptions().isAvailableOption(
8921           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8922       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8923     return InvalidKernelParam;
8924 
8925   if (PT->isRecordType())
8926     return RecordKernelParam;
8927 
8928   return ValidKernelParam;
8929 }
8930 
8931 static void checkIsValidOpenCLKernelParameter(
8932   Sema &S,
8933   Declarator &D,
8934   ParmVarDecl *Param,
8935   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8936   QualType PT = Param->getType();
8937 
8938   // Cache the valid types we encounter to avoid rechecking structs that are
8939   // used again
8940   if (ValidTypes.count(PT.getTypePtr()))
8941     return;
8942 
8943   switch (getOpenCLKernelParameterType(S, PT)) {
8944   case PtrPtrKernelParam:
8945     // OpenCL v3.0 s6.11.a:
8946     // A kernel function argument cannot be declared as a pointer to a pointer
8947     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8948     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8949       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8950       D.setInvalidType();
8951       return;
8952     }
8953 
8954     ValidTypes.insert(PT.getTypePtr());
8955     return;
8956 
8957   case InvalidAddrSpacePtrKernelParam:
8958     // OpenCL v1.0 s6.5:
8959     // __kernel function arguments declared to be a pointer of a type can point
8960     // to one of the following address spaces only : __global, __local or
8961     // __constant.
8962     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8963     D.setInvalidType();
8964     return;
8965 
8966     // OpenCL v1.2 s6.9.k:
8967     // Arguments to kernel functions in a program cannot be declared with the
8968     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8969     // uintptr_t or a struct and/or union that contain fields declared to be
8970     // one of these built-in scalar types.
8971 
8972   case InvalidKernelParam:
8973     // OpenCL v1.2 s6.8 n:
8974     // A kernel function argument cannot be declared
8975     // of event_t type.
8976     // Do not diagnose half type since it is diagnosed as invalid argument
8977     // type for any function elsewhere.
8978     if (!PT->isHalfType()) {
8979       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8980 
8981       // Explain what typedefs are involved.
8982       const TypedefType *Typedef = nullptr;
8983       while ((Typedef = PT->getAs<TypedefType>())) {
8984         SourceLocation Loc = Typedef->getDecl()->getLocation();
8985         // SourceLocation may be invalid for a built-in type.
8986         if (Loc.isValid())
8987           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8988         PT = Typedef->desugar();
8989       }
8990     }
8991 
8992     D.setInvalidType();
8993     return;
8994 
8995   case PtrKernelParam:
8996   case ValidKernelParam:
8997     ValidTypes.insert(PT.getTypePtr());
8998     return;
8999 
9000   case RecordKernelParam:
9001     break;
9002   }
9003 
9004   // Track nested structs we will inspect
9005   SmallVector<const Decl *, 4> VisitStack;
9006 
9007   // Track where we are in the nested structs. Items will migrate from
9008   // VisitStack to HistoryStack as we do the DFS for bad field.
9009   SmallVector<const FieldDecl *, 4> HistoryStack;
9010   HistoryStack.push_back(nullptr);
9011 
9012   // At this point we already handled everything except of a RecordType or
9013   // an ArrayType of a RecordType.
9014   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9015   const RecordType *RecTy =
9016       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9017   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9018 
9019   VisitStack.push_back(RecTy->getDecl());
9020   assert(VisitStack.back() && "First decl null?");
9021 
9022   do {
9023     const Decl *Next = VisitStack.pop_back_val();
9024     if (!Next) {
9025       assert(!HistoryStack.empty());
9026       // Found a marker, we have gone up a level
9027       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9028         ValidTypes.insert(Hist->getType().getTypePtr());
9029 
9030       continue;
9031     }
9032 
9033     // Adds everything except the original parameter declaration (which is not a
9034     // field itself) to the history stack.
9035     const RecordDecl *RD;
9036     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9037       HistoryStack.push_back(Field);
9038 
9039       QualType FieldTy = Field->getType();
9040       // Other field types (known to be valid or invalid) are handled while we
9041       // walk around RecordDecl::fields().
9042       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9043              "Unexpected type.");
9044       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9045 
9046       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9047     } else {
9048       RD = cast<RecordDecl>(Next);
9049     }
9050 
9051     // Add a null marker so we know when we've gone back up a level
9052     VisitStack.push_back(nullptr);
9053 
9054     for (const auto *FD : RD->fields()) {
9055       QualType QT = FD->getType();
9056 
9057       if (ValidTypes.count(QT.getTypePtr()))
9058         continue;
9059 
9060       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9061       if (ParamType == ValidKernelParam)
9062         continue;
9063 
9064       if (ParamType == RecordKernelParam) {
9065         VisitStack.push_back(FD);
9066         continue;
9067       }
9068 
9069       // OpenCL v1.2 s6.9.p:
9070       // Arguments to kernel functions that are declared to be a struct or union
9071       // do not allow OpenCL objects to be passed as elements of the struct or
9072       // union.
9073       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9074           ParamType == InvalidAddrSpacePtrKernelParam) {
9075         S.Diag(Param->getLocation(),
9076                diag::err_record_with_pointers_kernel_param)
9077           << PT->isUnionType()
9078           << PT;
9079       } else {
9080         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9081       }
9082 
9083       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9084           << OrigRecDecl->getDeclName();
9085 
9086       // We have an error, now let's go back up through history and show where
9087       // the offending field came from
9088       for (ArrayRef<const FieldDecl *>::const_iterator
9089                I = HistoryStack.begin() + 1,
9090                E = HistoryStack.end();
9091            I != E; ++I) {
9092         const FieldDecl *OuterField = *I;
9093         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9094           << OuterField->getType();
9095       }
9096 
9097       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9098         << QT->isPointerType()
9099         << QT;
9100       D.setInvalidType();
9101       return;
9102     }
9103   } while (!VisitStack.empty());
9104 }
9105 
9106 /// Find the DeclContext in which a tag is implicitly declared if we see an
9107 /// elaborated type specifier in the specified context, and lookup finds
9108 /// nothing.
9109 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9110   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9111     DC = DC->getParent();
9112   return DC;
9113 }
9114 
9115 /// Find the Scope in which a tag is implicitly declared if we see an
9116 /// elaborated type specifier in the specified context, and lookup finds
9117 /// nothing.
9118 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9119   while (S->isClassScope() ||
9120          (LangOpts.CPlusPlus &&
9121           S->isFunctionPrototypeScope()) ||
9122          ((S->getFlags() & Scope::DeclScope) == 0) ||
9123          (S->getEntity() && S->getEntity()->isTransparentContext()))
9124     S = S->getParent();
9125   return S;
9126 }
9127 
9128 NamedDecl*
9129 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9130                               TypeSourceInfo *TInfo, LookupResult &Previous,
9131                               MultiTemplateParamsArg TemplateParamListsRef,
9132                               bool &AddToScope) {
9133   QualType R = TInfo->getType();
9134 
9135   assert(R->isFunctionType());
9136   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9137     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9138 
9139   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9140   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9141   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9142     if (!TemplateParamLists.empty() &&
9143         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9144       TemplateParamLists.back() = Invented;
9145     else
9146       TemplateParamLists.push_back(Invented);
9147   }
9148 
9149   // TODO: consider using NameInfo for diagnostic.
9150   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9151   DeclarationName Name = NameInfo.getName();
9152   StorageClass SC = getFunctionStorageClass(*this, D);
9153 
9154   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9155     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9156          diag::err_invalid_thread)
9157       << DeclSpec::getSpecifierName(TSCS);
9158 
9159   if (D.isFirstDeclarationOfMember())
9160     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9161                            D.getIdentifierLoc());
9162 
9163   bool isFriend = false;
9164   FunctionTemplateDecl *FunctionTemplate = nullptr;
9165   bool isMemberSpecialization = false;
9166   bool isFunctionTemplateSpecialization = false;
9167 
9168   bool isDependentClassScopeExplicitSpecialization = false;
9169   bool HasExplicitTemplateArgs = false;
9170   TemplateArgumentListInfo TemplateArgs;
9171 
9172   bool isVirtualOkay = false;
9173 
9174   DeclContext *OriginalDC = DC;
9175   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9176 
9177   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9178                                               isVirtualOkay);
9179   if (!NewFD) return nullptr;
9180 
9181   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9182     NewFD->setTopLevelDeclInObjCContainer();
9183 
9184   // Set the lexical context. If this is a function-scope declaration, or has a
9185   // C++ scope specifier, or is the object of a friend declaration, the lexical
9186   // context will be different from the semantic context.
9187   NewFD->setLexicalDeclContext(CurContext);
9188 
9189   if (IsLocalExternDecl)
9190     NewFD->setLocalExternDecl();
9191 
9192   if (getLangOpts().CPlusPlus) {
9193     bool isInline = D.getDeclSpec().isInlineSpecified();
9194     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9195     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9196     isFriend = D.getDeclSpec().isFriendSpecified();
9197     if (isFriend && !isInline && D.isFunctionDefinition()) {
9198       // C++ [class.friend]p5
9199       //   A function can be defined in a friend declaration of a
9200       //   class . . . . Such a function is implicitly inline.
9201       NewFD->setImplicitlyInline();
9202     }
9203 
9204     // If this is a method defined in an __interface, and is not a constructor
9205     // or an overloaded operator, then set the pure flag (isVirtual will already
9206     // return true).
9207     if (const CXXRecordDecl *Parent =
9208           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9209       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9210         NewFD->setPure(true);
9211 
9212       // C++ [class.union]p2
9213       //   A union can have member functions, but not virtual functions.
9214       if (isVirtual && Parent->isUnion()) {
9215         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9216         NewFD->setInvalidDecl();
9217       }
9218       if ((Parent->isClass() || Parent->isStruct()) &&
9219           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9220           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9221           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9222         if (auto *Def = Parent->getDefinition())
9223           Def->setInitMethod(true);
9224       }
9225     }
9226 
9227     SetNestedNameSpecifier(*this, NewFD, D);
9228     isMemberSpecialization = false;
9229     isFunctionTemplateSpecialization = false;
9230     if (D.isInvalidType())
9231       NewFD->setInvalidDecl();
9232 
9233     // Match up the template parameter lists with the scope specifier, then
9234     // determine whether we have a template or a template specialization.
9235     bool Invalid = false;
9236     TemplateParameterList *TemplateParams =
9237         MatchTemplateParametersToScopeSpecifier(
9238             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9239             D.getCXXScopeSpec(),
9240             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9241                 ? D.getName().TemplateId
9242                 : nullptr,
9243             TemplateParamLists, isFriend, isMemberSpecialization,
9244             Invalid);
9245     if (TemplateParams) {
9246       // Check that we can declare a template here.
9247       if (CheckTemplateDeclScope(S, TemplateParams))
9248         NewFD->setInvalidDecl();
9249 
9250       if (TemplateParams->size() > 0) {
9251         // This is a function template
9252 
9253         // A destructor cannot be a template.
9254         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9255           Diag(NewFD->getLocation(), diag::err_destructor_template);
9256           NewFD->setInvalidDecl();
9257         }
9258 
9259         // If we're adding a template to a dependent context, we may need to
9260         // rebuilding some of the types used within the template parameter list,
9261         // now that we know what the current instantiation is.
9262         if (DC->isDependentContext()) {
9263           ContextRAII SavedContext(*this, DC);
9264           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9265             Invalid = true;
9266         }
9267 
9268         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9269                                                         NewFD->getLocation(),
9270                                                         Name, TemplateParams,
9271                                                         NewFD);
9272         FunctionTemplate->setLexicalDeclContext(CurContext);
9273         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9274 
9275         // For source fidelity, store the other template param lists.
9276         if (TemplateParamLists.size() > 1) {
9277           NewFD->setTemplateParameterListsInfo(Context,
9278               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9279                   .drop_back(1));
9280         }
9281       } else {
9282         // This is a function template specialization.
9283         isFunctionTemplateSpecialization = true;
9284         // For source fidelity, store all the template param lists.
9285         if (TemplateParamLists.size() > 0)
9286           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9287 
9288         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9289         if (isFriend) {
9290           // We want to remove the "template<>", found here.
9291           SourceRange RemoveRange = TemplateParams->getSourceRange();
9292 
9293           // If we remove the template<> and the name is not a
9294           // template-id, we're actually silently creating a problem:
9295           // the friend declaration will refer to an untemplated decl,
9296           // and clearly the user wants a template specialization.  So
9297           // we need to insert '<>' after the name.
9298           SourceLocation InsertLoc;
9299           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9300             InsertLoc = D.getName().getSourceRange().getEnd();
9301             InsertLoc = getLocForEndOfToken(InsertLoc);
9302           }
9303 
9304           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9305             << Name << RemoveRange
9306             << FixItHint::CreateRemoval(RemoveRange)
9307             << FixItHint::CreateInsertion(InsertLoc, "<>");
9308           Invalid = true;
9309         }
9310       }
9311     } else {
9312       // Check that we can declare a template here.
9313       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9314           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9315         NewFD->setInvalidDecl();
9316 
9317       // All template param lists were matched against the scope specifier:
9318       // this is NOT (an explicit specialization of) a template.
9319       if (TemplateParamLists.size() > 0)
9320         // For source fidelity, store all the template param lists.
9321         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9322     }
9323 
9324     if (Invalid) {
9325       NewFD->setInvalidDecl();
9326       if (FunctionTemplate)
9327         FunctionTemplate->setInvalidDecl();
9328     }
9329 
9330     // C++ [dcl.fct.spec]p5:
9331     //   The virtual specifier shall only be used in declarations of
9332     //   nonstatic class member functions that appear within a
9333     //   member-specification of a class declaration; see 10.3.
9334     //
9335     if (isVirtual && !NewFD->isInvalidDecl()) {
9336       if (!isVirtualOkay) {
9337         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9338              diag::err_virtual_non_function);
9339       } else if (!CurContext->isRecord()) {
9340         // 'virtual' was specified outside of the class.
9341         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9342              diag::err_virtual_out_of_class)
9343           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9344       } else if (NewFD->getDescribedFunctionTemplate()) {
9345         // C++ [temp.mem]p3:
9346         //  A member function template shall not be virtual.
9347         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9348              diag::err_virtual_member_function_template)
9349           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9350       } else {
9351         // Okay: Add virtual to the method.
9352         NewFD->setVirtualAsWritten(true);
9353       }
9354 
9355       if (getLangOpts().CPlusPlus14 &&
9356           NewFD->getReturnType()->isUndeducedType())
9357         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9358     }
9359 
9360     if (getLangOpts().CPlusPlus14 &&
9361         (NewFD->isDependentContext() ||
9362          (isFriend && CurContext->isDependentContext())) &&
9363         NewFD->getReturnType()->isUndeducedType()) {
9364       // If the function template is referenced directly (for instance, as a
9365       // member of the current instantiation), pretend it has a dependent type.
9366       // This is not really justified by the standard, but is the only sane
9367       // thing to do.
9368       // FIXME: For a friend function, we have not marked the function as being
9369       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9370       const FunctionProtoType *FPT =
9371           NewFD->getType()->castAs<FunctionProtoType>();
9372       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9373       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9374                                              FPT->getExtProtoInfo()));
9375     }
9376 
9377     // C++ [dcl.fct.spec]p3:
9378     //  The inline specifier shall not appear on a block scope function
9379     //  declaration.
9380     if (isInline && !NewFD->isInvalidDecl()) {
9381       if (CurContext->isFunctionOrMethod()) {
9382         // 'inline' is not allowed on block scope function declaration.
9383         Diag(D.getDeclSpec().getInlineSpecLoc(),
9384              diag::err_inline_declaration_block_scope) << Name
9385           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9386       }
9387     }
9388 
9389     // C++ [dcl.fct.spec]p6:
9390     //  The explicit specifier shall be used only in the declaration of a
9391     //  constructor or conversion function within its class definition;
9392     //  see 12.3.1 and 12.3.2.
9393     if (hasExplicit && !NewFD->isInvalidDecl() &&
9394         !isa<CXXDeductionGuideDecl>(NewFD)) {
9395       if (!CurContext->isRecord()) {
9396         // 'explicit' was specified outside of the class.
9397         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9398              diag::err_explicit_out_of_class)
9399             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9400       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9401                  !isa<CXXConversionDecl>(NewFD)) {
9402         // 'explicit' was specified on a function that wasn't a constructor
9403         // or conversion function.
9404         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9405              diag::err_explicit_non_ctor_or_conv_function)
9406             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9407       }
9408     }
9409 
9410     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9411     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9412       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9413       // are implicitly inline.
9414       NewFD->setImplicitlyInline();
9415 
9416       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9417       // be either constructors or to return a literal type. Therefore,
9418       // destructors cannot be declared constexpr.
9419       if (isa<CXXDestructorDecl>(NewFD) &&
9420           (!getLangOpts().CPlusPlus20 ||
9421            ConstexprKind == ConstexprSpecKind::Consteval)) {
9422         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9423             << static_cast<int>(ConstexprKind);
9424         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9425                                     ? ConstexprSpecKind::Unspecified
9426                                     : ConstexprSpecKind::Constexpr);
9427       }
9428       // C++20 [dcl.constexpr]p2: An allocation function, or a
9429       // deallocation function shall not be declared with the consteval
9430       // specifier.
9431       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9432           (NewFD->getOverloadedOperator() == OO_New ||
9433            NewFD->getOverloadedOperator() == OO_Array_New ||
9434            NewFD->getOverloadedOperator() == OO_Delete ||
9435            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9436         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9437              diag::err_invalid_consteval_decl_kind)
9438             << NewFD;
9439         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9440       }
9441     }
9442 
9443     // If __module_private__ was specified, mark the function accordingly.
9444     if (D.getDeclSpec().isModulePrivateSpecified()) {
9445       if (isFunctionTemplateSpecialization) {
9446         SourceLocation ModulePrivateLoc
9447           = D.getDeclSpec().getModulePrivateSpecLoc();
9448         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9449           << 0
9450           << FixItHint::CreateRemoval(ModulePrivateLoc);
9451       } else {
9452         NewFD->setModulePrivate();
9453         if (FunctionTemplate)
9454           FunctionTemplate->setModulePrivate();
9455       }
9456     }
9457 
9458     if (isFriend) {
9459       if (FunctionTemplate) {
9460         FunctionTemplate->setObjectOfFriendDecl();
9461         FunctionTemplate->setAccess(AS_public);
9462       }
9463       NewFD->setObjectOfFriendDecl();
9464       NewFD->setAccess(AS_public);
9465     }
9466 
9467     // If a function is defined as defaulted or deleted, mark it as such now.
9468     // We'll do the relevant checks on defaulted / deleted functions later.
9469     switch (D.getFunctionDefinitionKind()) {
9470     case FunctionDefinitionKind::Declaration:
9471     case FunctionDefinitionKind::Definition:
9472       break;
9473 
9474     case FunctionDefinitionKind::Defaulted:
9475       NewFD->setDefaulted();
9476       break;
9477 
9478     case FunctionDefinitionKind::Deleted:
9479       NewFD->setDeletedAsWritten();
9480       break;
9481     }
9482 
9483     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9484         D.isFunctionDefinition()) {
9485       // C++ [class.mfct]p2:
9486       //   A member function may be defined (8.4) in its class definition, in
9487       //   which case it is an inline member function (7.1.2)
9488       NewFD->setImplicitlyInline();
9489     }
9490 
9491     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9492         !CurContext->isRecord()) {
9493       // C++ [class.static]p1:
9494       //   A data or function member of a class may be declared static
9495       //   in a class definition, in which case it is a static member of
9496       //   the class.
9497 
9498       // Complain about the 'static' specifier if it's on an out-of-line
9499       // member function definition.
9500 
9501       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9502       // member function template declaration and class member template
9503       // declaration (MSVC versions before 2015), warn about this.
9504       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9505            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9506              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9507            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9508            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9509         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9510     }
9511 
9512     // C++11 [except.spec]p15:
9513     //   A deallocation function with no exception-specification is treated
9514     //   as if it were specified with noexcept(true).
9515     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9516     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9517          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9518         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9519       NewFD->setType(Context.getFunctionType(
9520           FPT->getReturnType(), FPT->getParamTypes(),
9521           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9522   }
9523 
9524   // Filter out previous declarations that don't match the scope.
9525   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9526                        D.getCXXScopeSpec().isNotEmpty() ||
9527                        isMemberSpecialization ||
9528                        isFunctionTemplateSpecialization);
9529 
9530   // Handle GNU asm-label extension (encoded as an attribute).
9531   if (Expr *E = (Expr*) D.getAsmLabel()) {
9532     // The parser guarantees this is a string.
9533     StringLiteral *SE = cast<StringLiteral>(E);
9534     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9535                                         /*IsLiteralLabel=*/true,
9536                                         SE->getStrTokenLoc(0)));
9537   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9538     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9539       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9540     if (I != ExtnameUndeclaredIdentifiers.end()) {
9541       if (isDeclExternC(NewFD)) {
9542         NewFD->addAttr(I->second);
9543         ExtnameUndeclaredIdentifiers.erase(I);
9544       } else
9545         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9546             << /*Variable*/0 << NewFD;
9547     }
9548   }
9549 
9550   // Copy the parameter declarations from the declarator D to the function
9551   // declaration NewFD, if they are available.  First scavenge them into Params.
9552   SmallVector<ParmVarDecl*, 16> Params;
9553   unsigned FTIIdx;
9554   if (D.isFunctionDeclarator(FTIIdx)) {
9555     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9556 
9557     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9558     // function that takes no arguments, not a function that takes a
9559     // single void argument.
9560     // We let through "const void" here because Sema::GetTypeForDeclarator
9561     // already checks for that case.
9562     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9563       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9564         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9565         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9566         Param->setDeclContext(NewFD);
9567         Params.push_back(Param);
9568 
9569         if (Param->isInvalidDecl())
9570           NewFD->setInvalidDecl();
9571       }
9572     }
9573 
9574     if (!getLangOpts().CPlusPlus) {
9575       // In C, find all the tag declarations from the prototype and move them
9576       // into the function DeclContext. Remove them from the surrounding tag
9577       // injection context of the function, which is typically but not always
9578       // the TU.
9579       DeclContext *PrototypeTagContext =
9580           getTagInjectionContext(NewFD->getLexicalDeclContext());
9581       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9582         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9583 
9584         // We don't want to reparent enumerators. Look at their parent enum
9585         // instead.
9586         if (!TD) {
9587           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9588             TD = cast<EnumDecl>(ECD->getDeclContext());
9589         }
9590         if (!TD)
9591           continue;
9592         DeclContext *TagDC = TD->getLexicalDeclContext();
9593         if (!TagDC->containsDecl(TD))
9594           continue;
9595         TagDC->removeDecl(TD);
9596         TD->setDeclContext(NewFD);
9597         NewFD->addDecl(TD);
9598 
9599         // Preserve the lexical DeclContext if it is not the surrounding tag
9600         // injection context of the FD. In this example, the semantic context of
9601         // E will be f and the lexical context will be S, while both the
9602         // semantic and lexical contexts of S will be f:
9603         //   void f(struct S { enum E { a } f; } s);
9604         if (TagDC != PrototypeTagContext)
9605           TD->setLexicalDeclContext(TagDC);
9606       }
9607     }
9608   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9609     // When we're declaring a function with a typedef, typeof, etc as in the
9610     // following example, we'll need to synthesize (unnamed)
9611     // parameters for use in the declaration.
9612     //
9613     // @code
9614     // typedef void fn(int);
9615     // fn f;
9616     // @endcode
9617 
9618     // Synthesize a parameter for each argument type.
9619     for (const auto &AI : FT->param_types()) {
9620       ParmVarDecl *Param =
9621           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9622       Param->setScopeInfo(0, Params.size());
9623       Params.push_back(Param);
9624     }
9625   } else {
9626     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9627            "Should not need args for typedef of non-prototype fn");
9628   }
9629 
9630   // Finally, we know we have the right number of parameters, install them.
9631   NewFD->setParams(Params);
9632 
9633   if (D.getDeclSpec().isNoreturnSpecified())
9634     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9635                                            D.getDeclSpec().getNoreturnSpecLoc(),
9636                                            AttributeCommonInfo::AS_Keyword));
9637 
9638   // Functions returning a variably modified type violate C99 6.7.5.2p2
9639   // because all functions have linkage.
9640   if (!NewFD->isInvalidDecl() &&
9641       NewFD->getReturnType()->isVariablyModifiedType()) {
9642     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9643     NewFD->setInvalidDecl();
9644   }
9645 
9646   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9647   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9648       !NewFD->hasAttr<SectionAttr>())
9649     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9650         Context, PragmaClangTextSection.SectionName,
9651         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9652 
9653   // Apply an implicit SectionAttr if #pragma code_seg is active.
9654   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9655       !NewFD->hasAttr<SectionAttr>()) {
9656     NewFD->addAttr(SectionAttr::CreateImplicit(
9657         Context, CodeSegStack.CurrentValue->getString(),
9658         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9659         SectionAttr::Declspec_allocate));
9660     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9661                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9662                          ASTContext::PSF_Read,
9663                      NewFD))
9664       NewFD->dropAttr<SectionAttr>();
9665   }
9666 
9667   // Apply an implicit CodeSegAttr from class declspec or
9668   // apply an implicit SectionAttr from #pragma code_seg if active.
9669   if (!NewFD->hasAttr<CodeSegAttr>()) {
9670     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9671                                                                  D.isFunctionDefinition())) {
9672       NewFD->addAttr(SAttr);
9673     }
9674   }
9675 
9676   // Handle attributes.
9677   ProcessDeclAttributes(S, NewFD, D);
9678 
9679   if (getLangOpts().OpenCL) {
9680     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9681     // type declaration will generate a compilation error.
9682     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9683     if (AddressSpace != LangAS::Default) {
9684       Diag(NewFD->getLocation(),
9685            diag::err_opencl_return_value_with_address_space);
9686       NewFD->setInvalidDecl();
9687     }
9688   }
9689 
9690   if (!getLangOpts().CPlusPlus) {
9691     // Perform semantic checking on the function declaration.
9692     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9693       CheckMain(NewFD, D.getDeclSpec());
9694 
9695     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9696       CheckMSVCRTEntryPoint(NewFD);
9697 
9698     if (!NewFD->isInvalidDecl())
9699       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9700                                                   isMemberSpecialization));
9701     else if (!Previous.empty())
9702       // Recover gracefully from an invalid redeclaration.
9703       D.setRedeclaration(true);
9704     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9705             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9706            "previous declaration set still overloaded");
9707 
9708     // Diagnose no-prototype function declarations with calling conventions that
9709     // don't support variadic calls. Only do this in C and do it after merging
9710     // possibly prototyped redeclarations.
9711     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9712     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9713       CallingConv CC = FT->getExtInfo().getCC();
9714       if (!supportsVariadicCall(CC)) {
9715         // Windows system headers sometimes accidentally use stdcall without
9716         // (void) parameters, so we relax this to a warning.
9717         int DiagID =
9718             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9719         Diag(NewFD->getLocation(), DiagID)
9720             << FunctionType::getNameForCallConv(CC);
9721       }
9722     }
9723 
9724    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9725        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9726      checkNonTrivialCUnion(NewFD->getReturnType(),
9727                            NewFD->getReturnTypeSourceRange().getBegin(),
9728                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9729   } else {
9730     // C++11 [replacement.functions]p3:
9731     //  The program's definitions shall not be specified as inline.
9732     //
9733     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9734     //
9735     // Suppress the diagnostic if the function is __attribute__((used)), since
9736     // that forces an external definition to be emitted.
9737     if (D.getDeclSpec().isInlineSpecified() &&
9738         NewFD->isReplaceableGlobalAllocationFunction() &&
9739         !NewFD->hasAttr<UsedAttr>())
9740       Diag(D.getDeclSpec().getInlineSpecLoc(),
9741            diag::ext_operator_new_delete_declared_inline)
9742         << NewFD->getDeclName();
9743 
9744     // If the declarator is a template-id, translate the parser's template
9745     // argument list into our AST format.
9746     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9747       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9748       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9749       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9750       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9751                                          TemplateId->NumArgs);
9752       translateTemplateArguments(TemplateArgsPtr,
9753                                  TemplateArgs);
9754 
9755       HasExplicitTemplateArgs = true;
9756 
9757       if (NewFD->isInvalidDecl()) {
9758         HasExplicitTemplateArgs = false;
9759       } else if (FunctionTemplate) {
9760         // Function template with explicit template arguments.
9761         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9762           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9763 
9764         HasExplicitTemplateArgs = false;
9765       } else {
9766         assert((isFunctionTemplateSpecialization ||
9767                 D.getDeclSpec().isFriendSpecified()) &&
9768                "should have a 'template<>' for this decl");
9769         // "friend void foo<>(int);" is an implicit specialization decl.
9770         isFunctionTemplateSpecialization = true;
9771       }
9772     } else if (isFriend && isFunctionTemplateSpecialization) {
9773       // This combination is only possible in a recovery case;  the user
9774       // wrote something like:
9775       //   template <> friend void foo(int);
9776       // which we're recovering from as if the user had written:
9777       //   friend void foo<>(int);
9778       // Go ahead and fake up a template id.
9779       HasExplicitTemplateArgs = true;
9780       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9781       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9782     }
9783 
9784     // We do not add HD attributes to specializations here because
9785     // they may have different constexpr-ness compared to their
9786     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9787     // may end up with different effective targets. Instead, a
9788     // specialization inherits its target attributes from its template
9789     // in the CheckFunctionTemplateSpecialization() call below.
9790     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9791       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9792 
9793     // If it's a friend (and only if it's a friend), it's possible
9794     // that either the specialized function type or the specialized
9795     // template is dependent, and therefore matching will fail.  In
9796     // this case, don't check the specialization yet.
9797     if (isFunctionTemplateSpecialization && isFriend &&
9798         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9799          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9800              TemplateArgs.arguments()))) {
9801       assert(HasExplicitTemplateArgs &&
9802              "friend function specialization without template args");
9803       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9804                                                        Previous))
9805         NewFD->setInvalidDecl();
9806     } else if (isFunctionTemplateSpecialization) {
9807       if (CurContext->isDependentContext() && CurContext->isRecord()
9808           && !isFriend) {
9809         isDependentClassScopeExplicitSpecialization = true;
9810       } else if (!NewFD->isInvalidDecl() &&
9811                  CheckFunctionTemplateSpecialization(
9812                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9813                      Previous))
9814         NewFD->setInvalidDecl();
9815 
9816       // C++ [dcl.stc]p1:
9817       //   A storage-class-specifier shall not be specified in an explicit
9818       //   specialization (14.7.3)
9819       FunctionTemplateSpecializationInfo *Info =
9820           NewFD->getTemplateSpecializationInfo();
9821       if (Info && SC != SC_None) {
9822         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9823           Diag(NewFD->getLocation(),
9824                diag::err_explicit_specialization_inconsistent_storage_class)
9825             << SC
9826             << FixItHint::CreateRemoval(
9827                                       D.getDeclSpec().getStorageClassSpecLoc());
9828 
9829         else
9830           Diag(NewFD->getLocation(),
9831                diag::ext_explicit_specialization_storage_class)
9832             << FixItHint::CreateRemoval(
9833                                       D.getDeclSpec().getStorageClassSpecLoc());
9834       }
9835     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9836       if (CheckMemberSpecialization(NewFD, Previous))
9837           NewFD->setInvalidDecl();
9838     }
9839 
9840     // Perform semantic checking on the function declaration.
9841     if (!isDependentClassScopeExplicitSpecialization) {
9842       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9843         CheckMain(NewFD, D.getDeclSpec());
9844 
9845       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9846         CheckMSVCRTEntryPoint(NewFD);
9847 
9848       if (!NewFD->isInvalidDecl())
9849         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9850                                                     isMemberSpecialization));
9851       else if (!Previous.empty())
9852         // Recover gracefully from an invalid redeclaration.
9853         D.setRedeclaration(true);
9854     }
9855 
9856     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9857             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9858            "previous declaration set still overloaded");
9859 
9860     NamedDecl *PrincipalDecl = (FunctionTemplate
9861                                 ? cast<NamedDecl>(FunctionTemplate)
9862                                 : NewFD);
9863 
9864     if (isFriend && NewFD->getPreviousDecl()) {
9865       AccessSpecifier Access = AS_public;
9866       if (!NewFD->isInvalidDecl())
9867         Access = NewFD->getPreviousDecl()->getAccess();
9868 
9869       NewFD->setAccess(Access);
9870       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9871     }
9872 
9873     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9874         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9875       PrincipalDecl->setNonMemberOperator();
9876 
9877     // If we have a function template, check the template parameter
9878     // list. This will check and merge default template arguments.
9879     if (FunctionTemplate) {
9880       FunctionTemplateDecl *PrevTemplate =
9881                                      FunctionTemplate->getPreviousDecl();
9882       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9883                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9884                                     : nullptr,
9885                             D.getDeclSpec().isFriendSpecified()
9886                               ? (D.isFunctionDefinition()
9887                                    ? TPC_FriendFunctionTemplateDefinition
9888                                    : TPC_FriendFunctionTemplate)
9889                               : (D.getCXXScopeSpec().isSet() &&
9890                                  DC && DC->isRecord() &&
9891                                  DC->isDependentContext())
9892                                   ? TPC_ClassTemplateMember
9893                                   : TPC_FunctionTemplate);
9894     }
9895 
9896     if (NewFD->isInvalidDecl()) {
9897       // Ignore all the rest of this.
9898     } else if (!D.isRedeclaration()) {
9899       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9900                                        AddToScope };
9901       // Fake up an access specifier if it's supposed to be a class member.
9902       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9903         NewFD->setAccess(AS_public);
9904 
9905       // Qualified decls generally require a previous declaration.
9906       if (D.getCXXScopeSpec().isSet()) {
9907         // ...with the major exception of templated-scope or
9908         // dependent-scope friend declarations.
9909 
9910         // TODO: we currently also suppress this check in dependent
9911         // contexts because (1) the parameter depth will be off when
9912         // matching friend templates and (2) we might actually be
9913         // selecting a friend based on a dependent factor.  But there
9914         // are situations where these conditions don't apply and we
9915         // can actually do this check immediately.
9916         //
9917         // Unless the scope is dependent, it's always an error if qualified
9918         // redeclaration lookup found nothing at all. Diagnose that now;
9919         // nothing will diagnose that error later.
9920         if (isFriend &&
9921             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9922              (!Previous.empty() && CurContext->isDependentContext()))) {
9923           // ignore these
9924         } else if (NewFD->isCPUDispatchMultiVersion() ||
9925                    NewFD->isCPUSpecificMultiVersion()) {
9926           // ignore this, we allow the redeclaration behavior here to create new
9927           // versions of the function.
9928         } else {
9929           // The user tried to provide an out-of-line definition for a
9930           // function that is a member of a class or namespace, but there
9931           // was no such member function declared (C++ [class.mfct]p2,
9932           // C++ [namespace.memdef]p2). For example:
9933           //
9934           // class X {
9935           //   void f() const;
9936           // };
9937           //
9938           // void X::f() { } // ill-formed
9939           //
9940           // Complain about this problem, and attempt to suggest close
9941           // matches (e.g., those that differ only in cv-qualifiers and
9942           // whether the parameter types are references).
9943 
9944           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9945                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9946             AddToScope = ExtraArgs.AddToScope;
9947             return Result;
9948           }
9949         }
9950 
9951         // Unqualified local friend declarations are required to resolve
9952         // to something.
9953       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9954         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9955                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9956           AddToScope = ExtraArgs.AddToScope;
9957           return Result;
9958         }
9959       }
9960     } else if (!D.isFunctionDefinition() &&
9961                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9962                !isFriend && !isFunctionTemplateSpecialization &&
9963                !isMemberSpecialization) {
9964       // An out-of-line member function declaration must also be a
9965       // definition (C++ [class.mfct]p2).
9966       // Note that this is not the case for explicit specializations of
9967       // function templates or member functions of class templates, per
9968       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9969       // extension for compatibility with old SWIG code which likes to
9970       // generate them.
9971       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9972         << D.getCXXScopeSpec().getRange();
9973     }
9974   }
9975 
9976   // If this is the first declaration of a library builtin function, add
9977   // attributes as appropriate.
9978   if (!D.isRedeclaration() &&
9979       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9980     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9981       if (unsigned BuiltinID = II->getBuiltinID()) {
9982         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9983           // Validate the type matches unless this builtin is specified as
9984           // matching regardless of its declared type.
9985           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9986             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9987           } else {
9988             ASTContext::GetBuiltinTypeError Error;
9989             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9990             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9991 
9992             if (!Error && !BuiltinType.isNull() &&
9993                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9994                     NewFD->getType(), BuiltinType))
9995               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9996           }
9997         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9998                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9999           // FIXME: We should consider this a builtin only in the std namespace.
10000           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10001         }
10002       }
10003     }
10004   }
10005 
10006   ProcessPragmaWeak(S, NewFD);
10007   checkAttributesAfterMerging(*this, *NewFD);
10008 
10009   AddKnownFunctionAttributes(NewFD);
10010 
10011   if (NewFD->hasAttr<OverloadableAttr>() &&
10012       !NewFD->getType()->getAs<FunctionProtoType>()) {
10013     Diag(NewFD->getLocation(),
10014          diag::err_attribute_overloadable_no_prototype)
10015       << NewFD;
10016 
10017     // Turn this into a variadic function with no parameters.
10018     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10019     FunctionProtoType::ExtProtoInfo EPI(
10020         Context.getDefaultCallingConvention(true, false));
10021     EPI.Variadic = true;
10022     EPI.ExtInfo = FT->getExtInfo();
10023 
10024     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10025     NewFD->setType(R);
10026   }
10027 
10028   // If there's a #pragma GCC visibility in scope, and this isn't a class
10029   // member, set the visibility of this function.
10030   if (!DC->isRecord() && NewFD->isExternallyVisible())
10031     AddPushedVisibilityAttribute(NewFD);
10032 
10033   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10034   // marking the function.
10035   AddCFAuditedAttribute(NewFD);
10036 
10037   // If this is a function definition, check if we have to apply optnone due to
10038   // a pragma.
10039   if(D.isFunctionDefinition())
10040     AddRangeBasedOptnone(NewFD);
10041 
10042   // If this is the first declaration of an extern C variable, update
10043   // the map of such variables.
10044   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10045       isIncompleteDeclExternC(*this, NewFD))
10046     RegisterLocallyScopedExternCDecl(NewFD, S);
10047 
10048   // Set this FunctionDecl's range up to the right paren.
10049   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10050 
10051   if (D.isRedeclaration() && !Previous.empty()) {
10052     NamedDecl *Prev = Previous.getRepresentativeDecl();
10053     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10054                                    isMemberSpecialization ||
10055                                        isFunctionTemplateSpecialization,
10056                                    D.isFunctionDefinition());
10057   }
10058 
10059   if (getLangOpts().CUDA) {
10060     IdentifierInfo *II = NewFD->getIdentifier();
10061     if (II && II->isStr(getCudaConfigureFuncName()) &&
10062         !NewFD->isInvalidDecl() &&
10063         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10064       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10065         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10066             << getCudaConfigureFuncName();
10067       Context.setcudaConfigureCallDecl(NewFD);
10068     }
10069 
10070     // Variadic functions, other than a *declaration* of printf, are not allowed
10071     // in device-side CUDA code, unless someone passed
10072     // -fcuda-allow-variadic-functions.
10073     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10074         (NewFD->hasAttr<CUDADeviceAttr>() ||
10075          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10076         !(II && II->isStr("printf") && NewFD->isExternC() &&
10077           !D.isFunctionDefinition())) {
10078       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10079     }
10080   }
10081 
10082   MarkUnusedFileScopedDecl(NewFD);
10083 
10084 
10085 
10086   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10087     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10088     if (SC == SC_Static) {
10089       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10090       D.setInvalidType();
10091     }
10092 
10093     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10094     if (!NewFD->getReturnType()->isVoidType()) {
10095       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10096       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10097           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10098                                 : FixItHint());
10099       D.setInvalidType();
10100     }
10101 
10102     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10103     for (auto Param : NewFD->parameters())
10104       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10105 
10106     if (getLangOpts().OpenCLCPlusPlus) {
10107       if (DC->isRecord()) {
10108         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10109         D.setInvalidType();
10110       }
10111       if (FunctionTemplate) {
10112         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10113         D.setInvalidType();
10114       }
10115     }
10116   }
10117 
10118   if (getLangOpts().CPlusPlus) {
10119     if (FunctionTemplate) {
10120       if (NewFD->isInvalidDecl())
10121         FunctionTemplate->setInvalidDecl();
10122       return FunctionTemplate;
10123     }
10124 
10125     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10126       CompleteMemberSpecialization(NewFD, Previous);
10127   }
10128 
10129   for (const ParmVarDecl *Param : NewFD->parameters()) {
10130     QualType PT = Param->getType();
10131 
10132     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10133     // types.
10134     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10135       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10136         QualType ElemTy = PipeTy->getElementType();
10137           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10138             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10139             D.setInvalidType();
10140           }
10141       }
10142     }
10143   }
10144 
10145   // Here we have an function template explicit specialization at class scope.
10146   // The actual specialization will be postponed to template instatiation
10147   // time via the ClassScopeFunctionSpecializationDecl node.
10148   if (isDependentClassScopeExplicitSpecialization) {
10149     ClassScopeFunctionSpecializationDecl *NewSpec =
10150                          ClassScopeFunctionSpecializationDecl::Create(
10151                                 Context, CurContext, NewFD->getLocation(),
10152                                 cast<CXXMethodDecl>(NewFD),
10153                                 HasExplicitTemplateArgs, TemplateArgs);
10154     CurContext->addDecl(NewSpec);
10155     AddToScope = false;
10156   }
10157 
10158   // Diagnose availability attributes. Availability cannot be used on functions
10159   // that are run during load/unload.
10160   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10161     if (NewFD->hasAttr<ConstructorAttr>()) {
10162       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10163           << 1;
10164       NewFD->dropAttr<AvailabilityAttr>();
10165     }
10166     if (NewFD->hasAttr<DestructorAttr>()) {
10167       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10168           << 2;
10169       NewFD->dropAttr<AvailabilityAttr>();
10170     }
10171   }
10172 
10173   // Diagnose no_builtin attribute on function declaration that are not a
10174   // definition.
10175   // FIXME: We should really be doing this in
10176   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10177   // the FunctionDecl and at this point of the code
10178   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10179   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10180   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10181     switch (D.getFunctionDefinitionKind()) {
10182     case FunctionDefinitionKind::Defaulted:
10183     case FunctionDefinitionKind::Deleted:
10184       Diag(NBA->getLocation(),
10185            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10186           << NBA->getSpelling();
10187       break;
10188     case FunctionDefinitionKind::Declaration:
10189       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10190           << NBA->getSpelling();
10191       break;
10192     case FunctionDefinitionKind::Definition:
10193       break;
10194     }
10195 
10196   return NewFD;
10197 }
10198 
10199 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10200 /// when __declspec(code_seg) "is applied to a class, all member functions of
10201 /// the class and nested classes -- this includes compiler-generated special
10202 /// member functions -- are put in the specified segment."
10203 /// The actual behavior is a little more complicated. The Microsoft compiler
10204 /// won't check outer classes if there is an active value from #pragma code_seg.
10205 /// The CodeSeg is always applied from the direct parent but only from outer
10206 /// classes when the #pragma code_seg stack is empty. See:
10207 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10208 /// available since MS has removed the page.
10209 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10210   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10211   if (!Method)
10212     return nullptr;
10213   const CXXRecordDecl *Parent = Method->getParent();
10214   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10215     Attr *NewAttr = SAttr->clone(S.getASTContext());
10216     NewAttr->setImplicit(true);
10217     return NewAttr;
10218   }
10219 
10220   // The Microsoft compiler won't check outer classes for the CodeSeg
10221   // when the #pragma code_seg stack is active.
10222   if (S.CodeSegStack.CurrentValue)
10223    return nullptr;
10224 
10225   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10226     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10227       Attr *NewAttr = SAttr->clone(S.getASTContext());
10228       NewAttr->setImplicit(true);
10229       return NewAttr;
10230     }
10231   }
10232   return nullptr;
10233 }
10234 
10235 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10236 /// containing class. Otherwise it will return implicit SectionAttr if the
10237 /// function is a definition and there is an active value on CodeSegStack
10238 /// (from the current #pragma code-seg value).
10239 ///
10240 /// \param FD Function being declared.
10241 /// \param IsDefinition Whether it is a definition or just a declarartion.
10242 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10243 ///          nullptr if no attribute should be added.
10244 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10245                                                        bool IsDefinition) {
10246   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10247     return A;
10248   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10249       CodeSegStack.CurrentValue)
10250     return SectionAttr::CreateImplicit(
10251         getASTContext(), CodeSegStack.CurrentValue->getString(),
10252         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10253         SectionAttr::Declspec_allocate);
10254   return nullptr;
10255 }
10256 
10257 /// Determines if we can perform a correct type check for \p D as a
10258 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10259 /// best-effort check.
10260 ///
10261 /// \param NewD The new declaration.
10262 /// \param OldD The old declaration.
10263 /// \param NewT The portion of the type of the new declaration to check.
10264 /// \param OldT The portion of the type of the old declaration to check.
10265 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10266                                           QualType NewT, QualType OldT) {
10267   if (!NewD->getLexicalDeclContext()->isDependentContext())
10268     return true;
10269 
10270   // For dependently-typed local extern declarations and friends, we can't
10271   // perform a correct type check in general until instantiation:
10272   //
10273   //   int f();
10274   //   template<typename T> void g() { T f(); }
10275   //
10276   // (valid if g() is only instantiated with T = int).
10277   if (NewT->isDependentType() &&
10278       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10279     return false;
10280 
10281   // Similarly, if the previous declaration was a dependent local extern
10282   // declaration, we don't really know its type yet.
10283   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10284     return false;
10285 
10286   return true;
10287 }
10288 
10289 /// Checks if the new declaration declared in dependent context must be
10290 /// put in the same redeclaration chain as the specified declaration.
10291 ///
10292 /// \param D Declaration that is checked.
10293 /// \param PrevDecl Previous declaration found with proper lookup method for the
10294 ///                 same declaration name.
10295 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10296 ///          belongs to.
10297 ///
10298 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10299   if (!D->getLexicalDeclContext()->isDependentContext())
10300     return true;
10301 
10302   // Don't chain dependent friend function definitions until instantiation, to
10303   // permit cases like
10304   //
10305   //   void func();
10306   //   template<typename T> class C1 { friend void func() {} };
10307   //   template<typename T> class C2 { friend void func() {} };
10308   //
10309   // ... which is valid if only one of C1 and C2 is ever instantiated.
10310   //
10311   // FIXME: This need only apply to function definitions. For now, we proxy
10312   // this by checking for a file-scope function. We do not want this to apply
10313   // to friend declarations nominating member functions, because that gets in
10314   // the way of access checks.
10315   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10316     return false;
10317 
10318   auto *VD = dyn_cast<ValueDecl>(D);
10319   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10320   return !VD || !PrevVD ||
10321          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10322                                         PrevVD->getType());
10323 }
10324 
10325 /// Check the target attribute of the function for MultiVersion
10326 /// validity.
10327 ///
10328 /// Returns true if there was an error, false otherwise.
10329 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10330   const auto *TA = FD->getAttr<TargetAttr>();
10331   assert(TA && "MultiVersion Candidate requires a target attribute");
10332   ParsedTargetAttr ParseInfo = TA->parse();
10333   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10334   enum ErrType { Feature = 0, Architecture = 1 };
10335 
10336   if (!ParseInfo.Architecture.empty() &&
10337       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10338     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10339         << Architecture << ParseInfo.Architecture;
10340     return true;
10341   }
10342 
10343   for (const auto &Feat : ParseInfo.Features) {
10344     auto BareFeat = StringRef{Feat}.substr(1);
10345     if (Feat[0] == '-') {
10346       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10347           << Feature << ("no-" + BareFeat).str();
10348       return true;
10349     }
10350 
10351     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10352         !TargetInfo.isValidFeatureName(BareFeat)) {
10353       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10354           << Feature << BareFeat;
10355       return true;
10356     }
10357   }
10358   return false;
10359 }
10360 
10361 // Provide a white-list of attributes that are allowed to be combined with
10362 // multiversion functions.
10363 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10364                                            MultiVersionKind MVKind) {
10365   // Note: this list/diagnosis must match the list in
10366   // checkMultiversionAttributesAllSame.
10367   switch (Kind) {
10368   default:
10369     return false;
10370   case attr::Used:
10371     return MVKind == MultiVersionKind::Target;
10372   case attr::NonNull:
10373   case attr::NoThrow:
10374     return true;
10375   }
10376 }
10377 
10378 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10379                                                  const FunctionDecl *FD,
10380                                                  const FunctionDecl *CausedFD,
10381                                                  MultiVersionKind MVKind) {
10382   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10383     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10384         << static_cast<unsigned>(MVKind) << A;
10385     if (CausedFD)
10386       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10387     return true;
10388   };
10389 
10390   for (const Attr *A : FD->attrs()) {
10391     switch (A->getKind()) {
10392     case attr::CPUDispatch:
10393     case attr::CPUSpecific:
10394       if (MVKind != MultiVersionKind::CPUDispatch &&
10395           MVKind != MultiVersionKind::CPUSpecific)
10396         return Diagnose(S, A);
10397       break;
10398     case attr::Target:
10399       if (MVKind != MultiVersionKind::Target)
10400         return Diagnose(S, A);
10401       break;
10402     case attr::TargetClones:
10403       if (MVKind != MultiVersionKind::TargetClones)
10404         return Diagnose(S, A);
10405       break;
10406     default:
10407       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10408         return Diagnose(S, A);
10409       break;
10410     }
10411   }
10412   return false;
10413 }
10414 
10415 bool Sema::areMultiversionVariantFunctionsCompatible(
10416     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10417     const PartialDiagnostic &NoProtoDiagID,
10418     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10419     const PartialDiagnosticAt &NoSupportDiagIDAt,
10420     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10421     bool ConstexprSupported, bool CLinkageMayDiffer) {
10422   enum DoesntSupport {
10423     FuncTemplates = 0,
10424     VirtFuncs = 1,
10425     DeducedReturn = 2,
10426     Constructors = 3,
10427     Destructors = 4,
10428     DeletedFuncs = 5,
10429     DefaultedFuncs = 6,
10430     ConstexprFuncs = 7,
10431     ConstevalFuncs = 8,
10432     Lambda = 9,
10433   };
10434   enum Different {
10435     CallingConv = 0,
10436     ReturnType = 1,
10437     ConstexprSpec = 2,
10438     InlineSpec = 3,
10439     Linkage = 4,
10440     LanguageLinkage = 5,
10441   };
10442 
10443   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10444       !OldFD->getType()->getAs<FunctionProtoType>()) {
10445     Diag(OldFD->getLocation(), NoProtoDiagID);
10446     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10447     return true;
10448   }
10449 
10450   if (NoProtoDiagID.getDiagID() != 0 &&
10451       !NewFD->getType()->getAs<FunctionProtoType>())
10452     return Diag(NewFD->getLocation(), NoProtoDiagID);
10453 
10454   if (!TemplatesSupported &&
10455       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10456     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10457            << FuncTemplates;
10458 
10459   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10460     if (NewCXXFD->isVirtual())
10461       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10462              << VirtFuncs;
10463 
10464     if (isa<CXXConstructorDecl>(NewCXXFD))
10465       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10466              << Constructors;
10467 
10468     if (isa<CXXDestructorDecl>(NewCXXFD))
10469       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10470              << Destructors;
10471   }
10472 
10473   if (NewFD->isDeleted())
10474     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10475            << DeletedFuncs;
10476 
10477   if (NewFD->isDefaulted())
10478     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10479            << DefaultedFuncs;
10480 
10481   if (!ConstexprSupported && NewFD->isConstexpr())
10482     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10483            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10484 
10485   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10486   const auto *NewType = cast<FunctionType>(NewQType);
10487   QualType NewReturnType = NewType->getReturnType();
10488 
10489   if (NewReturnType->isUndeducedType())
10490     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10491            << DeducedReturn;
10492 
10493   // Ensure the return type is identical.
10494   if (OldFD) {
10495     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10496     const auto *OldType = cast<FunctionType>(OldQType);
10497     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10498     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10499 
10500     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10501       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10502 
10503     QualType OldReturnType = OldType->getReturnType();
10504 
10505     if (OldReturnType != NewReturnType)
10506       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10507 
10508     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10509       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10510 
10511     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10512       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10513 
10514     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10515       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10516 
10517     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10518       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10519 
10520     if (CheckEquivalentExceptionSpec(
10521             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10522             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10523       return true;
10524   }
10525   return false;
10526 }
10527 
10528 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10529                                              const FunctionDecl *NewFD,
10530                                              bool CausesMV,
10531                                              MultiVersionKind MVKind) {
10532   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10533     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10534     if (OldFD)
10535       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10536     return true;
10537   }
10538 
10539   bool IsCPUSpecificCPUDispatchMVKind =
10540       MVKind == MultiVersionKind::CPUDispatch ||
10541       MVKind == MultiVersionKind::CPUSpecific;
10542 
10543   if (CausesMV && OldFD &&
10544       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10545     return true;
10546 
10547   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10548     return true;
10549 
10550   // Only allow transition to MultiVersion if it hasn't been used.
10551   if (OldFD && CausesMV && OldFD->isUsed(false))
10552     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10553 
10554   return S.areMultiversionVariantFunctionsCompatible(
10555       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10556       PartialDiagnosticAt(NewFD->getLocation(),
10557                           S.PDiag(diag::note_multiversioning_caused_here)),
10558       PartialDiagnosticAt(NewFD->getLocation(),
10559                           S.PDiag(diag::err_multiversion_doesnt_support)
10560                               << static_cast<unsigned>(MVKind)),
10561       PartialDiagnosticAt(NewFD->getLocation(),
10562                           S.PDiag(diag::err_multiversion_diff)),
10563       /*TemplatesSupported=*/false,
10564       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10565       /*CLinkageMayDiffer=*/false);
10566 }
10567 
10568 /// Check the validity of a multiversion function declaration that is the
10569 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10570 ///
10571 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10572 ///
10573 /// Returns true if there was an error, false otherwise.
10574 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10575                                            MultiVersionKind MVKind,
10576                                            const TargetAttr *TA) {
10577   assert(MVKind != MultiVersionKind::None &&
10578          "Function lacks multiversion attribute");
10579 
10580   // Target only causes MV if it is default, otherwise this is a normal
10581   // function.
10582   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10583     return false;
10584 
10585   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10586     FD->setInvalidDecl();
10587     return true;
10588   }
10589 
10590   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10591     FD->setInvalidDecl();
10592     return true;
10593   }
10594 
10595   FD->setIsMultiVersion();
10596   return false;
10597 }
10598 
10599 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10600   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10601     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10602       return true;
10603   }
10604 
10605   return false;
10606 }
10607 
10608 static bool CheckTargetCausesMultiVersioning(
10609     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10610     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10611   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10612   ParsedTargetAttr NewParsed = NewTA->parse();
10613   // Sort order doesn't matter, it just needs to be consistent.
10614   llvm::sort(NewParsed.Features);
10615 
10616   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10617   // to change, this is a simple redeclaration.
10618   if (!NewTA->isDefaultVersion() &&
10619       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10620     return false;
10621 
10622   // Otherwise, this decl causes MultiVersioning.
10623   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10624                                        MultiVersionKind::Target)) {
10625     NewFD->setInvalidDecl();
10626     return true;
10627   }
10628 
10629   if (CheckMultiVersionValue(S, NewFD)) {
10630     NewFD->setInvalidDecl();
10631     return true;
10632   }
10633 
10634   // If this is 'default', permit the forward declaration.
10635   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10636     Redeclaration = true;
10637     OldDecl = OldFD;
10638     OldFD->setIsMultiVersion();
10639     NewFD->setIsMultiVersion();
10640     return false;
10641   }
10642 
10643   if (CheckMultiVersionValue(S, OldFD)) {
10644     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10645     NewFD->setInvalidDecl();
10646     return true;
10647   }
10648 
10649   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10650 
10651   if (OldParsed == NewParsed) {
10652     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10653     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10654     NewFD->setInvalidDecl();
10655     return true;
10656   }
10657 
10658   for (const auto *FD : OldFD->redecls()) {
10659     const auto *CurTA = FD->getAttr<TargetAttr>();
10660     // We allow forward declarations before ANY multiversioning attributes, but
10661     // nothing after the fact.
10662     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10663         (!CurTA || CurTA->isInherited())) {
10664       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10665           << 0;
10666       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10667       NewFD->setInvalidDecl();
10668       return true;
10669     }
10670   }
10671 
10672   OldFD->setIsMultiVersion();
10673   NewFD->setIsMultiVersion();
10674   Redeclaration = false;
10675   OldDecl = nullptr;
10676   Previous.clear();
10677   return false;
10678 }
10679 
10680 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10681                                         MultiVersionKind New) {
10682   if (Old == New || Old == MultiVersionKind::None ||
10683       New == MultiVersionKind::None)
10684     return true;
10685 
10686   return (Old == MultiVersionKind::CPUDispatch &&
10687           New == MultiVersionKind::CPUSpecific) ||
10688          (Old == MultiVersionKind::CPUSpecific &&
10689           New == MultiVersionKind::CPUDispatch);
10690 }
10691 
10692 /// Check the validity of a new function declaration being added to an existing
10693 /// multiversioned declaration collection.
10694 static bool CheckMultiVersionAdditionalDecl(
10695     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10696     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10697     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10698     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10699     LookupResult &Previous) {
10700 
10701   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10702   // Disallow mixing of multiversioning types.
10703   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10704     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10705     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10706     NewFD->setInvalidDecl();
10707     return true;
10708   }
10709 
10710   ParsedTargetAttr NewParsed;
10711   if (NewTA) {
10712     NewParsed = NewTA->parse();
10713     llvm::sort(NewParsed.Features);
10714   }
10715 
10716   bool UseMemberUsingDeclRules =
10717       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10718 
10719   bool MayNeedOverloadableChecks =
10720       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10721 
10722   // Next, check ALL non-overloads to see if this is a redeclaration of a
10723   // previous member of the MultiVersion set.
10724   for (NamedDecl *ND : Previous) {
10725     FunctionDecl *CurFD = ND->getAsFunction();
10726     if (!CurFD)
10727       continue;
10728     if (MayNeedOverloadableChecks &&
10729         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10730       continue;
10731 
10732     switch (NewMVKind) {
10733     case MultiVersionKind::None:
10734       assert(OldMVKind == MultiVersionKind::TargetClones &&
10735              "Only target_clones can be omitted in subsequent declarations");
10736       break;
10737     case MultiVersionKind::Target: {
10738       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10739       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10740         NewFD->setIsMultiVersion();
10741         Redeclaration = true;
10742         OldDecl = ND;
10743         return false;
10744       }
10745 
10746       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10747       if (CurParsed == NewParsed) {
10748         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10749         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10750         NewFD->setInvalidDecl();
10751         return true;
10752       }
10753       break;
10754     }
10755     case MultiVersionKind::TargetClones: {
10756       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10757       Redeclaration = true;
10758       OldDecl = CurFD;
10759       NewFD->setIsMultiVersion();
10760 
10761       if (CurClones && NewClones &&
10762           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10763            !std::equal(CurClones->featuresStrs_begin(),
10764                        CurClones->featuresStrs_end(),
10765                        NewClones->featuresStrs_begin()))) {
10766         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10767         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10768         NewFD->setInvalidDecl();
10769         return true;
10770       }
10771 
10772       return false;
10773     }
10774     case MultiVersionKind::CPUSpecific:
10775     case MultiVersionKind::CPUDispatch: {
10776       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10777       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10778       // Handle CPUDispatch/CPUSpecific versions.
10779       // Only 1 CPUDispatch function is allowed, this will make it go through
10780       // the redeclaration errors.
10781       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10782           CurFD->hasAttr<CPUDispatchAttr>()) {
10783         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10784             std::equal(
10785                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10786                 NewCPUDisp->cpus_begin(),
10787                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10788                   return Cur->getName() == New->getName();
10789                 })) {
10790           NewFD->setIsMultiVersion();
10791           Redeclaration = true;
10792           OldDecl = ND;
10793           return false;
10794         }
10795 
10796         // If the declarations don't match, this is an error condition.
10797         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10798         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10799         NewFD->setInvalidDecl();
10800         return true;
10801       }
10802       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10803         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10804             std::equal(
10805                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10806                 NewCPUSpec->cpus_begin(),
10807                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10808                   return Cur->getName() == New->getName();
10809                 })) {
10810           NewFD->setIsMultiVersion();
10811           Redeclaration = true;
10812           OldDecl = ND;
10813           return false;
10814         }
10815 
10816         // Only 1 version of CPUSpecific is allowed for each CPU.
10817         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10818           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10819             if (CurII == NewII) {
10820               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10821                   << NewII;
10822               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10823               NewFD->setInvalidDecl();
10824               return true;
10825             }
10826           }
10827         }
10828       }
10829       break;
10830     }
10831     }
10832   }
10833 
10834   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10835   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10836   // handled in the attribute adding step.
10837   if (NewMVKind == MultiVersionKind::Target &&
10838       CheckMultiVersionValue(S, NewFD)) {
10839     NewFD->setInvalidDecl();
10840     return true;
10841   }
10842 
10843   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10844                                        !OldFD->isMultiVersion(), NewMVKind)) {
10845     NewFD->setInvalidDecl();
10846     return true;
10847   }
10848 
10849   // Permit forward declarations in the case where these two are compatible.
10850   if (!OldFD->isMultiVersion()) {
10851     OldFD->setIsMultiVersion();
10852     NewFD->setIsMultiVersion();
10853     Redeclaration = true;
10854     OldDecl = OldFD;
10855     return false;
10856   }
10857 
10858   NewFD->setIsMultiVersion();
10859   Redeclaration = false;
10860   OldDecl = nullptr;
10861   Previous.clear();
10862   return false;
10863 }
10864 
10865 /// Check the validity of a mulitversion function declaration.
10866 /// Also sets the multiversion'ness' of the function itself.
10867 ///
10868 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10869 ///
10870 /// Returns true if there was an error, false otherwise.
10871 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10872                                       bool &Redeclaration, NamedDecl *&OldDecl,
10873                                       LookupResult &Previous) {
10874   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10875   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10876   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10877   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10878   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
10879 
10880   // Main isn't allowed to become a multiversion function, however it IS
10881   // permitted to have 'main' be marked with the 'target' optimization hint.
10882   if (NewFD->isMain()) {
10883     if (MVKind != MultiVersionKind::None &&
10884         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10885       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10886       NewFD->setInvalidDecl();
10887       return true;
10888     }
10889     return false;
10890   }
10891 
10892   if (!OldDecl || !OldDecl->getAsFunction() ||
10893       OldDecl->getDeclContext()->getRedeclContext() !=
10894           NewFD->getDeclContext()->getRedeclContext()) {
10895     // If there's no previous declaration, AND this isn't attempting to cause
10896     // multiversioning, this isn't an error condition.
10897     if (MVKind == MultiVersionKind::None)
10898       return false;
10899     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
10900   }
10901 
10902   FunctionDecl *OldFD = OldDecl->getAsFunction();
10903 
10904   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
10905     return false;
10906 
10907   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10908   // for target_clones.
10909   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
10910       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10911     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10912         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10913     NewFD->setInvalidDecl();
10914     return true;
10915   }
10916 
10917   if (!OldFD->isMultiVersion()) {
10918     switch (MVKind) {
10919     case MultiVersionKind::Target:
10920       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10921                                               Redeclaration, OldDecl, Previous);
10922     case MultiVersionKind::TargetClones:
10923       if (OldFD->isUsed(false)) {
10924         NewFD->setInvalidDecl();
10925         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10926       }
10927       OldFD->setIsMultiVersion();
10928       break;
10929     case MultiVersionKind::CPUDispatch:
10930     case MultiVersionKind::CPUSpecific:
10931     case MultiVersionKind::None:
10932       break;
10933     }
10934   }
10935 
10936   // At this point, we have a multiversion function decl (in OldFD) AND an
10937   // appropriate attribute in the current function decl.  Resolve that these are
10938   // still compatible with previous declarations.
10939   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
10940                                          NewCPUDisp, NewCPUSpec, NewClones,
10941                                          Redeclaration, OldDecl, Previous);
10942 }
10943 
10944 /// Perform semantic checking of a new function declaration.
10945 ///
10946 /// Performs semantic analysis of the new function declaration
10947 /// NewFD. This routine performs all semantic checking that does not
10948 /// require the actual declarator involved in the declaration, and is
10949 /// used both for the declaration of functions as they are parsed
10950 /// (called via ActOnDeclarator) and for the declaration of functions
10951 /// that have been instantiated via C++ template instantiation (called
10952 /// via InstantiateDecl).
10953 ///
10954 /// \param IsMemberSpecialization whether this new function declaration is
10955 /// a member specialization (that replaces any definition provided by the
10956 /// previous declaration).
10957 ///
10958 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10959 ///
10960 /// \returns true if the function declaration is a redeclaration.
10961 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10962                                     LookupResult &Previous,
10963                                     bool IsMemberSpecialization) {
10964   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10965          "Variably modified return types are not handled here");
10966 
10967   // Determine whether the type of this function should be merged with
10968   // a previous visible declaration. This never happens for functions in C++,
10969   // and always happens in C if the previous declaration was visible.
10970   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10971                                !Previous.isShadowed();
10972 
10973   bool Redeclaration = false;
10974   NamedDecl *OldDecl = nullptr;
10975   bool MayNeedOverloadableChecks = false;
10976 
10977   // Merge or overload the declaration with an existing declaration of
10978   // the same name, if appropriate.
10979   if (!Previous.empty()) {
10980     // Determine whether NewFD is an overload of PrevDecl or
10981     // a declaration that requires merging. If it's an overload,
10982     // there's no more work to do here; we'll just add the new
10983     // function to the scope.
10984     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10985       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10986       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10987         Redeclaration = true;
10988         OldDecl = Candidate;
10989       }
10990     } else {
10991       MayNeedOverloadableChecks = true;
10992       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10993                             /*NewIsUsingDecl*/ false)) {
10994       case Ovl_Match:
10995         Redeclaration = true;
10996         break;
10997 
10998       case Ovl_NonFunction:
10999         Redeclaration = true;
11000         break;
11001 
11002       case Ovl_Overload:
11003         Redeclaration = false;
11004         break;
11005       }
11006     }
11007   }
11008 
11009   // Check for a previous extern "C" declaration with this name.
11010   if (!Redeclaration &&
11011       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11012     if (!Previous.empty()) {
11013       // This is an extern "C" declaration with the same name as a previous
11014       // declaration, and thus redeclares that entity...
11015       Redeclaration = true;
11016       OldDecl = Previous.getFoundDecl();
11017       MergeTypeWithPrevious = false;
11018 
11019       // ... except in the presence of __attribute__((overloadable)).
11020       if (OldDecl->hasAttr<OverloadableAttr>() ||
11021           NewFD->hasAttr<OverloadableAttr>()) {
11022         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11023           MayNeedOverloadableChecks = true;
11024           Redeclaration = false;
11025           OldDecl = nullptr;
11026         }
11027       }
11028     }
11029   }
11030 
11031   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11032     return Redeclaration;
11033 
11034   // PPC MMA non-pointer types are not allowed as function return types.
11035   if (Context.getTargetInfo().getTriple().isPPC64() &&
11036       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11037     NewFD->setInvalidDecl();
11038   }
11039 
11040   // C++11 [dcl.constexpr]p8:
11041   //   A constexpr specifier for a non-static member function that is not
11042   //   a constructor declares that member function to be const.
11043   //
11044   // This needs to be delayed until we know whether this is an out-of-line
11045   // definition of a static member function.
11046   //
11047   // This rule is not present in C++1y, so we produce a backwards
11048   // compatibility warning whenever it happens in C++11.
11049   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11050   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11051       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11052       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11053     CXXMethodDecl *OldMD = nullptr;
11054     if (OldDecl)
11055       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11056     if (!OldMD || !OldMD->isStatic()) {
11057       const FunctionProtoType *FPT =
11058         MD->getType()->castAs<FunctionProtoType>();
11059       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11060       EPI.TypeQuals.addConst();
11061       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11062                                           FPT->getParamTypes(), EPI));
11063 
11064       // Warn that we did this, if we're not performing template instantiation.
11065       // In that case, we'll have warned already when the template was defined.
11066       if (!inTemplateInstantiation()) {
11067         SourceLocation AddConstLoc;
11068         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11069                 .IgnoreParens().getAs<FunctionTypeLoc>())
11070           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11071 
11072         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11073           << FixItHint::CreateInsertion(AddConstLoc, " const");
11074       }
11075     }
11076   }
11077 
11078   if (Redeclaration) {
11079     // NewFD and OldDecl represent declarations that need to be
11080     // merged.
11081     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11082       NewFD->setInvalidDecl();
11083       return Redeclaration;
11084     }
11085 
11086     Previous.clear();
11087     Previous.addDecl(OldDecl);
11088 
11089     if (FunctionTemplateDecl *OldTemplateDecl =
11090             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11091       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11092       FunctionTemplateDecl *NewTemplateDecl
11093         = NewFD->getDescribedFunctionTemplate();
11094       assert(NewTemplateDecl && "Template/non-template mismatch");
11095 
11096       // The call to MergeFunctionDecl above may have created some state in
11097       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11098       // can add it as a redeclaration.
11099       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11100 
11101       NewFD->setPreviousDeclaration(OldFD);
11102       if (NewFD->isCXXClassMember()) {
11103         NewFD->setAccess(OldTemplateDecl->getAccess());
11104         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11105       }
11106 
11107       // If this is an explicit specialization of a member that is a function
11108       // template, mark it as a member specialization.
11109       if (IsMemberSpecialization &&
11110           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11111         NewTemplateDecl->setMemberSpecialization();
11112         assert(OldTemplateDecl->isMemberSpecialization());
11113         // Explicit specializations of a member template do not inherit deleted
11114         // status from the parent member template that they are specializing.
11115         if (OldFD->isDeleted()) {
11116           // FIXME: This assert will not hold in the presence of modules.
11117           assert(OldFD->getCanonicalDecl() == OldFD);
11118           // FIXME: We need an update record for this AST mutation.
11119           OldFD->setDeletedAsWritten(false);
11120         }
11121       }
11122 
11123     } else {
11124       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11125         auto *OldFD = cast<FunctionDecl>(OldDecl);
11126         // This needs to happen first so that 'inline' propagates.
11127         NewFD->setPreviousDeclaration(OldFD);
11128         if (NewFD->isCXXClassMember())
11129           NewFD->setAccess(OldFD->getAccess());
11130       }
11131     }
11132   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11133              !NewFD->getAttr<OverloadableAttr>()) {
11134     assert((Previous.empty() ||
11135             llvm::any_of(Previous,
11136                          [](const NamedDecl *ND) {
11137                            return ND->hasAttr<OverloadableAttr>();
11138                          })) &&
11139            "Non-redecls shouldn't happen without overloadable present");
11140 
11141     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11142       const auto *FD = dyn_cast<FunctionDecl>(ND);
11143       return FD && !FD->hasAttr<OverloadableAttr>();
11144     });
11145 
11146     if (OtherUnmarkedIter != Previous.end()) {
11147       Diag(NewFD->getLocation(),
11148            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11149       Diag((*OtherUnmarkedIter)->getLocation(),
11150            diag::note_attribute_overloadable_prev_overload)
11151           << false;
11152 
11153       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11154     }
11155   }
11156 
11157   if (LangOpts.OpenMP)
11158     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11159 
11160   // Semantic checking for this function declaration (in isolation).
11161 
11162   if (getLangOpts().CPlusPlus) {
11163     // C++-specific checks.
11164     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11165       CheckConstructor(Constructor);
11166     } else if (CXXDestructorDecl *Destructor =
11167                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11168       CXXRecordDecl *Record = Destructor->getParent();
11169       QualType ClassType = Context.getTypeDeclType(Record);
11170 
11171       // FIXME: Shouldn't we be able to perform this check even when the class
11172       // type is dependent? Both gcc and edg can handle that.
11173       if (!ClassType->isDependentType()) {
11174         DeclarationName Name
11175           = Context.DeclarationNames.getCXXDestructorName(
11176                                         Context.getCanonicalType(ClassType));
11177         if (NewFD->getDeclName() != Name) {
11178           Diag(NewFD->getLocation(), diag::err_destructor_name);
11179           NewFD->setInvalidDecl();
11180           return Redeclaration;
11181         }
11182       }
11183     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11184       if (auto *TD = Guide->getDescribedFunctionTemplate())
11185         CheckDeductionGuideTemplate(TD);
11186 
11187       // A deduction guide is not on the list of entities that can be
11188       // explicitly specialized.
11189       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11190         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11191             << /*explicit specialization*/ 1;
11192     }
11193 
11194     // Find any virtual functions that this function overrides.
11195     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11196       if (!Method->isFunctionTemplateSpecialization() &&
11197           !Method->getDescribedFunctionTemplate() &&
11198           Method->isCanonicalDecl()) {
11199         AddOverriddenMethods(Method->getParent(), Method);
11200       }
11201       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11202         // C++2a [class.virtual]p6
11203         // A virtual method shall not have a requires-clause.
11204         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11205              diag::err_constrained_virtual_method);
11206 
11207       if (Method->isStatic())
11208         checkThisInStaticMemberFunctionType(Method);
11209     }
11210 
11211     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11212       ActOnConversionDeclarator(Conversion);
11213 
11214     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11215     if (NewFD->isOverloadedOperator() &&
11216         CheckOverloadedOperatorDeclaration(NewFD)) {
11217       NewFD->setInvalidDecl();
11218       return Redeclaration;
11219     }
11220 
11221     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11222     if (NewFD->getLiteralIdentifier() &&
11223         CheckLiteralOperatorDeclaration(NewFD)) {
11224       NewFD->setInvalidDecl();
11225       return Redeclaration;
11226     }
11227 
11228     // In C++, check default arguments now that we have merged decls. Unless
11229     // the lexical context is the class, because in this case this is done
11230     // during delayed parsing anyway.
11231     if (!CurContext->isRecord())
11232       CheckCXXDefaultArguments(NewFD);
11233 
11234     // If this function is declared as being extern "C", then check to see if
11235     // the function returns a UDT (class, struct, or union type) that is not C
11236     // compatible, and if it does, warn the user.
11237     // But, issue any diagnostic on the first declaration only.
11238     if (Previous.empty() && NewFD->isExternC()) {
11239       QualType R = NewFD->getReturnType();
11240       if (R->isIncompleteType() && !R->isVoidType())
11241         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11242             << NewFD << R;
11243       else if (!R.isPODType(Context) && !R->isVoidType() &&
11244                !R->isObjCObjectPointerType())
11245         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11246     }
11247 
11248     // C++1z [dcl.fct]p6:
11249     //   [...] whether the function has a non-throwing exception-specification
11250     //   [is] part of the function type
11251     //
11252     // This results in an ABI break between C++14 and C++17 for functions whose
11253     // declared type includes an exception-specification in a parameter or
11254     // return type. (Exception specifications on the function itself are OK in
11255     // most cases, and exception specifications are not permitted in most other
11256     // contexts where they could make it into a mangling.)
11257     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11258       auto HasNoexcept = [&](QualType T) -> bool {
11259         // Strip off declarator chunks that could be between us and a function
11260         // type. We don't need to look far, exception specifications are very
11261         // restricted prior to C++17.
11262         if (auto *RT = T->getAs<ReferenceType>())
11263           T = RT->getPointeeType();
11264         else if (T->isAnyPointerType())
11265           T = T->getPointeeType();
11266         else if (auto *MPT = T->getAs<MemberPointerType>())
11267           T = MPT->getPointeeType();
11268         if (auto *FPT = T->getAs<FunctionProtoType>())
11269           if (FPT->isNothrow())
11270             return true;
11271         return false;
11272       };
11273 
11274       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11275       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11276       for (QualType T : FPT->param_types())
11277         AnyNoexcept |= HasNoexcept(T);
11278       if (AnyNoexcept)
11279         Diag(NewFD->getLocation(),
11280              diag::warn_cxx17_compat_exception_spec_in_signature)
11281             << NewFD;
11282     }
11283 
11284     if (!Redeclaration && LangOpts.CUDA)
11285       checkCUDATargetOverload(NewFD, Previous);
11286   }
11287   return Redeclaration;
11288 }
11289 
11290 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11291   // C++11 [basic.start.main]p3:
11292   //   A program that [...] declares main to be inline, static or
11293   //   constexpr is ill-formed.
11294   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11295   //   appear in a declaration of main.
11296   // static main is not an error under C99, but we should warn about it.
11297   // We accept _Noreturn main as an extension.
11298   if (FD->getStorageClass() == SC_Static)
11299     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11300          ? diag::err_static_main : diag::warn_static_main)
11301       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11302   if (FD->isInlineSpecified())
11303     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11304       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11305   if (DS.isNoreturnSpecified()) {
11306     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11307     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11308     Diag(NoreturnLoc, diag::ext_noreturn_main);
11309     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11310       << FixItHint::CreateRemoval(NoreturnRange);
11311   }
11312   if (FD->isConstexpr()) {
11313     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11314         << FD->isConsteval()
11315         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11316     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11317   }
11318 
11319   if (getLangOpts().OpenCL) {
11320     Diag(FD->getLocation(), diag::err_opencl_no_main)
11321         << FD->hasAttr<OpenCLKernelAttr>();
11322     FD->setInvalidDecl();
11323     return;
11324   }
11325 
11326   QualType T = FD->getType();
11327   assert(T->isFunctionType() && "function decl is not of function type");
11328   const FunctionType* FT = T->castAs<FunctionType>();
11329 
11330   // Set default calling convention for main()
11331   if (FT->getCallConv() != CC_C) {
11332     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11333     FD->setType(QualType(FT, 0));
11334     T = Context.getCanonicalType(FD->getType());
11335   }
11336 
11337   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11338     // In C with GNU extensions we allow main() to have non-integer return
11339     // type, but we should warn about the extension, and we disable the
11340     // implicit-return-zero rule.
11341 
11342     // GCC in C mode accepts qualified 'int'.
11343     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11344       FD->setHasImplicitReturnZero(true);
11345     else {
11346       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11347       SourceRange RTRange = FD->getReturnTypeSourceRange();
11348       if (RTRange.isValid())
11349         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11350             << FixItHint::CreateReplacement(RTRange, "int");
11351     }
11352   } else {
11353     // In C and C++, main magically returns 0 if you fall off the end;
11354     // set the flag which tells us that.
11355     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11356 
11357     // All the standards say that main() should return 'int'.
11358     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11359       FD->setHasImplicitReturnZero(true);
11360     else {
11361       // Otherwise, this is just a flat-out error.
11362       SourceRange RTRange = FD->getReturnTypeSourceRange();
11363       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11364           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11365                                 : FixItHint());
11366       FD->setInvalidDecl(true);
11367     }
11368   }
11369 
11370   // Treat protoless main() as nullary.
11371   if (isa<FunctionNoProtoType>(FT)) return;
11372 
11373   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11374   unsigned nparams = FTP->getNumParams();
11375   assert(FD->getNumParams() == nparams);
11376 
11377   bool HasExtraParameters = (nparams > 3);
11378 
11379   if (FTP->isVariadic()) {
11380     Diag(FD->getLocation(), diag::ext_variadic_main);
11381     // FIXME: if we had information about the location of the ellipsis, we
11382     // could add a FixIt hint to remove it as a parameter.
11383   }
11384 
11385   // Darwin passes an undocumented fourth argument of type char**.  If
11386   // other platforms start sprouting these, the logic below will start
11387   // getting shifty.
11388   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11389     HasExtraParameters = false;
11390 
11391   if (HasExtraParameters) {
11392     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11393     FD->setInvalidDecl(true);
11394     nparams = 3;
11395   }
11396 
11397   // FIXME: a lot of the following diagnostics would be improved
11398   // if we had some location information about types.
11399 
11400   QualType CharPP =
11401     Context.getPointerType(Context.getPointerType(Context.CharTy));
11402   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11403 
11404   for (unsigned i = 0; i < nparams; ++i) {
11405     QualType AT = FTP->getParamType(i);
11406 
11407     bool mismatch = true;
11408 
11409     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11410       mismatch = false;
11411     else if (Expected[i] == CharPP) {
11412       // As an extension, the following forms are okay:
11413       //   char const **
11414       //   char const * const *
11415       //   char * const *
11416 
11417       QualifierCollector qs;
11418       const PointerType* PT;
11419       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11420           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11421           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11422                               Context.CharTy)) {
11423         qs.removeConst();
11424         mismatch = !qs.empty();
11425       }
11426     }
11427 
11428     if (mismatch) {
11429       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11430       // TODO: suggest replacing given type with expected type
11431       FD->setInvalidDecl(true);
11432     }
11433   }
11434 
11435   if (nparams == 1 && !FD->isInvalidDecl()) {
11436     Diag(FD->getLocation(), diag::warn_main_one_arg);
11437   }
11438 
11439   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11440     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11441     FD->setInvalidDecl();
11442   }
11443 }
11444 
11445 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11446 
11447   // Default calling convention for main and wmain is __cdecl
11448   if (FD->getName() == "main" || FD->getName() == "wmain")
11449     return false;
11450 
11451   // Default calling convention for MinGW is __cdecl
11452   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11453   if (T.isWindowsGNUEnvironment())
11454     return false;
11455 
11456   // Default calling convention for WinMain, wWinMain and DllMain
11457   // is __stdcall on 32 bit Windows
11458   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11459     return true;
11460 
11461   return false;
11462 }
11463 
11464 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11465   QualType T = FD->getType();
11466   assert(T->isFunctionType() && "function decl is not of function type");
11467   const FunctionType *FT = T->castAs<FunctionType>();
11468 
11469   // Set an implicit return of 'zero' if the function can return some integral,
11470   // enumeration, pointer or nullptr type.
11471   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11472       FT->getReturnType()->isAnyPointerType() ||
11473       FT->getReturnType()->isNullPtrType())
11474     // DllMain is exempt because a return value of zero means it failed.
11475     if (FD->getName() != "DllMain")
11476       FD->setHasImplicitReturnZero(true);
11477 
11478   // Explicity specified calling conventions are applied to MSVC entry points
11479   if (!hasExplicitCallingConv(T)) {
11480     if (isDefaultStdCall(FD, *this)) {
11481       if (FT->getCallConv() != CC_X86StdCall) {
11482         FT = Context.adjustFunctionType(
11483             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11484         FD->setType(QualType(FT, 0));
11485       }
11486     } else if (FT->getCallConv() != CC_C) {
11487       FT = Context.adjustFunctionType(FT,
11488                                       FT->getExtInfo().withCallingConv(CC_C));
11489       FD->setType(QualType(FT, 0));
11490     }
11491   }
11492 
11493   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11494     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11495     FD->setInvalidDecl();
11496   }
11497 }
11498 
11499 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11500   // FIXME: Need strict checking.  In C89, we need to check for
11501   // any assignment, increment, decrement, function-calls, or
11502   // commas outside of a sizeof.  In C99, it's the same list,
11503   // except that the aforementioned are allowed in unevaluated
11504   // expressions.  Everything else falls under the
11505   // "may accept other forms of constant expressions" exception.
11506   //
11507   // Regular C++ code will not end up here (exceptions: language extensions,
11508   // OpenCL C++ etc), so the constant expression rules there don't matter.
11509   if (Init->isValueDependent()) {
11510     assert(Init->containsErrors() &&
11511            "Dependent code should only occur in error-recovery path.");
11512     return true;
11513   }
11514   const Expr *Culprit;
11515   if (Init->isConstantInitializer(Context, false, &Culprit))
11516     return false;
11517   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11518     << Culprit->getSourceRange();
11519   return true;
11520 }
11521 
11522 namespace {
11523   // Visits an initialization expression to see if OrigDecl is evaluated in
11524   // its own initialization and throws a warning if it does.
11525   class SelfReferenceChecker
11526       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11527     Sema &S;
11528     Decl *OrigDecl;
11529     bool isRecordType;
11530     bool isPODType;
11531     bool isReferenceType;
11532 
11533     bool isInitList;
11534     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11535 
11536   public:
11537     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11538 
11539     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11540                                                     S(S), OrigDecl(OrigDecl) {
11541       isPODType = false;
11542       isRecordType = false;
11543       isReferenceType = false;
11544       isInitList = false;
11545       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11546         isPODType = VD->getType().isPODType(S.Context);
11547         isRecordType = VD->getType()->isRecordType();
11548         isReferenceType = VD->getType()->isReferenceType();
11549       }
11550     }
11551 
11552     // For most expressions, just call the visitor.  For initializer lists,
11553     // track the index of the field being initialized since fields are
11554     // initialized in order allowing use of previously initialized fields.
11555     void CheckExpr(Expr *E) {
11556       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11557       if (!InitList) {
11558         Visit(E);
11559         return;
11560       }
11561 
11562       // Track and increment the index here.
11563       isInitList = true;
11564       InitFieldIndex.push_back(0);
11565       for (auto Child : InitList->children()) {
11566         CheckExpr(cast<Expr>(Child));
11567         ++InitFieldIndex.back();
11568       }
11569       InitFieldIndex.pop_back();
11570     }
11571 
11572     // Returns true if MemberExpr is checked and no further checking is needed.
11573     // Returns false if additional checking is required.
11574     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11575       llvm::SmallVector<FieldDecl*, 4> Fields;
11576       Expr *Base = E;
11577       bool ReferenceField = false;
11578 
11579       // Get the field members used.
11580       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11581         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11582         if (!FD)
11583           return false;
11584         Fields.push_back(FD);
11585         if (FD->getType()->isReferenceType())
11586           ReferenceField = true;
11587         Base = ME->getBase()->IgnoreParenImpCasts();
11588       }
11589 
11590       // Keep checking only if the base Decl is the same.
11591       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11592       if (!DRE || DRE->getDecl() != OrigDecl)
11593         return false;
11594 
11595       // A reference field can be bound to an unininitialized field.
11596       if (CheckReference && !ReferenceField)
11597         return true;
11598 
11599       // Convert FieldDecls to their index number.
11600       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11601       for (const FieldDecl *I : llvm::reverse(Fields))
11602         UsedFieldIndex.push_back(I->getFieldIndex());
11603 
11604       // See if a warning is needed by checking the first difference in index
11605       // numbers.  If field being used has index less than the field being
11606       // initialized, then the use is safe.
11607       for (auto UsedIter = UsedFieldIndex.begin(),
11608                 UsedEnd = UsedFieldIndex.end(),
11609                 OrigIter = InitFieldIndex.begin(),
11610                 OrigEnd = InitFieldIndex.end();
11611            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11612         if (*UsedIter < *OrigIter)
11613           return true;
11614         if (*UsedIter > *OrigIter)
11615           break;
11616       }
11617 
11618       // TODO: Add a different warning which will print the field names.
11619       HandleDeclRefExpr(DRE);
11620       return true;
11621     }
11622 
11623     // For most expressions, the cast is directly above the DeclRefExpr.
11624     // For conditional operators, the cast can be outside the conditional
11625     // operator if both expressions are DeclRefExpr's.
11626     void HandleValue(Expr *E) {
11627       E = E->IgnoreParens();
11628       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11629         HandleDeclRefExpr(DRE);
11630         return;
11631       }
11632 
11633       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11634         Visit(CO->getCond());
11635         HandleValue(CO->getTrueExpr());
11636         HandleValue(CO->getFalseExpr());
11637         return;
11638       }
11639 
11640       if (BinaryConditionalOperator *BCO =
11641               dyn_cast<BinaryConditionalOperator>(E)) {
11642         Visit(BCO->getCond());
11643         HandleValue(BCO->getFalseExpr());
11644         return;
11645       }
11646 
11647       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11648         HandleValue(OVE->getSourceExpr());
11649         return;
11650       }
11651 
11652       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11653         if (BO->getOpcode() == BO_Comma) {
11654           Visit(BO->getLHS());
11655           HandleValue(BO->getRHS());
11656           return;
11657         }
11658       }
11659 
11660       if (isa<MemberExpr>(E)) {
11661         if (isInitList) {
11662           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11663                                       false /*CheckReference*/))
11664             return;
11665         }
11666 
11667         Expr *Base = E->IgnoreParenImpCasts();
11668         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11669           // Check for static member variables and don't warn on them.
11670           if (!isa<FieldDecl>(ME->getMemberDecl()))
11671             return;
11672           Base = ME->getBase()->IgnoreParenImpCasts();
11673         }
11674         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11675           HandleDeclRefExpr(DRE);
11676         return;
11677       }
11678 
11679       Visit(E);
11680     }
11681 
11682     // Reference types not handled in HandleValue are handled here since all
11683     // uses of references are bad, not just r-value uses.
11684     void VisitDeclRefExpr(DeclRefExpr *E) {
11685       if (isReferenceType)
11686         HandleDeclRefExpr(E);
11687     }
11688 
11689     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11690       if (E->getCastKind() == CK_LValueToRValue) {
11691         HandleValue(E->getSubExpr());
11692         return;
11693       }
11694 
11695       Inherited::VisitImplicitCastExpr(E);
11696     }
11697 
11698     void VisitMemberExpr(MemberExpr *E) {
11699       if (isInitList) {
11700         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11701           return;
11702       }
11703 
11704       // Don't warn on arrays since they can be treated as pointers.
11705       if (E->getType()->canDecayToPointerType()) return;
11706 
11707       // Warn when a non-static method call is followed by non-static member
11708       // field accesses, which is followed by a DeclRefExpr.
11709       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11710       bool Warn = (MD && !MD->isStatic());
11711       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11712       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11713         if (!isa<FieldDecl>(ME->getMemberDecl()))
11714           Warn = false;
11715         Base = ME->getBase()->IgnoreParenImpCasts();
11716       }
11717 
11718       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11719         if (Warn)
11720           HandleDeclRefExpr(DRE);
11721         return;
11722       }
11723 
11724       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11725       // Visit that expression.
11726       Visit(Base);
11727     }
11728 
11729     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11730       Expr *Callee = E->getCallee();
11731 
11732       if (isa<UnresolvedLookupExpr>(Callee))
11733         return Inherited::VisitCXXOperatorCallExpr(E);
11734 
11735       Visit(Callee);
11736       for (auto Arg: E->arguments())
11737         HandleValue(Arg->IgnoreParenImpCasts());
11738     }
11739 
11740     void VisitUnaryOperator(UnaryOperator *E) {
11741       // For POD record types, addresses of its own members are well-defined.
11742       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11743           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11744         if (!isPODType)
11745           HandleValue(E->getSubExpr());
11746         return;
11747       }
11748 
11749       if (E->isIncrementDecrementOp()) {
11750         HandleValue(E->getSubExpr());
11751         return;
11752       }
11753 
11754       Inherited::VisitUnaryOperator(E);
11755     }
11756 
11757     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11758 
11759     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11760       if (E->getConstructor()->isCopyConstructor()) {
11761         Expr *ArgExpr = E->getArg(0);
11762         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11763           if (ILE->getNumInits() == 1)
11764             ArgExpr = ILE->getInit(0);
11765         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11766           if (ICE->getCastKind() == CK_NoOp)
11767             ArgExpr = ICE->getSubExpr();
11768         HandleValue(ArgExpr);
11769         return;
11770       }
11771       Inherited::VisitCXXConstructExpr(E);
11772     }
11773 
11774     void VisitCallExpr(CallExpr *E) {
11775       // Treat std::move as a use.
11776       if (E->isCallToStdMove()) {
11777         HandleValue(E->getArg(0));
11778         return;
11779       }
11780 
11781       Inherited::VisitCallExpr(E);
11782     }
11783 
11784     void VisitBinaryOperator(BinaryOperator *E) {
11785       if (E->isCompoundAssignmentOp()) {
11786         HandleValue(E->getLHS());
11787         Visit(E->getRHS());
11788         return;
11789       }
11790 
11791       Inherited::VisitBinaryOperator(E);
11792     }
11793 
11794     // A custom visitor for BinaryConditionalOperator is needed because the
11795     // regular visitor would check the condition and true expression separately
11796     // but both point to the same place giving duplicate diagnostics.
11797     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11798       Visit(E->getCond());
11799       Visit(E->getFalseExpr());
11800     }
11801 
11802     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11803       Decl* ReferenceDecl = DRE->getDecl();
11804       if (OrigDecl != ReferenceDecl) return;
11805       unsigned diag;
11806       if (isReferenceType) {
11807         diag = diag::warn_uninit_self_reference_in_reference_init;
11808       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11809         diag = diag::warn_static_self_reference_in_init;
11810       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11811                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11812                  DRE->getDecl()->getType()->isRecordType()) {
11813         diag = diag::warn_uninit_self_reference_in_init;
11814       } else {
11815         // Local variables will be handled by the CFG analysis.
11816         return;
11817       }
11818 
11819       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11820                             S.PDiag(diag)
11821                                 << DRE->getDecl() << OrigDecl->getLocation()
11822                                 << DRE->getSourceRange());
11823     }
11824   };
11825 
11826   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11827   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11828                                  bool DirectInit) {
11829     // Parameters arguments are occassionially constructed with itself,
11830     // for instance, in recursive functions.  Skip them.
11831     if (isa<ParmVarDecl>(OrigDecl))
11832       return;
11833 
11834     E = E->IgnoreParens();
11835 
11836     // Skip checking T a = a where T is not a record or reference type.
11837     // Doing so is a way to silence uninitialized warnings.
11838     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11839       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11840         if (ICE->getCastKind() == CK_LValueToRValue)
11841           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11842             if (DRE->getDecl() == OrigDecl)
11843               return;
11844 
11845     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11846   }
11847 } // end anonymous namespace
11848 
11849 namespace {
11850   // Simple wrapper to add the name of a variable or (if no variable is
11851   // available) a DeclarationName into a diagnostic.
11852   struct VarDeclOrName {
11853     VarDecl *VDecl;
11854     DeclarationName Name;
11855 
11856     friend const Sema::SemaDiagnosticBuilder &
11857     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11858       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11859     }
11860   };
11861 } // end anonymous namespace
11862 
11863 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11864                                             DeclarationName Name, QualType Type,
11865                                             TypeSourceInfo *TSI,
11866                                             SourceRange Range, bool DirectInit,
11867                                             Expr *Init) {
11868   bool IsInitCapture = !VDecl;
11869   assert((!VDecl || !VDecl->isInitCapture()) &&
11870          "init captures are expected to be deduced prior to initialization");
11871 
11872   VarDeclOrName VN{VDecl, Name};
11873 
11874   DeducedType *Deduced = Type->getContainedDeducedType();
11875   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11876 
11877   // C++11 [dcl.spec.auto]p3
11878   if (!Init) {
11879     assert(VDecl && "no init for init capture deduction?");
11880 
11881     // Except for class argument deduction, and then for an initializing
11882     // declaration only, i.e. no static at class scope or extern.
11883     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11884         VDecl->hasExternalStorage() ||
11885         VDecl->isStaticDataMember()) {
11886       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11887         << VDecl->getDeclName() << Type;
11888       return QualType();
11889     }
11890   }
11891 
11892   ArrayRef<Expr*> DeduceInits;
11893   if (Init)
11894     DeduceInits = Init;
11895 
11896   if (DirectInit) {
11897     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11898       DeduceInits = PL->exprs();
11899   }
11900 
11901   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11902     assert(VDecl && "non-auto type for init capture deduction?");
11903     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11904     InitializationKind Kind = InitializationKind::CreateForInit(
11905         VDecl->getLocation(), DirectInit, Init);
11906     // FIXME: Initialization should not be taking a mutable list of inits.
11907     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11908     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11909                                                        InitsCopy);
11910   }
11911 
11912   if (DirectInit) {
11913     if (auto *IL = dyn_cast<InitListExpr>(Init))
11914       DeduceInits = IL->inits();
11915   }
11916 
11917   // Deduction only works if we have exactly one source expression.
11918   if (DeduceInits.empty()) {
11919     // It isn't possible to write this directly, but it is possible to
11920     // end up in this situation with "auto x(some_pack...);"
11921     Diag(Init->getBeginLoc(), IsInitCapture
11922                                   ? diag::err_init_capture_no_expression
11923                                   : diag::err_auto_var_init_no_expression)
11924         << VN << Type << Range;
11925     return QualType();
11926   }
11927 
11928   if (DeduceInits.size() > 1) {
11929     Diag(DeduceInits[1]->getBeginLoc(),
11930          IsInitCapture ? diag::err_init_capture_multiple_expressions
11931                        : diag::err_auto_var_init_multiple_expressions)
11932         << VN << Type << Range;
11933     return QualType();
11934   }
11935 
11936   Expr *DeduceInit = DeduceInits[0];
11937   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11938     Diag(Init->getBeginLoc(), IsInitCapture
11939                                   ? diag::err_init_capture_paren_braces
11940                                   : diag::err_auto_var_init_paren_braces)
11941         << isa<InitListExpr>(Init) << VN << Type << Range;
11942     return QualType();
11943   }
11944 
11945   // Expressions default to 'id' when we're in a debugger.
11946   bool DefaultedAnyToId = false;
11947   if (getLangOpts().DebuggerCastResultToId &&
11948       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11949     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11950     if (Result.isInvalid()) {
11951       return QualType();
11952     }
11953     Init = Result.get();
11954     DefaultedAnyToId = true;
11955   }
11956 
11957   // C++ [dcl.decomp]p1:
11958   //   If the assignment-expression [...] has array type A and no ref-qualifier
11959   //   is present, e has type cv A
11960   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11961       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11962       DeduceInit->getType()->isConstantArrayType())
11963     return Context.getQualifiedType(DeduceInit->getType(),
11964                                     Type.getQualifiers());
11965 
11966   QualType DeducedType;
11967   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11968     if (!IsInitCapture)
11969       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11970     else if (isa<InitListExpr>(Init))
11971       Diag(Range.getBegin(),
11972            diag::err_init_capture_deduction_failure_from_init_list)
11973           << VN
11974           << (DeduceInit->getType().isNull() ? TSI->getType()
11975                                              : DeduceInit->getType())
11976           << DeduceInit->getSourceRange();
11977     else
11978       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11979           << VN << TSI->getType()
11980           << (DeduceInit->getType().isNull() ? TSI->getType()
11981                                              : DeduceInit->getType())
11982           << DeduceInit->getSourceRange();
11983   }
11984 
11985   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11986   // 'id' instead of a specific object type prevents most of our usual
11987   // checks.
11988   // We only want to warn outside of template instantiations, though:
11989   // inside a template, the 'id' could have come from a parameter.
11990   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11991       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11992     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11993     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11994   }
11995 
11996   return DeducedType;
11997 }
11998 
11999 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12000                                          Expr *Init) {
12001   assert(!Init || !Init->containsErrors());
12002   QualType DeducedType = deduceVarTypeFromInitializer(
12003       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12004       VDecl->getSourceRange(), DirectInit, Init);
12005   if (DeducedType.isNull()) {
12006     VDecl->setInvalidDecl();
12007     return true;
12008   }
12009 
12010   VDecl->setType(DeducedType);
12011   assert(VDecl->isLinkageValid());
12012 
12013   // In ARC, infer lifetime.
12014   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12015     VDecl->setInvalidDecl();
12016 
12017   if (getLangOpts().OpenCL)
12018     deduceOpenCLAddressSpace(VDecl);
12019 
12020   // If this is a redeclaration, check that the type we just deduced matches
12021   // the previously declared type.
12022   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12023     // We never need to merge the type, because we cannot form an incomplete
12024     // array of auto, nor deduce such a type.
12025     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12026   }
12027 
12028   // Check the deduced type is valid for a variable declaration.
12029   CheckVariableDeclarationType(VDecl);
12030   return VDecl->isInvalidDecl();
12031 }
12032 
12033 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12034                                               SourceLocation Loc) {
12035   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12036     Init = EWC->getSubExpr();
12037 
12038   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12039     Init = CE->getSubExpr();
12040 
12041   QualType InitType = Init->getType();
12042   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12043           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12044          "shouldn't be called if type doesn't have a non-trivial C struct");
12045   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12046     for (auto I : ILE->inits()) {
12047       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12048           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12049         continue;
12050       SourceLocation SL = I->getExprLoc();
12051       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12052     }
12053     return;
12054   }
12055 
12056   if (isa<ImplicitValueInitExpr>(Init)) {
12057     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12058       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12059                             NTCUK_Init);
12060   } else {
12061     // Assume all other explicit initializers involving copying some existing
12062     // object.
12063     // TODO: ignore any explicit initializers where we can guarantee
12064     // copy-elision.
12065     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12066       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12067   }
12068 }
12069 
12070 namespace {
12071 
12072 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12073   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12074   // in the source code or implicitly by the compiler if it is in a union
12075   // defined in a system header and has non-trivial ObjC ownership
12076   // qualifications. We don't want those fields to participate in determining
12077   // whether the containing union is non-trivial.
12078   return FD->hasAttr<UnavailableAttr>();
12079 }
12080 
12081 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12082     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12083                                     void> {
12084   using Super =
12085       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12086                                     void>;
12087 
12088   DiagNonTrivalCUnionDefaultInitializeVisitor(
12089       QualType OrigTy, SourceLocation OrigLoc,
12090       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12091       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12092 
12093   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12094                      const FieldDecl *FD, bool InNonTrivialUnion) {
12095     if (const auto *AT = S.Context.getAsArrayType(QT))
12096       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12097                                      InNonTrivialUnion);
12098     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12099   }
12100 
12101   void visitARCStrong(QualType QT, const FieldDecl *FD,
12102                       bool InNonTrivialUnion) {
12103     if (InNonTrivialUnion)
12104       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12105           << 1 << 0 << QT << FD->getName();
12106   }
12107 
12108   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12109     if (InNonTrivialUnion)
12110       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12111           << 1 << 0 << QT << FD->getName();
12112   }
12113 
12114   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12115     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12116     if (RD->isUnion()) {
12117       if (OrigLoc.isValid()) {
12118         bool IsUnion = false;
12119         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12120           IsUnion = OrigRD->isUnion();
12121         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12122             << 0 << OrigTy << IsUnion << UseContext;
12123         // Reset OrigLoc so that this diagnostic is emitted only once.
12124         OrigLoc = SourceLocation();
12125       }
12126       InNonTrivialUnion = true;
12127     }
12128 
12129     if (InNonTrivialUnion)
12130       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12131           << 0 << 0 << QT.getUnqualifiedType() << "";
12132 
12133     for (const FieldDecl *FD : RD->fields())
12134       if (!shouldIgnoreForRecordTriviality(FD))
12135         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12136   }
12137 
12138   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12139 
12140   // The non-trivial C union type or the struct/union type that contains a
12141   // non-trivial C union.
12142   QualType OrigTy;
12143   SourceLocation OrigLoc;
12144   Sema::NonTrivialCUnionContext UseContext;
12145   Sema &S;
12146 };
12147 
12148 struct DiagNonTrivalCUnionDestructedTypeVisitor
12149     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12150   using Super =
12151       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12152 
12153   DiagNonTrivalCUnionDestructedTypeVisitor(
12154       QualType OrigTy, SourceLocation OrigLoc,
12155       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12156       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12157 
12158   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12159                      const FieldDecl *FD, bool InNonTrivialUnion) {
12160     if (const auto *AT = S.Context.getAsArrayType(QT))
12161       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12162                                      InNonTrivialUnion);
12163     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12164   }
12165 
12166   void visitARCStrong(QualType QT, const FieldDecl *FD,
12167                       bool InNonTrivialUnion) {
12168     if (InNonTrivialUnion)
12169       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12170           << 1 << 1 << QT << FD->getName();
12171   }
12172 
12173   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12174     if (InNonTrivialUnion)
12175       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12176           << 1 << 1 << QT << FD->getName();
12177   }
12178 
12179   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12180     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12181     if (RD->isUnion()) {
12182       if (OrigLoc.isValid()) {
12183         bool IsUnion = false;
12184         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12185           IsUnion = OrigRD->isUnion();
12186         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12187             << 1 << OrigTy << IsUnion << UseContext;
12188         // Reset OrigLoc so that this diagnostic is emitted only once.
12189         OrigLoc = SourceLocation();
12190       }
12191       InNonTrivialUnion = true;
12192     }
12193 
12194     if (InNonTrivialUnion)
12195       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12196           << 0 << 1 << QT.getUnqualifiedType() << "";
12197 
12198     for (const FieldDecl *FD : RD->fields())
12199       if (!shouldIgnoreForRecordTriviality(FD))
12200         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12201   }
12202 
12203   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12204   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12205                           bool InNonTrivialUnion) {}
12206 
12207   // The non-trivial C union type or the struct/union type that contains a
12208   // non-trivial C union.
12209   QualType OrigTy;
12210   SourceLocation OrigLoc;
12211   Sema::NonTrivialCUnionContext UseContext;
12212   Sema &S;
12213 };
12214 
12215 struct DiagNonTrivalCUnionCopyVisitor
12216     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12217   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12218 
12219   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12220                                  Sema::NonTrivialCUnionContext UseContext,
12221                                  Sema &S)
12222       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12223 
12224   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12225                      const FieldDecl *FD, bool InNonTrivialUnion) {
12226     if (const auto *AT = S.Context.getAsArrayType(QT))
12227       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12228                                      InNonTrivialUnion);
12229     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12230   }
12231 
12232   void visitARCStrong(QualType QT, const FieldDecl *FD,
12233                       bool InNonTrivialUnion) {
12234     if (InNonTrivialUnion)
12235       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12236           << 1 << 2 << QT << FD->getName();
12237   }
12238 
12239   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12240     if (InNonTrivialUnion)
12241       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12242           << 1 << 2 << QT << FD->getName();
12243   }
12244 
12245   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12246     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12247     if (RD->isUnion()) {
12248       if (OrigLoc.isValid()) {
12249         bool IsUnion = false;
12250         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12251           IsUnion = OrigRD->isUnion();
12252         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12253             << 2 << OrigTy << IsUnion << UseContext;
12254         // Reset OrigLoc so that this diagnostic is emitted only once.
12255         OrigLoc = SourceLocation();
12256       }
12257       InNonTrivialUnion = true;
12258     }
12259 
12260     if (InNonTrivialUnion)
12261       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12262           << 0 << 2 << QT.getUnqualifiedType() << "";
12263 
12264     for (const FieldDecl *FD : RD->fields())
12265       if (!shouldIgnoreForRecordTriviality(FD))
12266         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12267   }
12268 
12269   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12270                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12271   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12272   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12273                             bool InNonTrivialUnion) {}
12274 
12275   // The non-trivial C union type or the struct/union type that contains a
12276   // non-trivial C union.
12277   QualType OrigTy;
12278   SourceLocation OrigLoc;
12279   Sema::NonTrivialCUnionContext UseContext;
12280   Sema &S;
12281 };
12282 
12283 } // namespace
12284 
12285 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12286                                  NonTrivialCUnionContext UseContext,
12287                                  unsigned NonTrivialKind) {
12288   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12289           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12290           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12291          "shouldn't be called if type doesn't have a non-trivial C union");
12292 
12293   if ((NonTrivialKind & NTCUK_Init) &&
12294       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12295     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12296         .visit(QT, nullptr, false);
12297   if ((NonTrivialKind & NTCUK_Destruct) &&
12298       QT.hasNonTrivialToPrimitiveDestructCUnion())
12299     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12300         .visit(QT, nullptr, false);
12301   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12302     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12303         .visit(QT, nullptr, false);
12304 }
12305 
12306 /// AddInitializerToDecl - Adds the initializer Init to the
12307 /// declaration dcl. If DirectInit is true, this is C++ direct
12308 /// initialization rather than copy initialization.
12309 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12310   // If there is no declaration, there was an error parsing it.  Just ignore
12311   // the initializer.
12312   if (!RealDecl || RealDecl->isInvalidDecl()) {
12313     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12314     return;
12315   }
12316 
12317   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12318     // Pure-specifiers are handled in ActOnPureSpecifier.
12319     Diag(Method->getLocation(), diag::err_member_function_initialization)
12320       << Method->getDeclName() << Init->getSourceRange();
12321     Method->setInvalidDecl();
12322     return;
12323   }
12324 
12325   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12326   if (!VDecl) {
12327     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12328     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12329     RealDecl->setInvalidDecl();
12330     return;
12331   }
12332 
12333   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12334   if (VDecl->getType()->isUndeducedType()) {
12335     // Attempt typo correction early so that the type of the init expression can
12336     // be deduced based on the chosen correction if the original init contains a
12337     // TypoExpr.
12338     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12339     if (!Res.isUsable()) {
12340       // There are unresolved typos in Init, just drop them.
12341       // FIXME: improve the recovery strategy to preserve the Init.
12342       RealDecl->setInvalidDecl();
12343       return;
12344     }
12345     if (Res.get()->containsErrors()) {
12346       // Invalidate the decl as we don't know the type for recovery-expr yet.
12347       RealDecl->setInvalidDecl();
12348       VDecl->setInit(Res.get());
12349       return;
12350     }
12351     Init = Res.get();
12352 
12353     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12354       return;
12355   }
12356 
12357   // dllimport cannot be used on variable definitions.
12358   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12359     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12360     VDecl->setInvalidDecl();
12361     return;
12362   }
12363 
12364   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12365     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12366     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12367     VDecl->setInvalidDecl();
12368     return;
12369   }
12370 
12371   if (!VDecl->getType()->isDependentType()) {
12372     // A definition must end up with a complete type, which means it must be
12373     // complete with the restriction that an array type might be completed by
12374     // the initializer; note that later code assumes this restriction.
12375     QualType BaseDeclType = VDecl->getType();
12376     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12377       BaseDeclType = Array->getElementType();
12378     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12379                             diag::err_typecheck_decl_incomplete_type)) {
12380       RealDecl->setInvalidDecl();
12381       return;
12382     }
12383 
12384     // The variable can not have an abstract class type.
12385     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12386                                diag::err_abstract_type_in_decl,
12387                                AbstractVariableType))
12388       VDecl->setInvalidDecl();
12389   }
12390 
12391   // If adding the initializer will turn this declaration into a definition,
12392   // and we already have a definition for this variable, diagnose or otherwise
12393   // handle the situation.
12394   if (VarDecl *Def = VDecl->getDefinition())
12395     if (Def != VDecl &&
12396         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12397         !VDecl->isThisDeclarationADemotedDefinition() &&
12398         checkVarDeclRedefinition(Def, VDecl))
12399       return;
12400 
12401   if (getLangOpts().CPlusPlus) {
12402     // C++ [class.static.data]p4
12403     //   If a static data member is of const integral or const
12404     //   enumeration type, its declaration in the class definition can
12405     //   specify a constant-initializer which shall be an integral
12406     //   constant expression (5.19). In that case, the member can appear
12407     //   in integral constant expressions. The member shall still be
12408     //   defined in a namespace scope if it is used in the program and the
12409     //   namespace scope definition shall not contain an initializer.
12410     //
12411     // We already performed a redefinition check above, but for static
12412     // data members we also need to check whether there was an in-class
12413     // declaration with an initializer.
12414     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12415       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12416           << VDecl->getDeclName();
12417       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12418            diag::note_previous_initializer)
12419           << 0;
12420       return;
12421     }
12422 
12423     if (VDecl->hasLocalStorage())
12424       setFunctionHasBranchProtectedScope();
12425 
12426     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12427       VDecl->setInvalidDecl();
12428       return;
12429     }
12430   }
12431 
12432   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12433   // a kernel function cannot be initialized."
12434   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12435     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12436     VDecl->setInvalidDecl();
12437     return;
12438   }
12439 
12440   // The LoaderUninitialized attribute acts as a definition (of undef).
12441   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12442     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12443     VDecl->setInvalidDecl();
12444     return;
12445   }
12446 
12447   // Get the decls type and save a reference for later, since
12448   // CheckInitializerTypes may change it.
12449   QualType DclT = VDecl->getType(), SavT = DclT;
12450 
12451   // Expressions default to 'id' when we're in a debugger
12452   // and we are assigning it to a variable of Objective-C pointer type.
12453   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12454       Init->getType() == Context.UnknownAnyTy) {
12455     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12456     if (Result.isInvalid()) {
12457       VDecl->setInvalidDecl();
12458       return;
12459     }
12460     Init = Result.get();
12461   }
12462 
12463   // Perform the initialization.
12464   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12465   if (!VDecl->isInvalidDecl()) {
12466     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12467     InitializationKind Kind = InitializationKind::CreateForInit(
12468         VDecl->getLocation(), DirectInit, Init);
12469 
12470     MultiExprArg Args = Init;
12471     if (CXXDirectInit)
12472       Args = MultiExprArg(CXXDirectInit->getExprs(),
12473                           CXXDirectInit->getNumExprs());
12474 
12475     // Try to correct any TypoExprs in the initialization arguments.
12476     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12477       ExprResult Res = CorrectDelayedTyposInExpr(
12478           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12479           [this, Entity, Kind](Expr *E) {
12480             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12481             return Init.Failed() ? ExprError() : E;
12482           });
12483       if (Res.isInvalid()) {
12484         VDecl->setInvalidDecl();
12485       } else if (Res.get() != Args[Idx]) {
12486         Args[Idx] = Res.get();
12487       }
12488     }
12489     if (VDecl->isInvalidDecl())
12490       return;
12491 
12492     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12493                                    /*TopLevelOfInitList=*/false,
12494                                    /*TreatUnavailableAsInvalid=*/false);
12495     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12496     if (Result.isInvalid()) {
12497       // If the provided initializer fails to initialize the var decl,
12498       // we attach a recovery expr for better recovery.
12499       auto RecoveryExpr =
12500           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12501       if (RecoveryExpr.get())
12502         VDecl->setInit(RecoveryExpr.get());
12503       return;
12504     }
12505 
12506     Init = Result.getAs<Expr>();
12507   }
12508 
12509   // Check for self-references within variable initializers.
12510   // Variables declared within a function/method body (except for references)
12511   // are handled by a dataflow analysis.
12512   // This is undefined behavior in C++, but valid in C.
12513   if (getLangOpts().CPlusPlus)
12514     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12515         VDecl->getType()->isReferenceType())
12516       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12517 
12518   // If the type changed, it means we had an incomplete type that was
12519   // completed by the initializer. For example:
12520   //   int ary[] = { 1, 3, 5 };
12521   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12522   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12523     VDecl->setType(DclT);
12524 
12525   if (!VDecl->isInvalidDecl()) {
12526     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12527 
12528     if (VDecl->hasAttr<BlocksAttr>())
12529       checkRetainCycles(VDecl, Init);
12530 
12531     // It is safe to assign a weak reference into a strong variable.
12532     // Although this code can still have problems:
12533     //   id x = self.weakProp;
12534     //   id y = self.weakProp;
12535     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12536     // paths through the function. This should be revisited if
12537     // -Wrepeated-use-of-weak is made flow-sensitive.
12538     if (FunctionScopeInfo *FSI = getCurFunction())
12539       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12540            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12541           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12542                            Init->getBeginLoc()))
12543         FSI->markSafeWeakUse(Init);
12544   }
12545 
12546   // The initialization is usually a full-expression.
12547   //
12548   // FIXME: If this is a braced initialization of an aggregate, it is not
12549   // an expression, and each individual field initializer is a separate
12550   // full-expression. For instance, in:
12551   //
12552   //   struct Temp { ~Temp(); };
12553   //   struct S { S(Temp); };
12554   //   struct T { S a, b; } t = { Temp(), Temp() }
12555   //
12556   // we should destroy the first Temp before constructing the second.
12557   ExprResult Result =
12558       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12559                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12560   if (Result.isInvalid()) {
12561     VDecl->setInvalidDecl();
12562     return;
12563   }
12564   Init = Result.get();
12565 
12566   // Attach the initializer to the decl.
12567   VDecl->setInit(Init);
12568 
12569   if (VDecl->isLocalVarDecl()) {
12570     // Don't check the initializer if the declaration is malformed.
12571     if (VDecl->isInvalidDecl()) {
12572       // do nothing
12573 
12574     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12575     // This is true even in C++ for OpenCL.
12576     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12577       CheckForConstantInitializer(Init, DclT);
12578 
12579     // Otherwise, C++ does not restrict the initializer.
12580     } else if (getLangOpts().CPlusPlus) {
12581       // do nothing
12582 
12583     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12584     // static storage duration shall be constant expressions or string literals.
12585     } else if (VDecl->getStorageClass() == SC_Static) {
12586       CheckForConstantInitializer(Init, DclT);
12587 
12588     // C89 is stricter than C99 for aggregate initializers.
12589     // C89 6.5.7p3: All the expressions [...] in an initializer list
12590     // for an object that has aggregate or union type shall be
12591     // constant expressions.
12592     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12593                isa<InitListExpr>(Init)) {
12594       const Expr *Culprit;
12595       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12596         Diag(Culprit->getExprLoc(),
12597              diag::ext_aggregate_init_not_constant)
12598           << Culprit->getSourceRange();
12599       }
12600     }
12601 
12602     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12603       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12604         if (VDecl->hasLocalStorage())
12605           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12606   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12607              VDecl->getLexicalDeclContext()->isRecord()) {
12608     // This is an in-class initialization for a static data member, e.g.,
12609     //
12610     // struct S {
12611     //   static const int value = 17;
12612     // };
12613 
12614     // C++ [class.mem]p4:
12615     //   A member-declarator can contain a constant-initializer only
12616     //   if it declares a static member (9.4) of const integral or
12617     //   const enumeration type, see 9.4.2.
12618     //
12619     // C++11 [class.static.data]p3:
12620     //   If a non-volatile non-inline const static data member is of integral
12621     //   or enumeration type, its declaration in the class definition can
12622     //   specify a brace-or-equal-initializer in which every initializer-clause
12623     //   that is an assignment-expression is a constant expression. A static
12624     //   data member of literal type can be declared in the class definition
12625     //   with the constexpr specifier; if so, its declaration shall specify a
12626     //   brace-or-equal-initializer in which every initializer-clause that is
12627     //   an assignment-expression is a constant expression.
12628 
12629     // Do nothing on dependent types.
12630     if (DclT->isDependentType()) {
12631 
12632     // Allow any 'static constexpr' members, whether or not they are of literal
12633     // type. We separately check that every constexpr variable is of literal
12634     // type.
12635     } else if (VDecl->isConstexpr()) {
12636 
12637     // Require constness.
12638     } else if (!DclT.isConstQualified()) {
12639       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12640         << Init->getSourceRange();
12641       VDecl->setInvalidDecl();
12642 
12643     // We allow integer constant expressions in all cases.
12644     } else if (DclT->isIntegralOrEnumerationType()) {
12645       // Check whether the expression is a constant expression.
12646       SourceLocation Loc;
12647       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12648         // In C++11, a non-constexpr const static data member with an
12649         // in-class initializer cannot be volatile.
12650         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12651       else if (Init->isValueDependent())
12652         ; // Nothing to check.
12653       else if (Init->isIntegerConstantExpr(Context, &Loc))
12654         ; // Ok, it's an ICE!
12655       else if (Init->getType()->isScopedEnumeralType() &&
12656                Init->isCXX11ConstantExpr(Context))
12657         ; // Ok, it is a scoped-enum constant expression.
12658       else if (Init->isEvaluatable(Context)) {
12659         // If we can constant fold the initializer through heroics, accept it,
12660         // but report this as a use of an extension for -pedantic.
12661         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12662           << Init->getSourceRange();
12663       } else {
12664         // Otherwise, this is some crazy unknown case.  Report the issue at the
12665         // location provided by the isIntegerConstantExpr failed check.
12666         Diag(Loc, diag::err_in_class_initializer_non_constant)
12667           << Init->getSourceRange();
12668         VDecl->setInvalidDecl();
12669       }
12670 
12671     // We allow foldable floating-point constants as an extension.
12672     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12673       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12674       // it anyway and provide a fixit to add the 'constexpr'.
12675       if (getLangOpts().CPlusPlus11) {
12676         Diag(VDecl->getLocation(),
12677              diag::ext_in_class_initializer_float_type_cxx11)
12678             << DclT << Init->getSourceRange();
12679         Diag(VDecl->getBeginLoc(),
12680              diag::note_in_class_initializer_float_type_cxx11)
12681             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12682       } else {
12683         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12684           << DclT << Init->getSourceRange();
12685 
12686         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12687           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12688             << Init->getSourceRange();
12689           VDecl->setInvalidDecl();
12690         }
12691       }
12692 
12693     // Suggest adding 'constexpr' in C++11 for literal types.
12694     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12695       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12696           << DclT << Init->getSourceRange()
12697           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12698       VDecl->setConstexpr(true);
12699 
12700     } else {
12701       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12702         << DclT << Init->getSourceRange();
12703       VDecl->setInvalidDecl();
12704     }
12705   } else if (VDecl->isFileVarDecl()) {
12706     // In C, extern is typically used to avoid tentative definitions when
12707     // declaring variables in headers, but adding an intializer makes it a
12708     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12709     // In C++, extern is often used to give implictly static const variables
12710     // external linkage, so don't warn in that case. If selectany is present,
12711     // this might be header code intended for C and C++ inclusion, so apply the
12712     // C++ rules.
12713     if (VDecl->getStorageClass() == SC_Extern &&
12714         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12715          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12716         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12717         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12718       Diag(VDecl->getLocation(), diag::warn_extern_init);
12719 
12720     // In Microsoft C++ mode, a const variable defined in namespace scope has
12721     // external linkage by default if the variable is declared with
12722     // __declspec(dllexport).
12723     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12724         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12725         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12726       VDecl->setStorageClass(SC_Extern);
12727 
12728     // C99 6.7.8p4. All file scoped initializers need to be constant.
12729     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12730       CheckForConstantInitializer(Init, DclT);
12731   }
12732 
12733   QualType InitType = Init->getType();
12734   if (!InitType.isNull() &&
12735       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12736        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12737     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12738 
12739   // We will represent direct-initialization similarly to copy-initialization:
12740   //    int x(1);  -as-> int x = 1;
12741   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12742   //
12743   // Clients that want to distinguish between the two forms, can check for
12744   // direct initializer using VarDecl::getInitStyle().
12745   // A major benefit is that clients that don't particularly care about which
12746   // exactly form was it (like the CodeGen) can handle both cases without
12747   // special case code.
12748 
12749   // C++ 8.5p11:
12750   // The form of initialization (using parentheses or '=') is generally
12751   // insignificant, but does matter when the entity being initialized has a
12752   // class type.
12753   if (CXXDirectInit) {
12754     assert(DirectInit && "Call-style initializer must be direct init.");
12755     VDecl->setInitStyle(VarDecl::CallInit);
12756   } else if (DirectInit) {
12757     // This must be list-initialization. No other way is direct-initialization.
12758     VDecl->setInitStyle(VarDecl::ListInit);
12759   }
12760 
12761   if (LangOpts.OpenMP &&
12762       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12763       VDecl->isFileVarDecl())
12764     DeclsToCheckForDeferredDiags.insert(VDecl);
12765   CheckCompleteVariableDeclaration(VDecl);
12766 }
12767 
12768 /// ActOnInitializerError - Given that there was an error parsing an
12769 /// initializer for the given declaration, try to at least re-establish
12770 /// invariants such as whether a variable's type is either dependent or
12771 /// complete.
12772 void Sema::ActOnInitializerError(Decl *D) {
12773   // Our main concern here is re-establishing invariants like "a
12774   // variable's type is either dependent or complete".
12775   if (!D || D->isInvalidDecl()) return;
12776 
12777   VarDecl *VD = dyn_cast<VarDecl>(D);
12778   if (!VD) return;
12779 
12780   // Bindings are not usable if we can't make sense of the initializer.
12781   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12782     for (auto *BD : DD->bindings())
12783       BD->setInvalidDecl();
12784 
12785   // Auto types are meaningless if we can't make sense of the initializer.
12786   if (VD->getType()->isUndeducedType()) {
12787     D->setInvalidDecl();
12788     return;
12789   }
12790 
12791   QualType Ty = VD->getType();
12792   if (Ty->isDependentType()) return;
12793 
12794   // Require a complete type.
12795   if (RequireCompleteType(VD->getLocation(),
12796                           Context.getBaseElementType(Ty),
12797                           diag::err_typecheck_decl_incomplete_type)) {
12798     VD->setInvalidDecl();
12799     return;
12800   }
12801 
12802   // Require a non-abstract type.
12803   if (RequireNonAbstractType(VD->getLocation(), Ty,
12804                              diag::err_abstract_type_in_decl,
12805                              AbstractVariableType)) {
12806     VD->setInvalidDecl();
12807     return;
12808   }
12809 
12810   // Don't bother complaining about constructors or destructors,
12811   // though.
12812 }
12813 
12814 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12815   // If there is no declaration, there was an error parsing it. Just ignore it.
12816   if (!RealDecl)
12817     return;
12818 
12819   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12820     QualType Type = Var->getType();
12821 
12822     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12823     if (isa<DecompositionDecl>(RealDecl)) {
12824       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12825       Var->setInvalidDecl();
12826       return;
12827     }
12828 
12829     if (Type->isUndeducedType() &&
12830         DeduceVariableDeclarationType(Var, false, nullptr))
12831       return;
12832 
12833     // C++11 [class.static.data]p3: A static data member can be declared with
12834     // the constexpr specifier; if so, its declaration shall specify
12835     // a brace-or-equal-initializer.
12836     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12837     // the definition of a variable [...] or the declaration of a static data
12838     // member.
12839     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12840         !Var->isThisDeclarationADemotedDefinition()) {
12841       if (Var->isStaticDataMember()) {
12842         // C++1z removes the relevant rule; the in-class declaration is always
12843         // a definition there.
12844         if (!getLangOpts().CPlusPlus17 &&
12845             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12846           Diag(Var->getLocation(),
12847                diag::err_constexpr_static_mem_var_requires_init)
12848               << Var;
12849           Var->setInvalidDecl();
12850           return;
12851         }
12852       } else {
12853         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12854         Var->setInvalidDecl();
12855         return;
12856       }
12857     }
12858 
12859     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12860     // be initialized.
12861     if (!Var->isInvalidDecl() &&
12862         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12863         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12864       bool HasConstExprDefaultConstructor = false;
12865       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12866         for (auto *Ctor : RD->ctors()) {
12867           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12868               Ctor->getMethodQualifiers().getAddressSpace() ==
12869                   LangAS::opencl_constant) {
12870             HasConstExprDefaultConstructor = true;
12871           }
12872         }
12873       }
12874       if (!HasConstExprDefaultConstructor) {
12875         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12876         Var->setInvalidDecl();
12877         return;
12878       }
12879     }
12880 
12881     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12882       if (Var->getStorageClass() == SC_Extern) {
12883         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12884             << Var;
12885         Var->setInvalidDecl();
12886         return;
12887       }
12888       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12889                               diag::err_typecheck_decl_incomplete_type)) {
12890         Var->setInvalidDecl();
12891         return;
12892       }
12893       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12894         if (!RD->hasTrivialDefaultConstructor()) {
12895           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12896           Var->setInvalidDecl();
12897           return;
12898         }
12899       }
12900       // The declaration is unitialized, no need for further checks.
12901       return;
12902     }
12903 
12904     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12905     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12906         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12907       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12908                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12909 
12910 
12911     switch (DefKind) {
12912     case VarDecl::Definition:
12913       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12914         break;
12915 
12916       // We have an out-of-line definition of a static data member
12917       // that has an in-class initializer, so we type-check this like
12918       // a declaration.
12919       //
12920       LLVM_FALLTHROUGH;
12921 
12922     case VarDecl::DeclarationOnly:
12923       // It's only a declaration.
12924 
12925       // Block scope. C99 6.7p7: If an identifier for an object is
12926       // declared with no linkage (C99 6.2.2p6), the type for the
12927       // object shall be complete.
12928       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12929           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12930           RequireCompleteType(Var->getLocation(), Type,
12931                               diag::err_typecheck_decl_incomplete_type))
12932         Var->setInvalidDecl();
12933 
12934       // Make sure that the type is not abstract.
12935       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12936           RequireNonAbstractType(Var->getLocation(), Type,
12937                                  diag::err_abstract_type_in_decl,
12938                                  AbstractVariableType))
12939         Var->setInvalidDecl();
12940       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12941           Var->getStorageClass() == SC_PrivateExtern) {
12942         Diag(Var->getLocation(), diag::warn_private_extern);
12943         Diag(Var->getLocation(), diag::note_private_extern);
12944       }
12945 
12946       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12947           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12948         ExternalDeclarations.push_back(Var);
12949 
12950       return;
12951 
12952     case VarDecl::TentativeDefinition:
12953       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12954       // object that has file scope without an initializer, and without a
12955       // storage-class specifier or with the storage-class specifier "static",
12956       // constitutes a tentative definition. Note: A tentative definition with
12957       // external linkage is valid (C99 6.2.2p5).
12958       if (!Var->isInvalidDecl()) {
12959         if (const IncompleteArrayType *ArrayT
12960                                     = Context.getAsIncompleteArrayType(Type)) {
12961           if (RequireCompleteSizedType(
12962                   Var->getLocation(), ArrayT->getElementType(),
12963                   diag::err_array_incomplete_or_sizeless_type))
12964             Var->setInvalidDecl();
12965         } else if (Var->getStorageClass() == SC_Static) {
12966           // C99 6.9.2p3: If the declaration of an identifier for an object is
12967           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12968           // declared type shall not be an incomplete type.
12969           // NOTE: code such as the following
12970           //     static struct s;
12971           //     struct s { int a; };
12972           // is accepted by gcc. Hence here we issue a warning instead of
12973           // an error and we do not invalidate the static declaration.
12974           // NOTE: to avoid multiple warnings, only check the first declaration.
12975           if (Var->isFirstDecl())
12976             RequireCompleteType(Var->getLocation(), Type,
12977                                 diag::ext_typecheck_decl_incomplete_type);
12978         }
12979       }
12980 
12981       // Record the tentative definition; we're done.
12982       if (!Var->isInvalidDecl())
12983         TentativeDefinitions.push_back(Var);
12984       return;
12985     }
12986 
12987     // Provide a specific diagnostic for uninitialized variable
12988     // definitions with incomplete array type.
12989     if (Type->isIncompleteArrayType()) {
12990       Diag(Var->getLocation(),
12991            diag::err_typecheck_incomplete_array_needs_initializer);
12992       Var->setInvalidDecl();
12993       return;
12994     }
12995 
12996     // Provide a specific diagnostic for uninitialized variable
12997     // definitions with reference type.
12998     if (Type->isReferenceType()) {
12999       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13000           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13001       Var->setInvalidDecl();
13002       return;
13003     }
13004 
13005     // Do not attempt to type-check the default initializer for a
13006     // variable with dependent type.
13007     if (Type->isDependentType())
13008       return;
13009 
13010     if (Var->isInvalidDecl())
13011       return;
13012 
13013     if (!Var->hasAttr<AliasAttr>()) {
13014       if (RequireCompleteType(Var->getLocation(),
13015                               Context.getBaseElementType(Type),
13016                               diag::err_typecheck_decl_incomplete_type)) {
13017         Var->setInvalidDecl();
13018         return;
13019       }
13020     } else {
13021       return;
13022     }
13023 
13024     // The variable can not have an abstract class type.
13025     if (RequireNonAbstractType(Var->getLocation(), Type,
13026                                diag::err_abstract_type_in_decl,
13027                                AbstractVariableType)) {
13028       Var->setInvalidDecl();
13029       return;
13030     }
13031 
13032     // Check for jumps past the implicit initializer.  C++0x
13033     // clarifies that this applies to a "variable with automatic
13034     // storage duration", not a "local variable".
13035     // C++11 [stmt.dcl]p3
13036     //   A program that jumps from a point where a variable with automatic
13037     //   storage duration is not in scope to a point where it is in scope is
13038     //   ill-formed unless the variable has scalar type, class type with a
13039     //   trivial default constructor and a trivial destructor, a cv-qualified
13040     //   version of one of these types, or an array of one of the preceding
13041     //   types and is declared without an initializer.
13042     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13043       if (const RecordType *Record
13044             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13045         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13046         // Mark the function (if we're in one) for further checking even if the
13047         // looser rules of C++11 do not require such checks, so that we can
13048         // diagnose incompatibilities with C++98.
13049         if (!CXXRecord->isPOD())
13050           setFunctionHasBranchProtectedScope();
13051       }
13052     }
13053     // In OpenCL, we can't initialize objects in the __local address space,
13054     // even implicitly, so don't synthesize an implicit initializer.
13055     if (getLangOpts().OpenCL &&
13056         Var->getType().getAddressSpace() == LangAS::opencl_local)
13057       return;
13058     // C++03 [dcl.init]p9:
13059     //   If no initializer is specified for an object, and the
13060     //   object is of (possibly cv-qualified) non-POD class type (or
13061     //   array thereof), the object shall be default-initialized; if
13062     //   the object is of const-qualified type, the underlying class
13063     //   type shall have a user-declared default
13064     //   constructor. Otherwise, if no initializer is specified for
13065     //   a non- static object, the object and its subobjects, if
13066     //   any, have an indeterminate initial value); if the object
13067     //   or any of its subobjects are of const-qualified type, the
13068     //   program is ill-formed.
13069     // C++0x [dcl.init]p11:
13070     //   If no initializer is specified for an object, the object is
13071     //   default-initialized; [...].
13072     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13073     InitializationKind Kind
13074       = InitializationKind::CreateDefault(Var->getLocation());
13075 
13076     InitializationSequence InitSeq(*this, Entity, Kind, None);
13077     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13078 
13079     if (Init.get()) {
13080       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13081       // This is important for template substitution.
13082       Var->setInitStyle(VarDecl::CallInit);
13083     } else if (Init.isInvalid()) {
13084       // If default-init fails, attach a recovery-expr initializer to track
13085       // that initialization was attempted and failed.
13086       auto RecoveryExpr =
13087           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13088       if (RecoveryExpr.get())
13089         Var->setInit(RecoveryExpr.get());
13090     }
13091 
13092     CheckCompleteVariableDeclaration(Var);
13093   }
13094 }
13095 
13096 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13097   // If there is no declaration, there was an error parsing it. Ignore it.
13098   if (!D)
13099     return;
13100 
13101   VarDecl *VD = dyn_cast<VarDecl>(D);
13102   if (!VD) {
13103     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13104     D->setInvalidDecl();
13105     return;
13106   }
13107 
13108   VD->setCXXForRangeDecl(true);
13109 
13110   // for-range-declaration cannot be given a storage class specifier.
13111   int Error = -1;
13112   switch (VD->getStorageClass()) {
13113   case SC_None:
13114     break;
13115   case SC_Extern:
13116     Error = 0;
13117     break;
13118   case SC_Static:
13119     Error = 1;
13120     break;
13121   case SC_PrivateExtern:
13122     Error = 2;
13123     break;
13124   case SC_Auto:
13125     Error = 3;
13126     break;
13127   case SC_Register:
13128     Error = 4;
13129     break;
13130   }
13131 
13132   // for-range-declaration cannot be given a storage class specifier con't.
13133   switch (VD->getTSCSpec()) {
13134   case TSCS_thread_local:
13135     Error = 6;
13136     break;
13137   case TSCS___thread:
13138   case TSCS__Thread_local:
13139   case TSCS_unspecified:
13140     break;
13141   }
13142 
13143   if (Error != -1) {
13144     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13145         << VD << Error;
13146     D->setInvalidDecl();
13147   }
13148 }
13149 
13150 StmtResult
13151 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13152                                  IdentifierInfo *Ident,
13153                                  ParsedAttributes &Attrs,
13154                                  SourceLocation AttrEnd) {
13155   // C++1y [stmt.iter]p1:
13156   //   A range-based for statement of the form
13157   //      for ( for-range-identifier : for-range-initializer ) statement
13158   //   is equivalent to
13159   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13160   DeclSpec DS(Attrs.getPool().getFactory());
13161 
13162   const char *PrevSpec;
13163   unsigned DiagID;
13164   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13165                      getPrintingPolicy());
13166 
13167   Declarator D(DS, DeclaratorContext::ForInit);
13168   D.SetIdentifier(Ident, IdentLoc);
13169   D.takeAttributes(Attrs, AttrEnd);
13170 
13171   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13172                 IdentLoc);
13173   Decl *Var = ActOnDeclarator(S, D);
13174   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13175   FinalizeDeclaration(Var);
13176   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13177                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13178 }
13179 
13180 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13181   if (var->isInvalidDecl()) return;
13182 
13183   MaybeAddCUDAConstantAttr(var);
13184 
13185   if (getLangOpts().OpenCL) {
13186     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13187     // initialiser
13188     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13189         !var->hasInit()) {
13190       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13191           << 1 /*Init*/;
13192       var->setInvalidDecl();
13193       return;
13194     }
13195   }
13196 
13197   // In Objective-C, don't allow jumps past the implicit initialization of a
13198   // local retaining variable.
13199   if (getLangOpts().ObjC &&
13200       var->hasLocalStorage()) {
13201     switch (var->getType().getObjCLifetime()) {
13202     case Qualifiers::OCL_None:
13203     case Qualifiers::OCL_ExplicitNone:
13204     case Qualifiers::OCL_Autoreleasing:
13205       break;
13206 
13207     case Qualifiers::OCL_Weak:
13208     case Qualifiers::OCL_Strong:
13209       setFunctionHasBranchProtectedScope();
13210       break;
13211     }
13212   }
13213 
13214   if (var->hasLocalStorage() &&
13215       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13216     setFunctionHasBranchProtectedScope();
13217 
13218   // Warn about externally-visible variables being defined without a
13219   // prior declaration.  We only want to do this for global
13220   // declarations, but we also specifically need to avoid doing it for
13221   // class members because the linkage of an anonymous class can
13222   // change if it's later given a typedef name.
13223   if (var->isThisDeclarationADefinition() &&
13224       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13225       var->isExternallyVisible() && var->hasLinkage() &&
13226       !var->isInline() && !var->getDescribedVarTemplate() &&
13227       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13228       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13229       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13230                                   var->getLocation())) {
13231     // Find a previous declaration that's not a definition.
13232     VarDecl *prev = var->getPreviousDecl();
13233     while (prev && prev->isThisDeclarationADefinition())
13234       prev = prev->getPreviousDecl();
13235 
13236     if (!prev) {
13237       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13238       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13239           << /* variable */ 0;
13240     }
13241   }
13242 
13243   // Cache the result of checking for constant initialization.
13244   Optional<bool> CacheHasConstInit;
13245   const Expr *CacheCulprit = nullptr;
13246   auto checkConstInit = [&]() mutable {
13247     if (!CacheHasConstInit)
13248       CacheHasConstInit = var->getInit()->isConstantInitializer(
13249             Context, var->getType()->isReferenceType(), &CacheCulprit);
13250     return *CacheHasConstInit;
13251   };
13252 
13253   if (var->getTLSKind() == VarDecl::TLS_Static) {
13254     if (var->getType().isDestructedType()) {
13255       // GNU C++98 edits for __thread, [basic.start.term]p3:
13256       //   The type of an object with thread storage duration shall not
13257       //   have a non-trivial destructor.
13258       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13259       if (getLangOpts().CPlusPlus11)
13260         Diag(var->getLocation(), diag::note_use_thread_local);
13261     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13262       if (!checkConstInit()) {
13263         // GNU C++98 edits for __thread, [basic.start.init]p4:
13264         //   An object of thread storage duration shall not require dynamic
13265         //   initialization.
13266         // FIXME: Need strict checking here.
13267         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13268           << CacheCulprit->getSourceRange();
13269         if (getLangOpts().CPlusPlus11)
13270           Diag(var->getLocation(), diag::note_use_thread_local);
13271       }
13272     }
13273   }
13274 
13275 
13276   if (!var->getType()->isStructureType() && var->hasInit() &&
13277       isa<InitListExpr>(var->getInit())) {
13278     const auto *ILE = cast<InitListExpr>(var->getInit());
13279     unsigned NumInits = ILE->getNumInits();
13280     if (NumInits > 2)
13281       for (unsigned I = 0; I < NumInits; ++I) {
13282         const auto *Init = ILE->getInit(I);
13283         if (!Init)
13284           break;
13285         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13286         if (!SL)
13287           break;
13288 
13289         unsigned NumConcat = SL->getNumConcatenated();
13290         // Diagnose missing comma in string array initialization.
13291         // Do not warn when all the elements in the initializer are concatenated
13292         // together. Do not warn for macros too.
13293         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13294           bool OnlyOneMissingComma = true;
13295           for (unsigned J = I + 1; J < NumInits; ++J) {
13296             const auto *Init = ILE->getInit(J);
13297             if (!Init)
13298               break;
13299             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13300             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13301               OnlyOneMissingComma = false;
13302               break;
13303             }
13304           }
13305 
13306           if (OnlyOneMissingComma) {
13307             SmallVector<FixItHint, 1> Hints;
13308             for (unsigned i = 0; i < NumConcat - 1; ++i)
13309               Hints.push_back(FixItHint::CreateInsertion(
13310                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13311 
13312             Diag(SL->getStrTokenLoc(1),
13313                  diag::warn_concatenated_literal_array_init)
13314                 << Hints;
13315             Diag(SL->getBeginLoc(),
13316                  diag::note_concatenated_string_literal_silence);
13317           }
13318           // In any case, stop now.
13319           break;
13320         }
13321       }
13322   }
13323 
13324 
13325   QualType type = var->getType();
13326 
13327   if (var->hasAttr<BlocksAttr>())
13328     getCurFunction()->addByrefBlockVar(var);
13329 
13330   Expr *Init = var->getInit();
13331   bool GlobalStorage = var->hasGlobalStorage();
13332   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13333   QualType baseType = Context.getBaseElementType(type);
13334   bool HasConstInit = true;
13335 
13336   // Check whether the initializer is sufficiently constant.
13337   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13338       !Init->isValueDependent() &&
13339       (GlobalStorage || var->isConstexpr() ||
13340        var->mightBeUsableInConstantExpressions(Context))) {
13341     // If this variable might have a constant initializer or might be usable in
13342     // constant expressions, check whether or not it actually is now.  We can't
13343     // do this lazily, because the result might depend on things that change
13344     // later, such as which constexpr functions happen to be defined.
13345     SmallVector<PartialDiagnosticAt, 8> Notes;
13346     if (!getLangOpts().CPlusPlus11) {
13347       // Prior to C++11, in contexts where a constant initializer is required,
13348       // the set of valid constant initializers is described by syntactic rules
13349       // in [expr.const]p2-6.
13350       // FIXME: Stricter checking for these rules would be useful for constinit /
13351       // -Wglobal-constructors.
13352       HasConstInit = checkConstInit();
13353 
13354       // Compute and cache the constant value, and remember that we have a
13355       // constant initializer.
13356       if (HasConstInit) {
13357         (void)var->checkForConstantInitialization(Notes);
13358         Notes.clear();
13359       } else if (CacheCulprit) {
13360         Notes.emplace_back(CacheCulprit->getExprLoc(),
13361                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13362         Notes.back().second << CacheCulprit->getSourceRange();
13363       }
13364     } else {
13365       // Evaluate the initializer to see if it's a constant initializer.
13366       HasConstInit = var->checkForConstantInitialization(Notes);
13367     }
13368 
13369     if (HasConstInit) {
13370       // FIXME: Consider replacing the initializer with a ConstantExpr.
13371     } else if (var->isConstexpr()) {
13372       SourceLocation DiagLoc = var->getLocation();
13373       // If the note doesn't add any useful information other than a source
13374       // location, fold it into the primary diagnostic.
13375       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13376                                    diag::note_invalid_subexpr_in_const_expr) {
13377         DiagLoc = Notes[0].first;
13378         Notes.clear();
13379       }
13380       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13381           << var << Init->getSourceRange();
13382       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13383         Diag(Notes[I].first, Notes[I].second);
13384     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13385       auto *Attr = var->getAttr<ConstInitAttr>();
13386       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13387           << Init->getSourceRange();
13388       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13389           << Attr->getRange() << Attr->isConstinit();
13390       for (auto &it : Notes)
13391         Diag(it.first, it.second);
13392     } else if (IsGlobal &&
13393                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13394                                            var->getLocation())) {
13395       // Warn about globals which don't have a constant initializer.  Don't
13396       // warn about globals with a non-trivial destructor because we already
13397       // warned about them.
13398       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13399       if (!(RD && !RD->hasTrivialDestructor())) {
13400         // checkConstInit() here permits trivial default initialization even in
13401         // C++11 onwards, where such an initializer is not a constant initializer
13402         // but nonetheless doesn't require a global constructor.
13403         if (!checkConstInit())
13404           Diag(var->getLocation(), diag::warn_global_constructor)
13405               << Init->getSourceRange();
13406       }
13407     }
13408   }
13409 
13410   // Apply section attributes and pragmas to global variables.
13411   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13412       !inTemplateInstantiation()) {
13413     PragmaStack<StringLiteral *> *Stack = nullptr;
13414     int SectionFlags = ASTContext::PSF_Read;
13415     if (var->getType().isConstQualified()) {
13416       if (HasConstInit)
13417         Stack = &ConstSegStack;
13418       else {
13419         Stack = &BSSSegStack;
13420         SectionFlags |= ASTContext::PSF_Write;
13421       }
13422     } else if (var->hasInit() && HasConstInit) {
13423       Stack = &DataSegStack;
13424       SectionFlags |= ASTContext::PSF_Write;
13425     } else {
13426       Stack = &BSSSegStack;
13427       SectionFlags |= ASTContext::PSF_Write;
13428     }
13429     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13430       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13431         SectionFlags |= ASTContext::PSF_Implicit;
13432       UnifySection(SA->getName(), SectionFlags, var);
13433     } else if (Stack->CurrentValue) {
13434       SectionFlags |= ASTContext::PSF_Implicit;
13435       auto SectionName = Stack->CurrentValue->getString();
13436       var->addAttr(SectionAttr::CreateImplicit(
13437           Context, SectionName, Stack->CurrentPragmaLocation,
13438           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13439       if (UnifySection(SectionName, SectionFlags, var))
13440         var->dropAttr<SectionAttr>();
13441     }
13442 
13443     // Apply the init_seg attribute if this has an initializer.  If the
13444     // initializer turns out to not be dynamic, we'll end up ignoring this
13445     // attribute.
13446     if (CurInitSeg && var->getInit())
13447       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13448                                                CurInitSegLoc,
13449                                                AttributeCommonInfo::AS_Pragma));
13450   }
13451 
13452   // All the following checks are C++ only.
13453   if (!getLangOpts().CPlusPlus) {
13454     // If this variable must be emitted, add it as an initializer for the
13455     // current module.
13456     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13457       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13458     return;
13459   }
13460 
13461   // Require the destructor.
13462   if (!type->isDependentType())
13463     if (const RecordType *recordType = baseType->getAs<RecordType>())
13464       FinalizeVarWithDestructor(var, recordType);
13465 
13466   // If this variable must be emitted, add it as an initializer for the current
13467   // module.
13468   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13469     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13470 
13471   // Build the bindings if this is a structured binding declaration.
13472   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13473     CheckCompleteDecompositionDeclaration(DD);
13474 }
13475 
13476 /// Check if VD needs to be dllexport/dllimport due to being in a
13477 /// dllexport/import function.
13478 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13479   assert(VD->isStaticLocal());
13480 
13481   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13482 
13483   // Find outermost function when VD is in lambda function.
13484   while (FD && !getDLLAttr(FD) &&
13485          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13486          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13487     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13488   }
13489 
13490   if (!FD)
13491     return;
13492 
13493   // Static locals inherit dll attributes from their function.
13494   if (Attr *A = getDLLAttr(FD)) {
13495     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13496     NewAttr->setInherited(true);
13497     VD->addAttr(NewAttr);
13498   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13499     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13500     NewAttr->setInherited(true);
13501     VD->addAttr(NewAttr);
13502 
13503     // Export this function to enforce exporting this static variable even
13504     // if it is not used in this compilation unit.
13505     if (!FD->hasAttr<DLLExportAttr>())
13506       FD->addAttr(NewAttr);
13507 
13508   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13509     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13510     NewAttr->setInherited(true);
13511     VD->addAttr(NewAttr);
13512   }
13513 }
13514 
13515 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13516 /// any semantic actions necessary after any initializer has been attached.
13517 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13518   // Note that we are no longer parsing the initializer for this declaration.
13519   ParsingInitForAutoVars.erase(ThisDecl);
13520 
13521   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13522   if (!VD)
13523     return;
13524 
13525   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13526   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13527       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13528     if (PragmaClangBSSSection.Valid)
13529       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13530           Context, PragmaClangBSSSection.SectionName,
13531           PragmaClangBSSSection.PragmaLocation,
13532           AttributeCommonInfo::AS_Pragma));
13533     if (PragmaClangDataSection.Valid)
13534       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13535           Context, PragmaClangDataSection.SectionName,
13536           PragmaClangDataSection.PragmaLocation,
13537           AttributeCommonInfo::AS_Pragma));
13538     if (PragmaClangRodataSection.Valid)
13539       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13540           Context, PragmaClangRodataSection.SectionName,
13541           PragmaClangRodataSection.PragmaLocation,
13542           AttributeCommonInfo::AS_Pragma));
13543     if (PragmaClangRelroSection.Valid)
13544       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13545           Context, PragmaClangRelroSection.SectionName,
13546           PragmaClangRelroSection.PragmaLocation,
13547           AttributeCommonInfo::AS_Pragma));
13548   }
13549 
13550   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13551     for (auto *BD : DD->bindings()) {
13552       FinalizeDeclaration(BD);
13553     }
13554   }
13555 
13556   checkAttributesAfterMerging(*this, *VD);
13557 
13558   // Perform TLS alignment check here after attributes attached to the variable
13559   // which may affect the alignment have been processed. Only perform the check
13560   // if the target has a maximum TLS alignment (zero means no constraints).
13561   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13562     // Protect the check so that it's not performed on dependent types and
13563     // dependent alignments (we can't determine the alignment in that case).
13564     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13565       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13566       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13567         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13568           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13569           << (unsigned)MaxAlignChars.getQuantity();
13570       }
13571     }
13572   }
13573 
13574   if (VD->isStaticLocal())
13575     CheckStaticLocalForDllExport(VD);
13576 
13577   // Perform check for initializers of device-side global variables.
13578   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13579   // 7.5). We must also apply the same checks to all __shared__
13580   // variables whether they are local or not. CUDA also allows
13581   // constant initializers for __constant__ and __device__ variables.
13582   if (getLangOpts().CUDA)
13583     checkAllowedCUDAInitializer(VD);
13584 
13585   // Grab the dllimport or dllexport attribute off of the VarDecl.
13586   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13587 
13588   // Imported static data members cannot be defined out-of-line.
13589   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13590     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13591         VD->isThisDeclarationADefinition()) {
13592       // We allow definitions of dllimport class template static data members
13593       // with a warning.
13594       CXXRecordDecl *Context =
13595         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13596       bool IsClassTemplateMember =
13597           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13598           Context->getDescribedClassTemplate();
13599 
13600       Diag(VD->getLocation(),
13601            IsClassTemplateMember
13602                ? diag::warn_attribute_dllimport_static_field_definition
13603                : diag::err_attribute_dllimport_static_field_definition);
13604       Diag(IA->getLocation(), diag::note_attribute);
13605       if (!IsClassTemplateMember)
13606         VD->setInvalidDecl();
13607     }
13608   }
13609 
13610   // dllimport/dllexport variables cannot be thread local, their TLS index
13611   // isn't exported with the variable.
13612   if (DLLAttr && VD->getTLSKind()) {
13613     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13614     if (F && getDLLAttr(F)) {
13615       assert(VD->isStaticLocal());
13616       // But if this is a static local in a dlimport/dllexport function, the
13617       // function will never be inlined, which means the var would never be
13618       // imported, so having it marked import/export is safe.
13619     } else {
13620       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13621                                                                     << DLLAttr;
13622       VD->setInvalidDecl();
13623     }
13624   }
13625 
13626   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13627     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13628       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13629           << Attr;
13630       VD->dropAttr<UsedAttr>();
13631     }
13632   }
13633   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13634     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13635       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13636           << Attr;
13637       VD->dropAttr<RetainAttr>();
13638     }
13639   }
13640 
13641   const DeclContext *DC = VD->getDeclContext();
13642   // If there's a #pragma GCC visibility in scope, and this isn't a class
13643   // member, set the visibility of this variable.
13644   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13645     AddPushedVisibilityAttribute(VD);
13646 
13647   // FIXME: Warn on unused var template partial specializations.
13648   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13649     MarkUnusedFileScopedDecl(VD);
13650 
13651   // Now we have parsed the initializer and can update the table of magic
13652   // tag values.
13653   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13654       !VD->getType()->isIntegralOrEnumerationType())
13655     return;
13656 
13657   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13658     const Expr *MagicValueExpr = VD->getInit();
13659     if (!MagicValueExpr) {
13660       continue;
13661     }
13662     Optional<llvm::APSInt> MagicValueInt;
13663     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13664       Diag(I->getRange().getBegin(),
13665            diag::err_type_tag_for_datatype_not_ice)
13666         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13667       continue;
13668     }
13669     if (MagicValueInt->getActiveBits() > 64) {
13670       Diag(I->getRange().getBegin(),
13671            diag::err_type_tag_for_datatype_too_large)
13672         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13673       continue;
13674     }
13675     uint64_t MagicValue = MagicValueInt->getZExtValue();
13676     RegisterTypeTagForDatatype(I->getArgumentKind(),
13677                                MagicValue,
13678                                I->getMatchingCType(),
13679                                I->getLayoutCompatible(),
13680                                I->getMustBeNull());
13681   }
13682 }
13683 
13684 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13685   auto *VD = dyn_cast<VarDecl>(DD);
13686   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13687 }
13688 
13689 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13690                                                    ArrayRef<Decl *> Group) {
13691   SmallVector<Decl*, 8> Decls;
13692 
13693   if (DS.isTypeSpecOwned())
13694     Decls.push_back(DS.getRepAsDecl());
13695 
13696   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13697   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13698   bool DiagnosedMultipleDecomps = false;
13699   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13700   bool DiagnosedNonDeducedAuto = false;
13701 
13702   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13703     if (Decl *D = Group[i]) {
13704       // For declarators, there are some additional syntactic-ish checks we need
13705       // to perform.
13706       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13707         if (!FirstDeclaratorInGroup)
13708           FirstDeclaratorInGroup = DD;
13709         if (!FirstDecompDeclaratorInGroup)
13710           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13711         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13712             !hasDeducedAuto(DD))
13713           FirstNonDeducedAutoInGroup = DD;
13714 
13715         if (FirstDeclaratorInGroup != DD) {
13716           // A decomposition declaration cannot be combined with any other
13717           // declaration in the same group.
13718           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13719             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13720                  diag::err_decomp_decl_not_alone)
13721                 << FirstDeclaratorInGroup->getSourceRange()
13722                 << DD->getSourceRange();
13723             DiagnosedMultipleDecomps = true;
13724           }
13725 
13726           // A declarator that uses 'auto' in any way other than to declare a
13727           // variable with a deduced type cannot be combined with any other
13728           // declarator in the same group.
13729           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13730             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13731                  diag::err_auto_non_deduced_not_alone)
13732                 << FirstNonDeducedAutoInGroup->getType()
13733                        ->hasAutoForTrailingReturnType()
13734                 << FirstDeclaratorInGroup->getSourceRange()
13735                 << DD->getSourceRange();
13736             DiagnosedNonDeducedAuto = true;
13737           }
13738         }
13739       }
13740 
13741       Decls.push_back(D);
13742     }
13743   }
13744 
13745   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13746     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13747       handleTagNumbering(Tag, S);
13748       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13749           getLangOpts().CPlusPlus)
13750         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13751     }
13752   }
13753 
13754   return BuildDeclaratorGroup(Decls);
13755 }
13756 
13757 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13758 /// group, performing any necessary semantic checking.
13759 Sema::DeclGroupPtrTy
13760 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13761   // C++14 [dcl.spec.auto]p7: (DR1347)
13762   //   If the type that replaces the placeholder type is not the same in each
13763   //   deduction, the program is ill-formed.
13764   if (Group.size() > 1) {
13765     QualType Deduced;
13766     VarDecl *DeducedDecl = nullptr;
13767     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13768       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13769       if (!D || D->isInvalidDecl())
13770         break;
13771       DeducedType *DT = D->getType()->getContainedDeducedType();
13772       if (!DT || DT->getDeducedType().isNull())
13773         continue;
13774       if (Deduced.isNull()) {
13775         Deduced = DT->getDeducedType();
13776         DeducedDecl = D;
13777       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13778         auto *AT = dyn_cast<AutoType>(DT);
13779         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13780                         diag::err_auto_different_deductions)
13781                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13782                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13783                    << D->getDeclName();
13784         if (DeducedDecl->hasInit())
13785           Dia << DeducedDecl->getInit()->getSourceRange();
13786         if (D->getInit())
13787           Dia << D->getInit()->getSourceRange();
13788         D->setInvalidDecl();
13789         break;
13790       }
13791     }
13792   }
13793 
13794   ActOnDocumentableDecls(Group);
13795 
13796   return DeclGroupPtrTy::make(
13797       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13798 }
13799 
13800 void Sema::ActOnDocumentableDecl(Decl *D) {
13801   ActOnDocumentableDecls(D);
13802 }
13803 
13804 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13805   // Don't parse the comment if Doxygen diagnostics are ignored.
13806   if (Group.empty() || !Group[0])
13807     return;
13808 
13809   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13810                       Group[0]->getLocation()) &&
13811       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13812                       Group[0]->getLocation()))
13813     return;
13814 
13815   if (Group.size() >= 2) {
13816     // This is a decl group.  Normally it will contain only declarations
13817     // produced from declarator list.  But in case we have any definitions or
13818     // additional declaration references:
13819     //   'typedef struct S {} S;'
13820     //   'typedef struct S *S;'
13821     //   'struct S *pS;'
13822     // FinalizeDeclaratorGroup adds these as separate declarations.
13823     Decl *MaybeTagDecl = Group[0];
13824     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13825       Group = Group.slice(1);
13826     }
13827   }
13828 
13829   // FIMXE: We assume every Decl in the group is in the same file.
13830   // This is false when preprocessor constructs the group from decls in
13831   // different files (e. g. macros or #include).
13832   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13833 }
13834 
13835 /// Common checks for a parameter-declaration that should apply to both function
13836 /// parameters and non-type template parameters.
13837 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13838   // Check that there are no default arguments inside the type of this
13839   // parameter.
13840   if (getLangOpts().CPlusPlus)
13841     CheckExtraCXXDefaultArguments(D);
13842 
13843   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13844   if (D.getCXXScopeSpec().isSet()) {
13845     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13846       << D.getCXXScopeSpec().getRange();
13847   }
13848 
13849   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13850   // simple identifier except [...irrelevant cases...].
13851   switch (D.getName().getKind()) {
13852   case UnqualifiedIdKind::IK_Identifier:
13853     break;
13854 
13855   case UnqualifiedIdKind::IK_OperatorFunctionId:
13856   case UnqualifiedIdKind::IK_ConversionFunctionId:
13857   case UnqualifiedIdKind::IK_LiteralOperatorId:
13858   case UnqualifiedIdKind::IK_ConstructorName:
13859   case UnqualifiedIdKind::IK_DestructorName:
13860   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13861   case UnqualifiedIdKind::IK_DeductionGuideName:
13862     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13863       << GetNameForDeclarator(D).getName();
13864     break;
13865 
13866   case UnqualifiedIdKind::IK_TemplateId:
13867   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13868     // GetNameForDeclarator would not produce a useful name in this case.
13869     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13870     break;
13871   }
13872 }
13873 
13874 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13875 /// to introduce parameters into function prototype scope.
13876 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13877   const DeclSpec &DS = D.getDeclSpec();
13878 
13879   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13880 
13881   // C++03 [dcl.stc]p2 also permits 'auto'.
13882   StorageClass SC = SC_None;
13883   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13884     SC = SC_Register;
13885     // In C++11, the 'register' storage class specifier is deprecated.
13886     // In C++17, it is not allowed, but we tolerate it as an extension.
13887     if (getLangOpts().CPlusPlus11) {
13888       Diag(DS.getStorageClassSpecLoc(),
13889            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13890                                      : diag::warn_deprecated_register)
13891         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13892     }
13893   } else if (getLangOpts().CPlusPlus &&
13894              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13895     SC = SC_Auto;
13896   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13897     Diag(DS.getStorageClassSpecLoc(),
13898          diag::err_invalid_storage_class_in_func_decl);
13899     D.getMutableDeclSpec().ClearStorageClassSpecs();
13900   }
13901 
13902   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13903     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13904       << DeclSpec::getSpecifierName(TSCS);
13905   if (DS.isInlineSpecified())
13906     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13907         << getLangOpts().CPlusPlus17;
13908   if (DS.hasConstexprSpecifier())
13909     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13910         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13911 
13912   DiagnoseFunctionSpecifiers(DS);
13913 
13914   CheckFunctionOrTemplateParamDeclarator(S, D);
13915 
13916   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13917   QualType parmDeclType = TInfo->getType();
13918 
13919   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13920   IdentifierInfo *II = D.getIdentifier();
13921   if (II) {
13922     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13923                    ForVisibleRedeclaration);
13924     LookupName(R, S);
13925     if (R.isSingleResult()) {
13926       NamedDecl *PrevDecl = R.getFoundDecl();
13927       if (PrevDecl->isTemplateParameter()) {
13928         // Maybe we will complain about the shadowed template parameter.
13929         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13930         // Just pretend that we didn't see the previous declaration.
13931         PrevDecl = nullptr;
13932       } else if (S->isDeclScope(PrevDecl)) {
13933         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13934         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13935 
13936         // Recover by removing the name
13937         II = nullptr;
13938         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13939         D.setInvalidType(true);
13940       }
13941     }
13942   }
13943 
13944   // Temporarily put parameter variables in the translation unit, not
13945   // the enclosing context.  This prevents them from accidentally
13946   // looking like class members in C++.
13947   ParmVarDecl *New =
13948       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13949                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13950 
13951   if (D.isInvalidType())
13952     New->setInvalidDecl();
13953 
13954   assert(S->isFunctionPrototypeScope());
13955   assert(S->getFunctionPrototypeDepth() >= 1);
13956   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13957                     S->getNextFunctionPrototypeIndex());
13958 
13959   // Add the parameter declaration into this scope.
13960   S->AddDecl(New);
13961   if (II)
13962     IdResolver.AddDecl(New);
13963 
13964   ProcessDeclAttributes(S, New, D);
13965 
13966   if (D.getDeclSpec().isModulePrivateSpecified())
13967     Diag(New->getLocation(), diag::err_module_private_local)
13968         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13969         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13970 
13971   if (New->hasAttr<BlocksAttr>()) {
13972     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13973   }
13974 
13975   if (getLangOpts().OpenCL)
13976     deduceOpenCLAddressSpace(New);
13977 
13978   return New;
13979 }
13980 
13981 /// Synthesizes a variable for a parameter arising from a
13982 /// typedef.
13983 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13984                                               SourceLocation Loc,
13985                                               QualType T) {
13986   /* FIXME: setting StartLoc == Loc.
13987      Would it be worth to modify callers so as to provide proper source
13988      location for the unnamed parameters, embedding the parameter's type? */
13989   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13990                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13991                                            SC_None, nullptr);
13992   Param->setImplicit();
13993   return Param;
13994 }
13995 
13996 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13997   // Don't diagnose unused-parameter errors in template instantiations; we
13998   // will already have done so in the template itself.
13999   if (inTemplateInstantiation())
14000     return;
14001 
14002   for (const ParmVarDecl *Parameter : Parameters) {
14003     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14004         !Parameter->hasAttr<UnusedAttr>()) {
14005       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14006         << Parameter->getDeclName();
14007     }
14008   }
14009 }
14010 
14011 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14012     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14013   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14014     return;
14015 
14016   // Warn if the return value is pass-by-value and larger than the specified
14017   // threshold.
14018   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14019     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14020     if (Size > LangOpts.NumLargeByValueCopy)
14021       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14022   }
14023 
14024   // Warn if any parameter is pass-by-value and larger than the specified
14025   // threshold.
14026   for (const ParmVarDecl *Parameter : Parameters) {
14027     QualType T = Parameter->getType();
14028     if (T->isDependentType() || !T.isPODType(Context))
14029       continue;
14030     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14031     if (Size > LangOpts.NumLargeByValueCopy)
14032       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14033           << Parameter << Size;
14034   }
14035 }
14036 
14037 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14038                                   SourceLocation NameLoc, IdentifierInfo *Name,
14039                                   QualType T, TypeSourceInfo *TSInfo,
14040                                   StorageClass SC) {
14041   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14042   if (getLangOpts().ObjCAutoRefCount &&
14043       T.getObjCLifetime() == Qualifiers::OCL_None &&
14044       T->isObjCLifetimeType()) {
14045 
14046     Qualifiers::ObjCLifetime lifetime;
14047 
14048     // Special cases for arrays:
14049     //   - if it's const, use __unsafe_unretained
14050     //   - otherwise, it's an error
14051     if (T->isArrayType()) {
14052       if (!T.isConstQualified()) {
14053         if (DelayedDiagnostics.shouldDelayDiagnostics())
14054           DelayedDiagnostics.add(
14055               sema::DelayedDiagnostic::makeForbiddenType(
14056               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14057         else
14058           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14059               << TSInfo->getTypeLoc().getSourceRange();
14060       }
14061       lifetime = Qualifiers::OCL_ExplicitNone;
14062     } else {
14063       lifetime = T->getObjCARCImplicitLifetime();
14064     }
14065     T = Context.getLifetimeQualifiedType(T, lifetime);
14066   }
14067 
14068   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14069                                          Context.getAdjustedParameterType(T),
14070                                          TSInfo, SC, nullptr);
14071 
14072   // Make a note if we created a new pack in the scope of a lambda, so that
14073   // we know that references to that pack must also be expanded within the
14074   // lambda scope.
14075   if (New->isParameterPack())
14076     if (auto *LSI = getEnclosingLambda())
14077       LSI->LocalPacks.push_back(New);
14078 
14079   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14080       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14081     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14082                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14083 
14084   // Parameters can not be abstract class types.
14085   // For record types, this is done by the AbstractClassUsageDiagnoser once
14086   // the class has been completely parsed.
14087   if (!CurContext->isRecord() &&
14088       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14089                              AbstractParamType))
14090     New->setInvalidDecl();
14091 
14092   // Parameter declarators cannot be interface types. All ObjC objects are
14093   // passed by reference.
14094   if (T->isObjCObjectType()) {
14095     SourceLocation TypeEndLoc =
14096         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14097     Diag(NameLoc,
14098          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14099       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14100     T = Context.getObjCObjectPointerType(T);
14101     New->setType(T);
14102   }
14103 
14104   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14105   // duration shall not be qualified by an address-space qualifier."
14106   // Since all parameters have automatic store duration, they can not have
14107   // an address space.
14108   if (T.getAddressSpace() != LangAS::Default &&
14109       // OpenCL allows function arguments declared to be an array of a type
14110       // to be qualified with an address space.
14111       !(getLangOpts().OpenCL &&
14112         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14113     Diag(NameLoc, diag::err_arg_with_address_space);
14114     New->setInvalidDecl();
14115   }
14116 
14117   // PPC MMA non-pointer types are not allowed as function argument types.
14118   if (Context.getTargetInfo().getTriple().isPPC64() &&
14119       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14120     New->setInvalidDecl();
14121   }
14122 
14123   return New;
14124 }
14125 
14126 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14127                                            SourceLocation LocAfterDecls) {
14128   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14129 
14130   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14131   // for a K&R function.
14132   if (!FTI.hasPrototype) {
14133     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14134       --i;
14135       if (FTI.Params[i].Param == nullptr) {
14136         SmallString<256> Code;
14137         llvm::raw_svector_ostream(Code)
14138             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14139         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14140             << FTI.Params[i].Ident
14141             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14142 
14143         // Implicitly declare the argument as type 'int' for lack of a better
14144         // type.
14145         AttributeFactory attrs;
14146         DeclSpec DS(attrs);
14147         const char* PrevSpec; // unused
14148         unsigned DiagID; // unused
14149         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14150                            DiagID, Context.getPrintingPolicy());
14151         // Use the identifier location for the type source range.
14152         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14153         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14154         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14155         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14156         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14157       }
14158     }
14159   }
14160 }
14161 
14162 Decl *
14163 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14164                               MultiTemplateParamsArg TemplateParameterLists,
14165                               SkipBodyInfo *SkipBody) {
14166   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14167   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14168   Scope *ParentScope = FnBodyScope->getParent();
14169 
14170   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14171   // we define a non-templated function definition, we will create a declaration
14172   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14173   // The base function declaration will have the equivalent of an `omp declare
14174   // variant` annotation which specifies the mangled definition as a
14175   // specialization function under the OpenMP context defined as part of the
14176   // `omp begin declare variant`.
14177   SmallVector<FunctionDecl *, 4> Bases;
14178   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14179     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14180         ParentScope, D, TemplateParameterLists, Bases);
14181 
14182   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14183   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14184   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14185 
14186   if (!Bases.empty())
14187     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14188 
14189   return Dcl;
14190 }
14191 
14192 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14193   Consumer.HandleInlineFunctionDefinition(D);
14194 }
14195 
14196 static bool
14197 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14198                                 const FunctionDecl *&PossiblePrototype) {
14199   // Don't warn about invalid declarations.
14200   if (FD->isInvalidDecl())
14201     return false;
14202 
14203   // Or declarations that aren't global.
14204   if (!FD->isGlobal())
14205     return false;
14206 
14207   // Don't warn about C++ member functions.
14208   if (isa<CXXMethodDecl>(FD))
14209     return false;
14210 
14211   // Don't warn about 'main'.
14212   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14213     if (IdentifierInfo *II = FD->getIdentifier())
14214       if (II->isStr("main") || II->isStr("efi_main"))
14215         return false;
14216 
14217   // Don't warn about inline functions.
14218   if (FD->isInlined())
14219     return false;
14220 
14221   // Don't warn about function templates.
14222   if (FD->getDescribedFunctionTemplate())
14223     return false;
14224 
14225   // Don't warn about function template specializations.
14226   if (FD->isFunctionTemplateSpecialization())
14227     return false;
14228 
14229   // Don't warn for OpenCL kernels.
14230   if (FD->hasAttr<OpenCLKernelAttr>())
14231     return false;
14232 
14233   // Don't warn on explicitly deleted functions.
14234   if (FD->isDeleted())
14235     return false;
14236 
14237   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14238        Prev; Prev = Prev->getPreviousDecl()) {
14239     // Ignore any declarations that occur in function or method
14240     // scope, because they aren't visible from the header.
14241     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14242       continue;
14243 
14244     PossiblePrototype = Prev;
14245     return Prev->getType()->isFunctionNoProtoType();
14246   }
14247 
14248   return true;
14249 }
14250 
14251 void
14252 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14253                                    const FunctionDecl *EffectiveDefinition,
14254                                    SkipBodyInfo *SkipBody) {
14255   const FunctionDecl *Definition = EffectiveDefinition;
14256   if (!Definition &&
14257       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14258     return;
14259 
14260   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14261     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14262       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14263         // A merged copy of the same function, instantiated as a member of
14264         // the same class, is OK.
14265         if (declaresSameEntity(OrigFD, OrigDef) &&
14266             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14267                                cast<Decl>(FD->getLexicalDeclContext())))
14268           return;
14269       }
14270     }
14271   }
14272 
14273   if (canRedefineFunction(Definition, getLangOpts()))
14274     return;
14275 
14276   // Don't emit an error when this is redefinition of a typo-corrected
14277   // definition.
14278   if (TypoCorrectedFunctionDefinitions.count(Definition))
14279     return;
14280 
14281   // If we don't have a visible definition of the function, and it's inline or
14282   // a template, skip the new definition.
14283   if (SkipBody && !hasVisibleDefinition(Definition) &&
14284       (Definition->getFormalLinkage() == InternalLinkage ||
14285        Definition->isInlined() ||
14286        Definition->getDescribedFunctionTemplate() ||
14287        Definition->getNumTemplateParameterLists())) {
14288     SkipBody->ShouldSkip = true;
14289     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14290     if (auto *TD = Definition->getDescribedFunctionTemplate())
14291       makeMergedDefinitionVisible(TD);
14292     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14293     return;
14294   }
14295 
14296   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14297       Definition->getStorageClass() == SC_Extern)
14298     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14299         << FD << getLangOpts().CPlusPlus;
14300   else
14301     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14302 
14303   Diag(Definition->getLocation(), diag::note_previous_definition);
14304   FD->setInvalidDecl();
14305 }
14306 
14307 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14308                                    Sema &S) {
14309   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14310 
14311   LambdaScopeInfo *LSI = S.PushLambdaScope();
14312   LSI->CallOperator = CallOperator;
14313   LSI->Lambda = LambdaClass;
14314   LSI->ReturnType = CallOperator->getReturnType();
14315   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14316 
14317   if (LCD == LCD_None)
14318     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14319   else if (LCD == LCD_ByCopy)
14320     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14321   else if (LCD == LCD_ByRef)
14322     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14323   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14324 
14325   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14326   LSI->Mutable = !CallOperator->isConst();
14327 
14328   // Add the captures to the LSI so they can be noted as already
14329   // captured within tryCaptureVar.
14330   auto I = LambdaClass->field_begin();
14331   for (const auto &C : LambdaClass->captures()) {
14332     if (C.capturesVariable()) {
14333       VarDecl *VD = C.getCapturedVar();
14334       if (VD->isInitCapture())
14335         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14336       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14337       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14338           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14339           /*EllipsisLoc*/C.isPackExpansion()
14340                          ? C.getEllipsisLoc() : SourceLocation(),
14341           I->getType(), /*Invalid*/false);
14342 
14343     } else if (C.capturesThis()) {
14344       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14345                           C.getCaptureKind() == LCK_StarThis);
14346     } else {
14347       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14348                              I->getType());
14349     }
14350     ++I;
14351   }
14352 }
14353 
14354 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14355                                     SkipBodyInfo *SkipBody) {
14356   if (!D) {
14357     // Parsing the function declaration failed in some way. Push on a fake scope
14358     // anyway so we can try to parse the function body.
14359     PushFunctionScope();
14360     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14361     return D;
14362   }
14363 
14364   FunctionDecl *FD = nullptr;
14365 
14366   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14367     FD = FunTmpl->getTemplatedDecl();
14368   else
14369     FD = cast<FunctionDecl>(D);
14370 
14371   // Do not push if it is a lambda because one is already pushed when building
14372   // the lambda in ActOnStartOfLambdaDefinition().
14373   if (!isLambdaCallOperator(FD))
14374     PushExpressionEvaluationContext(
14375         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14376                           : ExprEvalContexts.back().Context);
14377 
14378   // Check for defining attributes before the check for redefinition.
14379   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14380     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14381     FD->dropAttr<AliasAttr>();
14382     FD->setInvalidDecl();
14383   }
14384   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14385     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14386     FD->dropAttr<IFuncAttr>();
14387     FD->setInvalidDecl();
14388   }
14389 
14390   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14391     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14392         Ctor->isDefaultConstructor() &&
14393         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14394       // If this is an MS ABI dllexport default constructor, instantiate any
14395       // default arguments.
14396       InstantiateDefaultCtorDefaultArgs(Ctor);
14397     }
14398   }
14399 
14400   // See if this is a redefinition. If 'will have body' (or similar) is already
14401   // set, then these checks were already performed when it was set.
14402   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14403       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14404     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14405 
14406     // If we're skipping the body, we're done. Don't enter the scope.
14407     if (SkipBody && SkipBody->ShouldSkip)
14408       return D;
14409   }
14410 
14411   // Mark this function as "will have a body eventually".  This lets users to
14412   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14413   // this function.
14414   FD->setWillHaveBody();
14415 
14416   // If we are instantiating a generic lambda call operator, push
14417   // a LambdaScopeInfo onto the function stack.  But use the information
14418   // that's already been calculated (ActOnLambdaExpr) to prime the current
14419   // LambdaScopeInfo.
14420   // When the template operator is being specialized, the LambdaScopeInfo,
14421   // has to be properly restored so that tryCaptureVariable doesn't try
14422   // and capture any new variables. In addition when calculating potential
14423   // captures during transformation of nested lambdas, it is necessary to
14424   // have the LSI properly restored.
14425   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14426     assert(inTemplateInstantiation() &&
14427            "There should be an active template instantiation on the stack "
14428            "when instantiating a generic lambda!");
14429     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14430   } else {
14431     // Enter a new function scope
14432     PushFunctionScope();
14433   }
14434 
14435   // Builtin functions cannot be defined.
14436   if (unsigned BuiltinID = FD->getBuiltinID()) {
14437     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14438         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14439       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14440       FD->setInvalidDecl();
14441     }
14442   }
14443 
14444   // The return type of a function definition must be complete
14445   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14446   QualType ResultType = FD->getReturnType();
14447   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14448       !FD->isInvalidDecl() &&
14449       RequireCompleteType(FD->getLocation(), ResultType,
14450                           diag::err_func_def_incomplete_result))
14451     FD->setInvalidDecl();
14452 
14453   if (FnBodyScope)
14454     PushDeclContext(FnBodyScope, FD);
14455 
14456   // Check the validity of our function parameters
14457   CheckParmsForFunctionDef(FD->parameters(),
14458                            /*CheckParameterNames=*/true);
14459 
14460   // Add non-parameter declarations already in the function to the current
14461   // scope.
14462   if (FnBodyScope) {
14463     for (Decl *NPD : FD->decls()) {
14464       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14465       if (!NonParmDecl)
14466         continue;
14467       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14468              "parameters should not be in newly created FD yet");
14469 
14470       // If the decl has a name, make it accessible in the current scope.
14471       if (NonParmDecl->getDeclName())
14472         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14473 
14474       // Similarly, dive into enums and fish their constants out, making them
14475       // accessible in this scope.
14476       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14477         for (auto *EI : ED->enumerators())
14478           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14479       }
14480     }
14481   }
14482 
14483   // Introduce our parameters into the function scope
14484   for (auto Param : FD->parameters()) {
14485     Param->setOwningFunction(FD);
14486 
14487     // If this has an identifier, add it to the scope stack.
14488     if (Param->getIdentifier() && FnBodyScope) {
14489       CheckShadow(FnBodyScope, Param);
14490 
14491       PushOnScopeChains(Param, FnBodyScope);
14492     }
14493   }
14494 
14495   // Ensure that the function's exception specification is instantiated.
14496   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14497     ResolveExceptionSpec(D->getLocation(), FPT);
14498 
14499   // dllimport cannot be applied to non-inline function definitions.
14500   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14501       !FD->isTemplateInstantiation()) {
14502     assert(!FD->hasAttr<DLLExportAttr>());
14503     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14504     FD->setInvalidDecl();
14505     return D;
14506   }
14507   // We want to attach documentation to original Decl (which might be
14508   // a function template).
14509   ActOnDocumentableDecl(D);
14510   if (getCurLexicalContext()->isObjCContainer() &&
14511       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14512       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14513     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14514 
14515   return D;
14516 }
14517 
14518 /// Given the set of return statements within a function body,
14519 /// compute the variables that are subject to the named return value
14520 /// optimization.
14521 ///
14522 /// Each of the variables that is subject to the named return value
14523 /// optimization will be marked as NRVO variables in the AST, and any
14524 /// return statement that has a marked NRVO variable as its NRVO candidate can
14525 /// use the named return value optimization.
14526 ///
14527 /// This function applies a very simplistic algorithm for NRVO: if every return
14528 /// statement in the scope of a variable has the same NRVO candidate, that
14529 /// candidate is an NRVO variable.
14530 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14531   ReturnStmt **Returns = Scope->Returns.data();
14532 
14533   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14534     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14535       if (!NRVOCandidate->isNRVOVariable())
14536         Returns[I]->setNRVOCandidate(nullptr);
14537     }
14538   }
14539 }
14540 
14541 bool Sema::canDelayFunctionBody(const Declarator &D) {
14542   // We can't delay parsing the body of a constexpr function template (yet).
14543   if (D.getDeclSpec().hasConstexprSpecifier())
14544     return false;
14545 
14546   // We can't delay parsing the body of a function template with a deduced
14547   // return type (yet).
14548   if (D.getDeclSpec().hasAutoTypeSpec()) {
14549     // If the placeholder introduces a non-deduced trailing return type,
14550     // we can still delay parsing it.
14551     if (D.getNumTypeObjects()) {
14552       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14553       if (Outer.Kind == DeclaratorChunk::Function &&
14554           Outer.Fun.hasTrailingReturnType()) {
14555         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14556         return Ty.isNull() || !Ty->isUndeducedType();
14557       }
14558     }
14559     return false;
14560   }
14561 
14562   return true;
14563 }
14564 
14565 bool Sema::canSkipFunctionBody(Decl *D) {
14566   // We cannot skip the body of a function (or function template) which is
14567   // constexpr, since we may need to evaluate its body in order to parse the
14568   // rest of the file.
14569   // We cannot skip the body of a function with an undeduced return type,
14570   // because any callers of that function need to know the type.
14571   if (const FunctionDecl *FD = D->getAsFunction()) {
14572     if (FD->isConstexpr())
14573       return false;
14574     // We can't simply call Type::isUndeducedType here, because inside template
14575     // auto can be deduced to a dependent type, which is not considered
14576     // "undeduced".
14577     if (FD->getReturnType()->getContainedDeducedType())
14578       return false;
14579   }
14580   return Consumer.shouldSkipFunctionBody(D);
14581 }
14582 
14583 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14584   if (!Decl)
14585     return nullptr;
14586   if (FunctionDecl *FD = Decl->getAsFunction())
14587     FD->setHasSkippedBody();
14588   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14589     MD->setHasSkippedBody();
14590   return Decl;
14591 }
14592 
14593 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14594   return ActOnFinishFunctionBody(D, BodyArg, false);
14595 }
14596 
14597 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14598 /// body.
14599 class ExitFunctionBodyRAII {
14600 public:
14601   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14602   ~ExitFunctionBodyRAII() {
14603     if (!IsLambda)
14604       S.PopExpressionEvaluationContext();
14605   }
14606 
14607 private:
14608   Sema &S;
14609   bool IsLambda = false;
14610 };
14611 
14612 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14613   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14614 
14615   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14616     if (EscapeInfo.count(BD))
14617       return EscapeInfo[BD];
14618 
14619     bool R = false;
14620     const BlockDecl *CurBD = BD;
14621 
14622     do {
14623       R = !CurBD->doesNotEscape();
14624       if (R)
14625         break;
14626       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14627     } while (CurBD);
14628 
14629     return EscapeInfo[BD] = R;
14630   };
14631 
14632   // If the location where 'self' is implicitly retained is inside a escaping
14633   // block, emit a diagnostic.
14634   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14635        S.ImplicitlyRetainedSelfLocs)
14636     if (IsOrNestedInEscapingBlock(P.second))
14637       S.Diag(P.first, diag::warn_implicitly_retains_self)
14638           << FixItHint::CreateInsertion(P.first, "self->");
14639 }
14640 
14641 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14642                                     bool IsInstantiation) {
14643   FunctionScopeInfo *FSI = getCurFunction();
14644   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14645 
14646   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14647     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14648 
14649   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14650   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14651 
14652   if (getLangOpts().Coroutines && FSI->isCoroutine())
14653     CheckCompletedCoroutineBody(FD, Body);
14654 
14655   {
14656     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14657     // one is already popped when finishing the lambda in BuildLambdaExpr().
14658     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14659     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14660 
14661     if (FD) {
14662       FD->setBody(Body);
14663       FD->setWillHaveBody(false);
14664 
14665       if (getLangOpts().CPlusPlus14) {
14666         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14667             FD->getReturnType()->isUndeducedType()) {
14668           // For a function with a deduced result type to return void,
14669           // the result type as written must be 'auto' or 'decltype(auto)',
14670           // possibly cv-qualified or constrained, but not ref-qualified.
14671           if (!FD->getReturnType()->getAs<AutoType>()) {
14672             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14673                 << FD->getReturnType();
14674             FD->setInvalidDecl();
14675           } else {
14676             // Falling off the end of the function is the same as 'return;'.
14677             Expr *Dummy = nullptr;
14678             if (DeduceFunctionTypeFromReturnExpr(
14679                     FD, dcl->getLocation(), Dummy,
14680                     FD->getReturnType()->getAs<AutoType>()))
14681               FD->setInvalidDecl();
14682           }
14683         }
14684       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14685         // In C++11, we don't use 'auto' deduction rules for lambda call
14686         // operators because we don't support return type deduction.
14687         auto *LSI = getCurLambda();
14688         if (LSI->HasImplicitReturnType) {
14689           deduceClosureReturnType(*LSI);
14690 
14691           // C++11 [expr.prim.lambda]p4:
14692           //   [...] if there are no return statements in the compound-statement
14693           //   [the deduced type is] the type void
14694           QualType RetType =
14695               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14696 
14697           // Update the return type to the deduced type.
14698           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14699           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14700                                               Proto->getExtProtoInfo()));
14701         }
14702       }
14703 
14704       // If the function implicitly returns zero (like 'main') or is naked,
14705       // don't complain about missing return statements.
14706       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14707         WP.disableCheckFallThrough();
14708 
14709       // MSVC permits the use of pure specifier (=0) on function definition,
14710       // defined at class scope, warn about this non-standard construct.
14711       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14712         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14713 
14714       if (!FD->isInvalidDecl()) {
14715         // Don't diagnose unused parameters of defaulted, deleted or naked
14716         // functions.
14717         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14718             !FD->hasAttr<NakedAttr>())
14719           DiagnoseUnusedParameters(FD->parameters());
14720         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14721                                                FD->getReturnType(), FD);
14722 
14723         // If this is a structor, we need a vtable.
14724         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14725           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14726         else if (CXXDestructorDecl *Destructor =
14727                      dyn_cast<CXXDestructorDecl>(FD))
14728           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14729 
14730         // Try to apply the named return value optimization. We have to check
14731         // if we can do this here because lambdas keep return statements around
14732         // to deduce an implicit return type.
14733         if (FD->getReturnType()->isRecordType() &&
14734             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14735           computeNRVO(Body, FSI);
14736       }
14737 
14738       // GNU warning -Wmissing-prototypes:
14739       //   Warn if a global function is defined without a previous
14740       //   prototype declaration. This warning is issued even if the
14741       //   definition itself provides a prototype. The aim is to detect
14742       //   global functions that fail to be declared in header files.
14743       const FunctionDecl *PossiblePrototype = nullptr;
14744       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14745         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14746 
14747         if (PossiblePrototype) {
14748           // We found a declaration that is not a prototype,
14749           // but that could be a zero-parameter prototype
14750           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14751             TypeLoc TL = TI->getTypeLoc();
14752             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14753               Diag(PossiblePrototype->getLocation(),
14754                    diag::note_declaration_not_a_prototype)
14755                   << (FD->getNumParams() != 0)
14756                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14757                                                     FTL.getRParenLoc(), "void")
14758                                               : FixItHint{});
14759           }
14760         } else {
14761           // Returns true if the token beginning at this Loc is `const`.
14762           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14763                                   const LangOptions &LangOpts) {
14764             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14765             if (LocInfo.first.isInvalid())
14766               return false;
14767 
14768             bool Invalid = false;
14769             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14770             if (Invalid)
14771               return false;
14772 
14773             if (LocInfo.second > Buffer.size())
14774               return false;
14775 
14776             const char *LexStart = Buffer.data() + LocInfo.second;
14777             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14778 
14779             return StartTok.consume_front("const") &&
14780                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14781                     StartTok.startswith("/*") || StartTok.startswith("//"));
14782           };
14783 
14784           auto findBeginLoc = [&]() {
14785             // If the return type has `const` qualifier, we want to insert
14786             // `static` before `const` (and not before the typename).
14787             if ((FD->getReturnType()->isAnyPointerType() &&
14788                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14789                 FD->getReturnType().isConstQualified()) {
14790               // But only do this if we can determine where the `const` is.
14791 
14792               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14793                                getLangOpts()))
14794 
14795                 return FD->getBeginLoc();
14796             }
14797             return FD->getTypeSpecStartLoc();
14798           };
14799           Diag(FD->getTypeSpecStartLoc(),
14800                diag::note_static_for_internal_linkage)
14801               << /* function */ 1
14802               << (FD->getStorageClass() == SC_None
14803                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14804                       : FixItHint{});
14805         }
14806 
14807         // GNU warning -Wstrict-prototypes
14808         //   Warn if K&R function is defined without a previous declaration.
14809         //   This warning is issued only if the definition itself does not
14810         //   provide a prototype. Only K&R definitions do not provide a
14811         //   prototype.
14812         if (!FD->hasWrittenPrototype()) {
14813           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14814           TypeLoc TL = TI->getTypeLoc();
14815           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14816           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14817         }
14818       }
14819 
14820       // Warn on CPUDispatch with an actual body.
14821       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14822         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14823           if (!CmpndBody->body_empty())
14824             Diag(CmpndBody->body_front()->getBeginLoc(),
14825                  diag::warn_dispatch_body_ignored);
14826 
14827       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14828         const CXXMethodDecl *KeyFunction;
14829         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14830             MD->isVirtual() &&
14831             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14832             MD == KeyFunction->getCanonicalDecl()) {
14833           // Update the key-function state if necessary for this ABI.
14834           if (FD->isInlined() &&
14835               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14836             Context.setNonKeyFunction(MD);
14837 
14838             // If the newly-chosen key function is already defined, then we
14839             // need to mark the vtable as used retroactively.
14840             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14841             const FunctionDecl *Definition;
14842             if (KeyFunction && KeyFunction->isDefined(Definition))
14843               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14844           } else {
14845             // We just defined they key function; mark the vtable as used.
14846             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14847           }
14848         }
14849       }
14850 
14851       assert(
14852           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14853           "Function parsing confused");
14854     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14855       assert(MD == getCurMethodDecl() && "Method parsing confused");
14856       MD->setBody(Body);
14857       if (!MD->isInvalidDecl()) {
14858         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14859                                                MD->getReturnType(), MD);
14860 
14861         if (Body)
14862           computeNRVO(Body, FSI);
14863       }
14864       if (FSI->ObjCShouldCallSuper) {
14865         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14866             << MD->getSelector().getAsString();
14867         FSI->ObjCShouldCallSuper = false;
14868       }
14869       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14870         const ObjCMethodDecl *InitMethod = nullptr;
14871         bool isDesignated =
14872             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14873         assert(isDesignated && InitMethod);
14874         (void)isDesignated;
14875 
14876         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14877           auto IFace = MD->getClassInterface();
14878           if (!IFace)
14879             return false;
14880           auto SuperD = IFace->getSuperClass();
14881           if (!SuperD)
14882             return false;
14883           return SuperD->getIdentifier() ==
14884                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14885         };
14886         // Don't issue this warning for unavailable inits or direct subclasses
14887         // of NSObject.
14888         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14889           Diag(MD->getLocation(),
14890                diag::warn_objc_designated_init_missing_super_call);
14891           Diag(InitMethod->getLocation(),
14892                diag::note_objc_designated_init_marked_here);
14893         }
14894         FSI->ObjCWarnForNoDesignatedInitChain = false;
14895       }
14896       if (FSI->ObjCWarnForNoInitDelegation) {
14897         // Don't issue this warning for unavaialable inits.
14898         if (!MD->isUnavailable())
14899           Diag(MD->getLocation(),
14900                diag::warn_objc_secondary_init_missing_init_call);
14901         FSI->ObjCWarnForNoInitDelegation = false;
14902       }
14903 
14904       diagnoseImplicitlyRetainedSelf(*this);
14905     } else {
14906       // Parsing the function declaration failed in some way. Pop the fake scope
14907       // we pushed on.
14908       PopFunctionScopeInfo(ActivePolicy, dcl);
14909       return nullptr;
14910     }
14911 
14912     if (Body && FSI->HasPotentialAvailabilityViolations)
14913       DiagnoseUnguardedAvailabilityViolations(dcl);
14914 
14915     assert(!FSI->ObjCShouldCallSuper &&
14916            "This should only be set for ObjC methods, which should have been "
14917            "handled in the block above.");
14918 
14919     // Verify and clean out per-function state.
14920     if (Body && (!FD || !FD->isDefaulted())) {
14921       // C++ constructors that have function-try-blocks can't have return
14922       // statements in the handlers of that block. (C++ [except.handle]p14)
14923       // Verify this.
14924       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14925         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14926 
14927       // Verify that gotos and switch cases don't jump into scopes illegally.
14928       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14929         DiagnoseInvalidJumps(Body);
14930 
14931       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14932         if (!Destructor->getParent()->isDependentType())
14933           CheckDestructor(Destructor);
14934 
14935         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14936                                                Destructor->getParent());
14937       }
14938 
14939       // If any errors have occurred, clear out any temporaries that may have
14940       // been leftover. This ensures that these temporaries won't be picked up
14941       // for deletion in some later function.
14942       if (hasUncompilableErrorOccurred() ||
14943           getDiagnostics().getSuppressAllDiagnostics()) {
14944         DiscardCleanupsInEvaluationContext();
14945       }
14946       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14947         // Since the body is valid, issue any analysis-based warnings that are
14948         // enabled.
14949         ActivePolicy = &WP;
14950       }
14951 
14952       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14953           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14954         FD->setInvalidDecl();
14955 
14956       if (FD && FD->hasAttr<NakedAttr>()) {
14957         for (const Stmt *S : Body->children()) {
14958           // Allow local register variables without initializer as they don't
14959           // require prologue.
14960           bool RegisterVariables = false;
14961           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14962             for (const auto *Decl : DS->decls()) {
14963               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14964                 RegisterVariables =
14965                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14966                 if (!RegisterVariables)
14967                   break;
14968               }
14969             }
14970           }
14971           if (RegisterVariables)
14972             continue;
14973           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14974             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14975             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14976             FD->setInvalidDecl();
14977             break;
14978           }
14979         }
14980       }
14981 
14982       assert(ExprCleanupObjects.size() ==
14983                  ExprEvalContexts.back().NumCleanupObjects &&
14984              "Leftover temporaries in function");
14985       assert(!Cleanup.exprNeedsCleanups() &&
14986              "Unaccounted cleanups in function");
14987       assert(MaybeODRUseExprs.empty() &&
14988              "Leftover expressions for odr-use checking");
14989     }
14990   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14991     // the declaration context below. Otherwise, we're unable to transform
14992     // 'this' expressions when transforming immediate context functions.
14993 
14994   if (!IsInstantiation)
14995     PopDeclContext();
14996 
14997   PopFunctionScopeInfo(ActivePolicy, dcl);
14998   // If any errors have occurred, clear out any temporaries that may have
14999   // been leftover. This ensures that these temporaries won't be picked up for
15000   // deletion in some later function.
15001   if (hasUncompilableErrorOccurred()) {
15002     DiscardCleanupsInEvaluationContext();
15003   }
15004 
15005   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15006                                   !LangOpts.OMPTargetTriples.empty())) ||
15007              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15008     auto ES = getEmissionStatus(FD);
15009     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15010         ES == Sema::FunctionEmissionStatus::Unknown)
15011       DeclsToCheckForDeferredDiags.insert(FD);
15012   }
15013 
15014   if (FD && !FD->isDeleted())
15015     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15016 
15017   return dcl;
15018 }
15019 
15020 /// When we finish delayed parsing of an attribute, we must attach it to the
15021 /// relevant Decl.
15022 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15023                                        ParsedAttributes &Attrs) {
15024   // Always attach attributes to the underlying decl.
15025   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15026     D = TD->getTemplatedDecl();
15027   ProcessDeclAttributeList(S, D, Attrs);
15028 
15029   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15030     if (Method->isStatic())
15031       checkThisInStaticMemberFunctionAttributes(Method);
15032 }
15033 
15034 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15035 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15036 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15037                                           IdentifierInfo &II, Scope *S) {
15038   // Find the scope in which the identifier is injected and the corresponding
15039   // DeclContext.
15040   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15041   // In that case, we inject the declaration into the translation unit scope
15042   // instead.
15043   Scope *BlockScope = S;
15044   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15045     BlockScope = BlockScope->getParent();
15046 
15047   Scope *ContextScope = BlockScope;
15048   while (!ContextScope->getEntity())
15049     ContextScope = ContextScope->getParent();
15050   ContextRAII SavedContext(*this, ContextScope->getEntity());
15051 
15052   // Before we produce a declaration for an implicitly defined
15053   // function, see whether there was a locally-scoped declaration of
15054   // this name as a function or variable. If so, use that
15055   // (non-visible) declaration, and complain about it.
15056   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15057   if (ExternCPrev) {
15058     // We still need to inject the function into the enclosing block scope so
15059     // that later (non-call) uses can see it.
15060     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15061 
15062     // C89 footnote 38:
15063     //   If in fact it is not defined as having type "function returning int",
15064     //   the behavior is undefined.
15065     if (!isa<FunctionDecl>(ExternCPrev) ||
15066         !Context.typesAreCompatible(
15067             cast<FunctionDecl>(ExternCPrev)->getType(),
15068             Context.getFunctionNoProtoType(Context.IntTy))) {
15069       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15070           << ExternCPrev << !getLangOpts().C99;
15071       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15072       return ExternCPrev;
15073     }
15074   }
15075 
15076   // Extension in C99.  Legal in C90, but warn about it.
15077   unsigned diag_id;
15078   if (II.getName().startswith("__builtin_"))
15079     diag_id = diag::warn_builtin_unknown;
15080   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15081   else if (getLangOpts().OpenCL)
15082     diag_id = diag::err_opencl_implicit_function_decl;
15083   else if (getLangOpts().C99)
15084     diag_id = diag::ext_implicit_function_decl;
15085   else
15086     diag_id = diag::warn_implicit_function_decl;
15087 
15088   TypoCorrection Corrected;
15089   // Because typo correction is expensive, only do it if the implicit
15090   // function declaration is going to be treated as an error.
15091   //
15092   // Perform the corection before issuing the main diagnostic, as some consumers
15093   // use typo-correction callbacks to enhance the main diagnostic.
15094   if (S && !ExternCPrev &&
15095       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15096     DeclFilterCCC<FunctionDecl> CCC{};
15097     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15098                             S, nullptr, CCC, CTK_NonError);
15099   }
15100 
15101   Diag(Loc, diag_id) << &II;
15102   if (Corrected)
15103     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15104                  /*ErrorRecovery*/ false);
15105 
15106   // If we found a prior declaration of this function, don't bother building
15107   // another one. We've already pushed that one into scope, so there's nothing
15108   // more to do.
15109   if (ExternCPrev)
15110     return ExternCPrev;
15111 
15112   // Set a Declarator for the implicit definition: int foo();
15113   const char *Dummy;
15114   AttributeFactory attrFactory;
15115   DeclSpec DS(attrFactory);
15116   unsigned DiagID;
15117   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15118                                   Context.getPrintingPolicy());
15119   (void)Error; // Silence warning.
15120   assert(!Error && "Error setting up implicit decl!");
15121   SourceLocation NoLoc;
15122   Declarator D(DS, DeclaratorContext::Block);
15123   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15124                                              /*IsAmbiguous=*/false,
15125                                              /*LParenLoc=*/NoLoc,
15126                                              /*Params=*/nullptr,
15127                                              /*NumParams=*/0,
15128                                              /*EllipsisLoc=*/NoLoc,
15129                                              /*RParenLoc=*/NoLoc,
15130                                              /*RefQualifierIsLvalueRef=*/true,
15131                                              /*RefQualifierLoc=*/NoLoc,
15132                                              /*MutableLoc=*/NoLoc, EST_None,
15133                                              /*ESpecRange=*/SourceRange(),
15134                                              /*Exceptions=*/nullptr,
15135                                              /*ExceptionRanges=*/nullptr,
15136                                              /*NumExceptions=*/0,
15137                                              /*NoexceptExpr=*/nullptr,
15138                                              /*ExceptionSpecTokens=*/nullptr,
15139                                              /*DeclsInPrototype=*/None, Loc,
15140                                              Loc, D),
15141                 std::move(DS.getAttributes()), SourceLocation());
15142   D.SetIdentifier(&II, Loc);
15143 
15144   // Insert this function into the enclosing block scope.
15145   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15146   FD->setImplicit();
15147 
15148   AddKnownFunctionAttributes(FD);
15149 
15150   return FD;
15151 }
15152 
15153 /// If this function is a C++ replaceable global allocation function
15154 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15155 /// adds any function attributes that we know a priori based on the standard.
15156 ///
15157 /// We need to check for duplicate attributes both here and where user-written
15158 /// attributes are applied to declarations.
15159 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15160     FunctionDecl *FD) {
15161   if (FD->isInvalidDecl())
15162     return;
15163 
15164   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15165       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15166     return;
15167 
15168   Optional<unsigned> AlignmentParam;
15169   bool IsNothrow = false;
15170   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15171     return;
15172 
15173   // C++2a [basic.stc.dynamic.allocation]p4:
15174   //   An allocation function that has a non-throwing exception specification
15175   //   indicates failure by returning a null pointer value. Any other allocation
15176   //   function never returns a null pointer value and indicates failure only by
15177   //   throwing an exception [...]
15178   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15179     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15180 
15181   // C++2a [basic.stc.dynamic.allocation]p2:
15182   //   An allocation function attempts to allocate the requested amount of
15183   //   storage. [...] If the request succeeds, the value returned by a
15184   //   replaceable allocation function is a [...] pointer value p0 different
15185   //   from any previously returned value p1 [...]
15186   //
15187   // However, this particular information is being added in codegen,
15188   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15189 
15190   // C++2a [basic.stc.dynamic.allocation]p2:
15191   //   An allocation function attempts to allocate the requested amount of
15192   //   storage. If it is successful, it returns the address of the start of a
15193   //   block of storage whose length in bytes is at least as large as the
15194   //   requested size.
15195   if (!FD->hasAttr<AllocSizeAttr>()) {
15196     FD->addAttr(AllocSizeAttr::CreateImplicit(
15197         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15198         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15199   }
15200 
15201   // C++2a [basic.stc.dynamic.allocation]p3:
15202   //   For an allocation function [...], the pointer returned on a successful
15203   //   call shall represent the address of storage that is aligned as follows:
15204   //   (3.1) If the allocation function takes an argument of type
15205   //         std​::​align_­val_­t, the storage will have the alignment
15206   //         specified by the value of this argument.
15207   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15208     FD->addAttr(AllocAlignAttr::CreateImplicit(
15209         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15210   }
15211 
15212   // FIXME:
15213   // C++2a [basic.stc.dynamic.allocation]p3:
15214   //   For an allocation function [...], the pointer returned on a successful
15215   //   call shall represent the address of storage that is aligned as follows:
15216   //   (3.2) Otherwise, if the allocation function is named operator new[],
15217   //         the storage is aligned for any object that does not have
15218   //         new-extended alignment ([basic.align]) and is no larger than the
15219   //         requested size.
15220   //   (3.3) Otherwise, the storage is aligned for any object that does not
15221   //         have new-extended alignment and is of the requested size.
15222 }
15223 
15224 /// Adds any function attributes that we know a priori based on
15225 /// the declaration of this function.
15226 ///
15227 /// These attributes can apply both to implicitly-declared builtins
15228 /// (like __builtin___printf_chk) or to library-declared functions
15229 /// like NSLog or printf.
15230 ///
15231 /// We need to check for duplicate attributes both here and where user-written
15232 /// attributes are applied to declarations.
15233 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15234   if (FD->isInvalidDecl())
15235     return;
15236 
15237   // If this is a built-in function, map its builtin attributes to
15238   // actual attributes.
15239   if (unsigned BuiltinID = FD->getBuiltinID()) {
15240     // Handle printf-formatting attributes.
15241     unsigned FormatIdx;
15242     bool HasVAListArg;
15243     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15244       if (!FD->hasAttr<FormatAttr>()) {
15245         const char *fmt = "printf";
15246         unsigned int NumParams = FD->getNumParams();
15247         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15248             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15249           fmt = "NSString";
15250         FD->addAttr(FormatAttr::CreateImplicit(Context,
15251                                                &Context.Idents.get(fmt),
15252                                                FormatIdx+1,
15253                                                HasVAListArg ? 0 : FormatIdx+2,
15254                                                FD->getLocation()));
15255       }
15256     }
15257     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15258                                              HasVAListArg)) {
15259      if (!FD->hasAttr<FormatAttr>())
15260        FD->addAttr(FormatAttr::CreateImplicit(Context,
15261                                               &Context.Idents.get("scanf"),
15262                                               FormatIdx+1,
15263                                               HasVAListArg ? 0 : FormatIdx+2,
15264                                               FD->getLocation()));
15265     }
15266 
15267     // Handle automatically recognized callbacks.
15268     SmallVector<int, 4> Encoding;
15269     if (!FD->hasAttr<CallbackAttr>() &&
15270         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15271       FD->addAttr(CallbackAttr::CreateImplicit(
15272           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15273 
15274     // Mark const if we don't care about errno and that is the only thing
15275     // preventing the function from being const. This allows IRgen to use LLVM
15276     // intrinsics for such functions.
15277     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15278         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15279       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15280 
15281     // We make "fma" on GNU or Windows const because we know it does not set
15282     // errno in those environments even though it could set errno based on the
15283     // C standard.
15284     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15285     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15286         !FD->hasAttr<ConstAttr>()) {
15287       switch (BuiltinID) {
15288       case Builtin::BI__builtin_fma:
15289       case Builtin::BI__builtin_fmaf:
15290       case Builtin::BI__builtin_fmal:
15291       case Builtin::BIfma:
15292       case Builtin::BIfmaf:
15293       case Builtin::BIfmal:
15294         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15295         break;
15296       default:
15297         break;
15298       }
15299     }
15300 
15301     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15302         !FD->hasAttr<ReturnsTwiceAttr>())
15303       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15304                                          FD->getLocation()));
15305     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15306       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15307     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15308       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15309     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15310       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15311     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15312         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15313       // Add the appropriate attribute, depending on the CUDA compilation mode
15314       // and which target the builtin belongs to. For example, during host
15315       // compilation, aux builtins are __device__, while the rest are __host__.
15316       if (getLangOpts().CUDAIsDevice !=
15317           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15318         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15319       else
15320         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15321     }
15322 
15323     // Add known guaranteed alignment for allocation functions.
15324     switch (BuiltinID) {
15325     case Builtin::BImemalign:
15326     case Builtin::BIaligned_alloc:
15327       if (!FD->hasAttr<AllocAlignAttr>())
15328         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15329                                                    FD->getLocation()));
15330       break;
15331     default:
15332       break;
15333     }
15334 
15335     // Add allocsize attribute for allocation functions.
15336     switch (BuiltinID) {
15337     case Builtin::BIcalloc:
15338       FD->addAttr(AllocSizeAttr::CreateImplicit(
15339           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15340       break;
15341     case Builtin::BImemalign:
15342     case Builtin::BIaligned_alloc:
15343     case Builtin::BIrealloc:
15344       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15345                                                 ParamIdx(), FD->getLocation()));
15346       break;
15347     case Builtin::BImalloc:
15348       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15349                                                 ParamIdx(), FD->getLocation()));
15350       break;
15351     default:
15352       break;
15353     }
15354   }
15355 
15356   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15357 
15358   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15359   // throw, add an implicit nothrow attribute to any extern "C" function we come
15360   // across.
15361   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15362       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15363     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15364     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15365       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15366   }
15367 
15368   IdentifierInfo *Name = FD->getIdentifier();
15369   if (!Name)
15370     return;
15371   if ((!getLangOpts().CPlusPlus &&
15372        FD->getDeclContext()->isTranslationUnit()) ||
15373       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15374        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15375        LinkageSpecDecl::lang_c)) {
15376     // Okay: this could be a libc/libm/Objective-C function we know
15377     // about.
15378   } else
15379     return;
15380 
15381   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15382     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15383     // target-specific builtins, perhaps?
15384     if (!FD->hasAttr<FormatAttr>())
15385       FD->addAttr(FormatAttr::CreateImplicit(Context,
15386                                              &Context.Idents.get("printf"), 2,
15387                                              Name->isStr("vasprintf") ? 0 : 3,
15388                                              FD->getLocation()));
15389   }
15390 
15391   if (Name->isStr("__CFStringMakeConstantString")) {
15392     // We already have a __builtin___CFStringMakeConstantString,
15393     // but builds that use -fno-constant-cfstrings don't go through that.
15394     if (!FD->hasAttr<FormatArgAttr>())
15395       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15396                                                 FD->getLocation()));
15397   }
15398 }
15399 
15400 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15401                                     TypeSourceInfo *TInfo) {
15402   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15403   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15404 
15405   if (!TInfo) {
15406     assert(D.isInvalidType() && "no declarator info for valid type");
15407     TInfo = Context.getTrivialTypeSourceInfo(T);
15408   }
15409 
15410   // Scope manipulation handled by caller.
15411   TypedefDecl *NewTD =
15412       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15413                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15414 
15415   // Bail out immediately if we have an invalid declaration.
15416   if (D.isInvalidType()) {
15417     NewTD->setInvalidDecl();
15418     return NewTD;
15419   }
15420 
15421   if (D.getDeclSpec().isModulePrivateSpecified()) {
15422     if (CurContext->isFunctionOrMethod())
15423       Diag(NewTD->getLocation(), diag::err_module_private_local)
15424           << 2 << NewTD
15425           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15426           << FixItHint::CreateRemoval(
15427                  D.getDeclSpec().getModulePrivateSpecLoc());
15428     else
15429       NewTD->setModulePrivate();
15430   }
15431 
15432   // C++ [dcl.typedef]p8:
15433   //   If the typedef declaration defines an unnamed class (or
15434   //   enum), the first typedef-name declared by the declaration
15435   //   to be that class type (or enum type) is used to denote the
15436   //   class type (or enum type) for linkage purposes only.
15437   // We need to check whether the type was declared in the declaration.
15438   switch (D.getDeclSpec().getTypeSpecType()) {
15439   case TST_enum:
15440   case TST_struct:
15441   case TST_interface:
15442   case TST_union:
15443   case TST_class: {
15444     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15445     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15446     break;
15447   }
15448 
15449   default:
15450     break;
15451   }
15452 
15453   return NewTD;
15454 }
15455 
15456 /// Check that this is a valid underlying type for an enum declaration.
15457 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15458   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15459   QualType T = TI->getType();
15460 
15461   if (T->isDependentType())
15462     return false;
15463 
15464   // This doesn't use 'isIntegralType' despite the error message mentioning
15465   // integral type because isIntegralType would also allow enum types in C.
15466   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15467     if (BT->isInteger())
15468       return false;
15469 
15470   if (T->isBitIntType())
15471     return false;
15472 
15473   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15474 }
15475 
15476 /// Check whether this is a valid redeclaration of a previous enumeration.
15477 /// \return true if the redeclaration was invalid.
15478 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15479                                   QualType EnumUnderlyingTy, bool IsFixed,
15480                                   const EnumDecl *Prev) {
15481   if (IsScoped != Prev->isScoped()) {
15482     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15483       << Prev->isScoped();
15484     Diag(Prev->getLocation(), diag::note_previous_declaration);
15485     return true;
15486   }
15487 
15488   if (IsFixed && Prev->isFixed()) {
15489     if (!EnumUnderlyingTy->isDependentType() &&
15490         !Prev->getIntegerType()->isDependentType() &&
15491         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15492                                         Prev->getIntegerType())) {
15493       // TODO: Highlight the underlying type of the redeclaration.
15494       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15495         << EnumUnderlyingTy << Prev->getIntegerType();
15496       Diag(Prev->getLocation(), diag::note_previous_declaration)
15497           << Prev->getIntegerTypeRange();
15498       return true;
15499     }
15500   } else if (IsFixed != Prev->isFixed()) {
15501     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15502       << Prev->isFixed();
15503     Diag(Prev->getLocation(), diag::note_previous_declaration);
15504     return true;
15505   }
15506 
15507   return false;
15508 }
15509 
15510 /// Get diagnostic %select index for tag kind for
15511 /// redeclaration diagnostic message.
15512 /// WARNING: Indexes apply to particular diagnostics only!
15513 ///
15514 /// \returns diagnostic %select index.
15515 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15516   switch (Tag) {
15517   case TTK_Struct: return 0;
15518   case TTK_Interface: return 1;
15519   case TTK_Class:  return 2;
15520   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15521   }
15522 }
15523 
15524 /// Determine if tag kind is a class-key compatible with
15525 /// class for redeclaration (class, struct, or __interface).
15526 ///
15527 /// \returns true iff the tag kind is compatible.
15528 static bool isClassCompatTagKind(TagTypeKind Tag)
15529 {
15530   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15531 }
15532 
15533 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15534                                              TagTypeKind TTK) {
15535   if (isa<TypedefDecl>(PrevDecl))
15536     return NTK_Typedef;
15537   else if (isa<TypeAliasDecl>(PrevDecl))
15538     return NTK_TypeAlias;
15539   else if (isa<ClassTemplateDecl>(PrevDecl))
15540     return NTK_Template;
15541   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15542     return NTK_TypeAliasTemplate;
15543   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15544     return NTK_TemplateTemplateArgument;
15545   switch (TTK) {
15546   case TTK_Struct:
15547   case TTK_Interface:
15548   case TTK_Class:
15549     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15550   case TTK_Union:
15551     return NTK_NonUnion;
15552   case TTK_Enum:
15553     return NTK_NonEnum;
15554   }
15555   llvm_unreachable("invalid TTK");
15556 }
15557 
15558 /// Determine whether a tag with a given kind is acceptable
15559 /// as a redeclaration of the given tag declaration.
15560 ///
15561 /// \returns true if the new tag kind is acceptable, false otherwise.
15562 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15563                                         TagTypeKind NewTag, bool isDefinition,
15564                                         SourceLocation NewTagLoc,
15565                                         const IdentifierInfo *Name) {
15566   // C++ [dcl.type.elab]p3:
15567   //   The class-key or enum keyword present in the
15568   //   elaborated-type-specifier shall agree in kind with the
15569   //   declaration to which the name in the elaborated-type-specifier
15570   //   refers. This rule also applies to the form of
15571   //   elaborated-type-specifier that declares a class-name or
15572   //   friend class since it can be construed as referring to the
15573   //   definition of the class. Thus, in any
15574   //   elaborated-type-specifier, the enum keyword shall be used to
15575   //   refer to an enumeration (7.2), the union class-key shall be
15576   //   used to refer to a union (clause 9), and either the class or
15577   //   struct class-key shall be used to refer to a class (clause 9)
15578   //   declared using the class or struct class-key.
15579   TagTypeKind OldTag = Previous->getTagKind();
15580   if (OldTag != NewTag &&
15581       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15582     return false;
15583 
15584   // Tags are compatible, but we might still want to warn on mismatched tags.
15585   // Non-class tags can't be mismatched at this point.
15586   if (!isClassCompatTagKind(NewTag))
15587     return true;
15588 
15589   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15590   // by our warning analysis. We don't want to warn about mismatches with (eg)
15591   // declarations in system headers that are designed to be specialized, but if
15592   // a user asks us to warn, we should warn if their code contains mismatched
15593   // declarations.
15594   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15595     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15596                                       Loc);
15597   };
15598   if (IsIgnoredLoc(NewTagLoc))
15599     return true;
15600 
15601   auto IsIgnored = [&](const TagDecl *Tag) {
15602     return IsIgnoredLoc(Tag->getLocation());
15603   };
15604   while (IsIgnored(Previous)) {
15605     Previous = Previous->getPreviousDecl();
15606     if (!Previous)
15607       return true;
15608     OldTag = Previous->getTagKind();
15609   }
15610 
15611   bool isTemplate = false;
15612   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15613     isTemplate = Record->getDescribedClassTemplate();
15614 
15615   if (inTemplateInstantiation()) {
15616     if (OldTag != NewTag) {
15617       // In a template instantiation, do not offer fix-its for tag mismatches
15618       // since they usually mess up the template instead of fixing the problem.
15619       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15620         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15621         << getRedeclDiagFromTagKind(OldTag);
15622       // FIXME: Note previous location?
15623     }
15624     return true;
15625   }
15626 
15627   if (isDefinition) {
15628     // On definitions, check all previous tags and issue a fix-it for each
15629     // one that doesn't match the current tag.
15630     if (Previous->getDefinition()) {
15631       // Don't suggest fix-its for redefinitions.
15632       return true;
15633     }
15634 
15635     bool previousMismatch = false;
15636     for (const TagDecl *I : Previous->redecls()) {
15637       if (I->getTagKind() != NewTag) {
15638         // Ignore previous declarations for which the warning was disabled.
15639         if (IsIgnored(I))
15640           continue;
15641 
15642         if (!previousMismatch) {
15643           previousMismatch = true;
15644           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15645             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15646             << getRedeclDiagFromTagKind(I->getTagKind());
15647         }
15648         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15649           << getRedeclDiagFromTagKind(NewTag)
15650           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15651                TypeWithKeyword::getTagTypeKindName(NewTag));
15652       }
15653     }
15654     return true;
15655   }
15656 
15657   // Identify the prevailing tag kind: this is the kind of the definition (if
15658   // there is a non-ignored definition), or otherwise the kind of the prior
15659   // (non-ignored) declaration.
15660   const TagDecl *PrevDef = Previous->getDefinition();
15661   if (PrevDef && IsIgnored(PrevDef))
15662     PrevDef = nullptr;
15663   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15664   if (Redecl->getTagKind() != NewTag) {
15665     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15666       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15667       << getRedeclDiagFromTagKind(OldTag);
15668     Diag(Redecl->getLocation(), diag::note_previous_use);
15669 
15670     // If there is a previous definition, suggest a fix-it.
15671     if (PrevDef) {
15672       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15673         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15674         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15675              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15676     }
15677   }
15678 
15679   return true;
15680 }
15681 
15682 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15683 /// from an outer enclosing namespace or file scope inside a friend declaration.
15684 /// This should provide the commented out code in the following snippet:
15685 ///   namespace N {
15686 ///     struct X;
15687 ///     namespace M {
15688 ///       struct Y { friend struct /*N::*/ X; };
15689 ///     }
15690 ///   }
15691 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15692                                          SourceLocation NameLoc) {
15693   // While the decl is in a namespace, do repeated lookup of that name and see
15694   // if we get the same namespace back.  If we do not, continue until
15695   // translation unit scope, at which point we have a fully qualified NNS.
15696   SmallVector<IdentifierInfo *, 4> Namespaces;
15697   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15698   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15699     // This tag should be declared in a namespace, which can only be enclosed by
15700     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15701     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15702     if (!Namespace || Namespace->isAnonymousNamespace())
15703       return FixItHint();
15704     IdentifierInfo *II = Namespace->getIdentifier();
15705     Namespaces.push_back(II);
15706     NamedDecl *Lookup = SemaRef.LookupSingleName(
15707         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15708     if (Lookup == Namespace)
15709       break;
15710   }
15711 
15712   // Once we have all the namespaces, reverse them to go outermost first, and
15713   // build an NNS.
15714   SmallString<64> Insertion;
15715   llvm::raw_svector_ostream OS(Insertion);
15716   if (DC->isTranslationUnit())
15717     OS << "::";
15718   std::reverse(Namespaces.begin(), Namespaces.end());
15719   for (auto *II : Namespaces)
15720     OS << II->getName() << "::";
15721   return FixItHint::CreateInsertion(NameLoc, Insertion);
15722 }
15723 
15724 /// Determine whether a tag originally declared in context \p OldDC can
15725 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15726 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15727 /// using-declaration).
15728 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15729                                          DeclContext *NewDC) {
15730   OldDC = OldDC->getRedeclContext();
15731   NewDC = NewDC->getRedeclContext();
15732 
15733   if (OldDC->Equals(NewDC))
15734     return true;
15735 
15736   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15737   // encloses the other).
15738   if (S.getLangOpts().MSVCCompat &&
15739       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15740     return true;
15741 
15742   return false;
15743 }
15744 
15745 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15746 /// former case, Name will be non-null.  In the later case, Name will be null.
15747 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15748 /// reference/declaration/definition of a tag.
15749 ///
15750 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15751 /// trailing-type-specifier) other than one in an alias-declaration.
15752 ///
15753 /// \param SkipBody If non-null, will be set to indicate if the caller should
15754 /// skip the definition of this tag and treat it as if it were a declaration.
15755 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15756                      SourceLocation KWLoc, CXXScopeSpec &SS,
15757                      IdentifierInfo *Name, SourceLocation NameLoc,
15758                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15759                      SourceLocation ModulePrivateLoc,
15760                      MultiTemplateParamsArg TemplateParameterLists,
15761                      bool &OwnedDecl, bool &IsDependent,
15762                      SourceLocation ScopedEnumKWLoc,
15763                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15764                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15765                      SkipBodyInfo *SkipBody) {
15766   // If this is not a definition, it must have a name.
15767   IdentifierInfo *OrigName = Name;
15768   assert((Name != nullptr || TUK == TUK_Definition) &&
15769          "Nameless record must be a definition!");
15770   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15771 
15772   OwnedDecl = false;
15773   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15774   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15775 
15776   // FIXME: Check member specializations more carefully.
15777   bool isMemberSpecialization = false;
15778   bool Invalid = false;
15779 
15780   // We only need to do this matching if we have template parameters
15781   // or a scope specifier, which also conveniently avoids this work
15782   // for non-C++ cases.
15783   if (TemplateParameterLists.size() > 0 ||
15784       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15785     if (TemplateParameterList *TemplateParams =
15786             MatchTemplateParametersToScopeSpecifier(
15787                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15788                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15789       if (Kind == TTK_Enum) {
15790         Diag(KWLoc, diag::err_enum_template);
15791         return nullptr;
15792       }
15793 
15794       if (TemplateParams->size() > 0) {
15795         // This is a declaration or definition of a class template (which may
15796         // be a member of another template).
15797 
15798         if (Invalid)
15799           return nullptr;
15800 
15801         OwnedDecl = false;
15802         DeclResult Result = CheckClassTemplate(
15803             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15804             AS, ModulePrivateLoc,
15805             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15806             TemplateParameterLists.data(), SkipBody);
15807         return Result.get();
15808       } else {
15809         // The "template<>" header is extraneous.
15810         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15811           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15812         isMemberSpecialization = true;
15813       }
15814     }
15815 
15816     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15817         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15818       return nullptr;
15819   }
15820 
15821   // Figure out the underlying type if this a enum declaration. We need to do
15822   // this early, because it's needed to detect if this is an incompatible
15823   // redeclaration.
15824   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15825   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15826 
15827   if (Kind == TTK_Enum) {
15828     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15829       // No underlying type explicitly specified, or we failed to parse the
15830       // type, default to int.
15831       EnumUnderlying = Context.IntTy.getTypePtr();
15832     } else if (UnderlyingType.get()) {
15833       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15834       // integral type; any cv-qualification is ignored.
15835       TypeSourceInfo *TI = nullptr;
15836       GetTypeFromParser(UnderlyingType.get(), &TI);
15837       EnumUnderlying = TI;
15838 
15839       if (CheckEnumUnderlyingType(TI))
15840         // Recover by falling back to int.
15841         EnumUnderlying = Context.IntTy.getTypePtr();
15842 
15843       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15844                                           UPPC_FixedUnderlyingType))
15845         EnumUnderlying = Context.IntTy.getTypePtr();
15846 
15847     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15848       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15849       // of 'int'. However, if this is an unfixed forward declaration, don't set
15850       // the underlying type unless the user enables -fms-compatibility. This
15851       // makes unfixed forward declared enums incomplete and is more conforming.
15852       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15853         EnumUnderlying = Context.IntTy.getTypePtr();
15854     }
15855   }
15856 
15857   DeclContext *SearchDC = CurContext;
15858   DeclContext *DC = CurContext;
15859   bool isStdBadAlloc = false;
15860   bool isStdAlignValT = false;
15861 
15862   RedeclarationKind Redecl = forRedeclarationInCurContext();
15863   if (TUK == TUK_Friend || TUK == TUK_Reference)
15864     Redecl = NotForRedeclaration;
15865 
15866   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15867   /// implemented asks for structural equivalence checking, the returned decl
15868   /// here is passed back to the parser, allowing the tag body to be parsed.
15869   auto createTagFromNewDecl = [&]() -> TagDecl * {
15870     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15871     // If there is an identifier, use the location of the identifier as the
15872     // location of the decl, otherwise use the location of the struct/union
15873     // keyword.
15874     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15875     TagDecl *New = nullptr;
15876 
15877     if (Kind == TTK_Enum) {
15878       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15879                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15880       // If this is an undefined enum, bail.
15881       if (TUK != TUK_Definition && !Invalid)
15882         return nullptr;
15883       if (EnumUnderlying) {
15884         EnumDecl *ED = cast<EnumDecl>(New);
15885         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15886           ED->setIntegerTypeSourceInfo(TI);
15887         else
15888           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15889         ED->setPromotionType(ED->getIntegerType());
15890       }
15891     } else { // struct/union
15892       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15893                                nullptr);
15894     }
15895 
15896     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15897       // Add alignment attributes if necessary; these attributes are checked
15898       // when the ASTContext lays out the structure.
15899       //
15900       // It is important for implementing the correct semantics that this
15901       // happen here (in ActOnTag). The #pragma pack stack is
15902       // maintained as a result of parser callbacks which can occur at
15903       // many points during the parsing of a struct declaration (because
15904       // the #pragma tokens are effectively skipped over during the
15905       // parsing of the struct).
15906       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15907         AddAlignmentAttributesForRecord(RD);
15908         AddMsStructLayoutForRecord(RD);
15909       }
15910     }
15911     New->setLexicalDeclContext(CurContext);
15912     return New;
15913   };
15914 
15915   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15916   if (Name && SS.isNotEmpty()) {
15917     // We have a nested-name tag ('struct foo::bar').
15918 
15919     // Check for invalid 'foo::'.
15920     if (SS.isInvalid()) {
15921       Name = nullptr;
15922       goto CreateNewDecl;
15923     }
15924 
15925     // If this is a friend or a reference to a class in a dependent
15926     // context, don't try to make a decl for it.
15927     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15928       DC = computeDeclContext(SS, false);
15929       if (!DC) {
15930         IsDependent = true;
15931         return nullptr;
15932       }
15933     } else {
15934       DC = computeDeclContext(SS, true);
15935       if (!DC) {
15936         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15937           << SS.getRange();
15938         return nullptr;
15939       }
15940     }
15941 
15942     if (RequireCompleteDeclContext(SS, DC))
15943       return nullptr;
15944 
15945     SearchDC = DC;
15946     // Look-up name inside 'foo::'.
15947     LookupQualifiedName(Previous, DC);
15948 
15949     if (Previous.isAmbiguous())
15950       return nullptr;
15951 
15952     if (Previous.empty()) {
15953       // Name lookup did not find anything. However, if the
15954       // nested-name-specifier refers to the current instantiation,
15955       // and that current instantiation has any dependent base
15956       // classes, we might find something at instantiation time: treat
15957       // this as a dependent elaborated-type-specifier.
15958       // But this only makes any sense for reference-like lookups.
15959       if (Previous.wasNotFoundInCurrentInstantiation() &&
15960           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15961         IsDependent = true;
15962         return nullptr;
15963       }
15964 
15965       // A tag 'foo::bar' must already exist.
15966       Diag(NameLoc, diag::err_not_tag_in_scope)
15967         << Kind << Name << DC << SS.getRange();
15968       Name = nullptr;
15969       Invalid = true;
15970       goto CreateNewDecl;
15971     }
15972   } else if (Name) {
15973     // C++14 [class.mem]p14:
15974     //   If T is the name of a class, then each of the following shall have a
15975     //   name different from T:
15976     //    -- every member of class T that is itself a type
15977     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15978         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15979       return nullptr;
15980 
15981     // If this is a named struct, check to see if there was a previous forward
15982     // declaration or definition.
15983     // FIXME: We're looking into outer scopes here, even when we
15984     // shouldn't be. Doing so can result in ambiguities that we
15985     // shouldn't be diagnosing.
15986     LookupName(Previous, S);
15987 
15988     // When declaring or defining a tag, ignore ambiguities introduced
15989     // by types using'ed into this scope.
15990     if (Previous.isAmbiguous() &&
15991         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15992       LookupResult::Filter F = Previous.makeFilter();
15993       while (F.hasNext()) {
15994         NamedDecl *ND = F.next();
15995         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15996                 SearchDC->getRedeclContext()))
15997           F.erase();
15998       }
15999       F.done();
16000     }
16001 
16002     // C++11 [namespace.memdef]p3:
16003     //   If the name in a friend declaration is neither qualified nor
16004     //   a template-id and the declaration is a function or an
16005     //   elaborated-type-specifier, the lookup to determine whether
16006     //   the entity has been previously declared shall not consider
16007     //   any scopes outside the innermost enclosing namespace.
16008     //
16009     // MSVC doesn't implement the above rule for types, so a friend tag
16010     // declaration may be a redeclaration of a type declared in an enclosing
16011     // scope.  They do implement this rule for friend functions.
16012     //
16013     // Does it matter that this should be by scope instead of by
16014     // semantic context?
16015     if (!Previous.empty() && TUK == TUK_Friend) {
16016       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16017       LookupResult::Filter F = Previous.makeFilter();
16018       bool FriendSawTagOutsideEnclosingNamespace = false;
16019       while (F.hasNext()) {
16020         NamedDecl *ND = F.next();
16021         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16022         if (DC->isFileContext() &&
16023             !EnclosingNS->Encloses(ND->getDeclContext())) {
16024           if (getLangOpts().MSVCCompat)
16025             FriendSawTagOutsideEnclosingNamespace = true;
16026           else
16027             F.erase();
16028         }
16029       }
16030       F.done();
16031 
16032       // Diagnose this MSVC extension in the easy case where lookup would have
16033       // unambiguously found something outside the enclosing namespace.
16034       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16035         NamedDecl *ND = Previous.getFoundDecl();
16036         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16037             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16038       }
16039     }
16040 
16041     // Note:  there used to be some attempt at recovery here.
16042     if (Previous.isAmbiguous())
16043       return nullptr;
16044 
16045     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16046       // FIXME: This makes sure that we ignore the contexts associated
16047       // with C structs, unions, and enums when looking for a matching
16048       // tag declaration or definition. See the similar lookup tweak
16049       // in Sema::LookupName; is there a better way to deal with this?
16050       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
16051         SearchDC = SearchDC->getParent();
16052     }
16053   }
16054 
16055   if (Previous.isSingleResult() &&
16056       Previous.getFoundDecl()->isTemplateParameter()) {
16057     // Maybe we will complain about the shadowed template parameter.
16058     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16059     // Just pretend that we didn't see the previous declaration.
16060     Previous.clear();
16061   }
16062 
16063   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16064       DC->Equals(getStdNamespace())) {
16065     if (Name->isStr("bad_alloc")) {
16066       // This is a declaration of or a reference to "std::bad_alloc".
16067       isStdBadAlloc = true;
16068 
16069       // If std::bad_alloc has been implicitly declared (but made invisible to
16070       // name lookup), fill in this implicit declaration as the previous
16071       // declaration, so that the declarations get chained appropriately.
16072       if (Previous.empty() && StdBadAlloc)
16073         Previous.addDecl(getStdBadAlloc());
16074     } else if (Name->isStr("align_val_t")) {
16075       isStdAlignValT = true;
16076       if (Previous.empty() && StdAlignValT)
16077         Previous.addDecl(getStdAlignValT());
16078     }
16079   }
16080 
16081   // If we didn't find a previous declaration, and this is a reference
16082   // (or friend reference), move to the correct scope.  In C++, we
16083   // also need to do a redeclaration lookup there, just in case
16084   // there's a shadow friend decl.
16085   if (Name && Previous.empty() &&
16086       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16087     if (Invalid) goto CreateNewDecl;
16088     assert(SS.isEmpty());
16089 
16090     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16091       // C++ [basic.scope.pdecl]p5:
16092       //   -- for an elaborated-type-specifier of the form
16093       //
16094       //          class-key identifier
16095       //
16096       //      if the elaborated-type-specifier is used in the
16097       //      decl-specifier-seq or parameter-declaration-clause of a
16098       //      function defined in namespace scope, the identifier is
16099       //      declared as a class-name in the namespace that contains
16100       //      the declaration; otherwise, except as a friend
16101       //      declaration, the identifier is declared in the smallest
16102       //      non-class, non-function-prototype scope that contains the
16103       //      declaration.
16104       //
16105       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16106       // C structs and unions.
16107       //
16108       // It is an error in C++ to declare (rather than define) an enum
16109       // type, including via an elaborated type specifier.  We'll
16110       // diagnose that later; for now, declare the enum in the same
16111       // scope as we would have picked for any other tag type.
16112       //
16113       // GNU C also supports this behavior as part of its incomplete
16114       // enum types extension, while GNU C++ does not.
16115       //
16116       // Find the context where we'll be declaring the tag.
16117       // FIXME: We would like to maintain the current DeclContext as the
16118       // lexical context,
16119       SearchDC = getTagInjectionContext(SearchDC);
16120 
16121       // Find the scope where we'll be declaring the tag.
16122       S = getTagInjectionScope(S, getLangOpts());
16123     } else {
16124       assert(TUK == TUK_Friend);
16125       // C++ [namespace.memdef]p3:
16126       //   If a friend declaration in a non-local class first declares a
16127       //   class or function, the friend class or function is a member of
16128       //   the innermost enclosing namespace.
16129       SearchDC = SearchDC->getEnclosingNamespaceContext();
16130     }
16131 
16132     // In C++, we need to do a redeclaration lookup to properly
16133     // diagnose some problems.
16134     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16135     // hidden declaration so that we don't get ambiguity errors when using a
16136     // type declared by an elaborated-type-specifier.  In C that is not correct
16137     // and we should instead merge compatible types found by lookup.
16138     if (getLangOpts().CPlusPlus) {
16139       // FIXME: This can perform qualified lookups into function contexts,
16140       // which are meaningless.
16141       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16142       LookupQualifiedName(Previous, SearchDC);
16143     } else {
16144       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16145       LookupName(Previous, S);
16146     }
16147   }
16148 
16149   // If we have a known previous declaration to use, then use it.
16150   if (Previous.empty() && SkipBody && SkipBody->Previous)
16151     Previous.addDecl(SkipBody->Previous);
16152 
16153   if (!Previous.empty()) {
16154     NamedDecl *PrevDecl = Previous.getFoundDecl();
16155     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16156 
16157     // It's okay to have a tag decl in the same scope as a typedef
16158     // which hides a tag decl in the same scope.  Finding this
16159     // with a redeclaration lookup can only actually happen in C++.
16160     //
16161     // This is also okay for elaborated-type-specifiers, which is
16162     // technically forbidden by the current standard but which is
16163     // okay according to the likely resolution of an open issue;
16164     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16165     if (getLangOpts().CPlusPlus) {
16166       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16167         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16168           TagDecl *Tag = TT->getDecl();
16169           if (Tag->getDeclName() == Name &&
16170               Tag->getDeclContext()->getRedeclContext()
16171                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16172             PrevDecl = Tag;
16173             Previous.clear();
16174             Previous.addDecl(Tag);
16175             Previous.resolveKind();
16176           }
16177         }
16178       }
16179     }
16180 
16181     // If this is a redeclaration of a using shadow declaration, it must
16182     // declare a tag in the same context. In MSVC mode, we allow a
16183     // redefinition if either context is within the other.
16184     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16185       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16186       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16187           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16188           !(OldTag && isAcceptableTagRedeclContext(
16189                           *this, OldTag->getDeclContext(), SearchDC))) {
16190         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16191         Diag(Shadow->getTargetDecl()->getLocation(),
16192              diag::note_using_decl_target);
16193         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16194             << 0;
16195         // Recover by ignoring the old declaration.
16196         Previous.clear();
16197         goto CreateNewDecl;
16198       }
16199     }
16200 
16201     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16202       // If this is a use of a previous tag, or if the tag is already declared
16203       // in the same scope (so that the definition/declaration completes or
16204       // rementions the tag), reuse the decl.
16205       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16206           isDeclInScope(DirectPrevDecl, SearchDC, S,
16207                         SS.isNotEmpty() || isMemberSpecialization)) {
16208         // Make sure that this wasn't declared as an enum and now used as a
16209         // struct or something similar.
16210         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16211                                           TUK == TUK_Definition, KWLoc,
16212                                           Name)) {
16213           bool SafeToContinue
16214             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16215                Kind != TTK_Enum);
16216           if (SafeToContinue)
16217             Diag(KWLoc, diag::err_use_with_wrong_tag)
16218               << Name
16219               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16220                                               PrevTagDecl->getKindName());
16221           else
16222             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16223           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16224 
16225           if (SafeToContinue)
16226             Kind = PrevTagDecl->getTagKind();
16227           else {
16228             // Recover by making this an anonymous redefinition.
16229             Name = nullptr;
16230             Previous.clear();
16231             Invalid = true;
16232           }
16233         }
16234 
16235         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16236           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16237           if (TUK == TUK_Reference || TUK == TUK_Friend)
16238             return PrevTagDecl;
16239 
16240           QualType EnumUnderlyingTy;
16241           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16242             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16243           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16244             EnumUnderlyingTy = QualType(T, 0);
16245 
16246           // All conflicts with previous declarations are recovered by
16247           // returning the previous declaration, unless this is a definition,
16248           // in which case we want the caller to bail out.
16249           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16250                                      ScopedEnum, EnumUnderlyingTy,
16251                                      IsFixed, PrevEnum))
16252             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16253         }
16254 
16255         // C++11 [class.mem]p1:
16256         //   A member shall not be declared twice in the member-specification,
16257         //   except that a nested class or member class template can be declared
16258         //   and then later defined.
16259         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16260             S->isDeclScope(PrevDecl)) {
16261           Diag(NameLoc, diag::ext_member_redeclared);
16262           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16263         }
16264 
16265         if (!Invalid) {
16266           // If this is a use, just return the declaration we found, unless
16267           // we have attributes.
16268           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16269             if (!Attrs.empty()) {
16270               // FIXME: Diagnose these attributes. For now, we create a new
16271               // declaration to hold them.
16272             } else if (TUK == TUK_Reference &&
16273                        (PrevTagDecl->getFriendObjectKind() ==
16274                             Decl::FOK_Undeclared ||
16275                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16276                        SS.isEmpty()) {
16277               // This declaration is a reference to an existing entity, but
16278               // has different visibility from that entity: it either makes
16279               // a friend visible or it makes a type visible in a new module.
16280               // In either case, create a new declaration. We only do this if
16281               // the declaration would have meant the same thing if no prior
16282               // declaration were found, that is, if it was found in the same
16283               // scope where we would have injected a declaration.
16284               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16285                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16286                 return PrevTagDecl;
16287               // This is in the injected scope, create a new declaration in
16288               // that scope.
16289               S = getTagInjectionScope(S, getLangOpts());
16290             } else {
16291               return PrevTagDecl;
16292             }
16293           }
16294 
16295           // Diagnose attempts to redefine a tag.
16296           if (TUK == TUK_Definition) {
16297             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16298               // If we're defining a specialization and the previous definition
16299               // is from an implicit instantiation, don't emit an error
16300               // here; we'll catch this in the general case below.
16301               bool IsExplicitSpecializationAfterInstantiation = false;
16302               if (isMemberSpecialization) {
16303                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16304                   IsExplicitSpecializationAfterInstantiation =
16305                     RD->getTemplateSpecializationKind() !=
16306                     TSK_ExplicitSpecialization;
16307                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16308                   IsExplicitSpecializationAfterInstantiation =
16309                     ED->getTemplateSpecializationKind() !=
16310                     TSK_ExplicitSpecialization;
16311               }
16312 
16313               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16314               // not keep more that one definition around (merge them). However,
16315               // ensure the decl passes the structural compatibility check in
16316               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16317               NamedDecl *Hidden = nullptr;
16318               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16319                 // There is a definition of this tag, but it is not visible. We
16320                 // explicitly make use of C++'s one definition rule here, and
16321                 // assume that this definition is identical to the hidden one
16322                 // we already have. Make the existing definition visible and
16323                 // use it in place of this one.
16324                 if (!getLangOpts().CPlusPlus) {
16325                   // Postpone making the old definition visible until after we
16326                   // complete parsing the new one and do the structural
16327                   // comparison.
16328                   SkipBody->CheckSameAsPrevious = true;
16329                   SkipBody->New = createTagFromNewDecl();
16330                   SkipBody->Previous = Def;
16331                   return Def;
16332                 } else {
16333                   SkipBody->ShouldSkip = true;
16334                   SkipBody->Previous = Def;
16335                   makeMergedDefinitionVisible(Hidden);
16336                   // Carry on and handle it like a normal definition. We'll
16337                   // skip starting the definitiion later.
16338                 }
16339               } else if (!IsExplicitSpecializationAfterInstantiation) {
16340                 // A redeclaration in function prototype scope in C isn't
16341                 // visible elsewhere, so merely issue a warning.
16342                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16343                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16344                 else
16345                   Diag(NameLoc, diag::err_redefinition) << Name;
16346                 notePreviousDefinition(Def,
16347                                        NameLoc.isValid() ? NameLoc : KWLoc);
16348                 // If this is a redefinition, recover by making this
16349                 // struct be anonymous, which will make any later
16350                 // references get the previous definition.
16351                 Name = nullptr;
16352                 Previous.clear();
16353                 Invalid = true;
16354               }
16355             } else {
16356               // If the type is currently being defined, complain
16357               // about a nested redefinition.
16358               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16359               if (TD->isBeingDefined()) {
16360                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16361                 Diag(PrevTagDecl->getLocation(),
16362                      diag::note_previous_definition);
16363                 Name = nullptr;
16364                 Previous.clear();
16365                 Invalid = true;
16366               }
16367             }
16368 
16369             // Okay, this is definition of a previously declared or referenced
16370             // tag. We're going to create a new Decl for it.
16371           }
16372 
16373           // Okay, we're going to make a redeclaration.  If this is some kind
16374           // of reference, make sure we build the redeclaration in the same DC
16375           // as the original, and ignore the current access specifier.
16376           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16377             SearchDC = PrevTagDecl->getDeclContext();
16378             AS = AS_none;
16379           }
16380         }
16381         // If we get here we have (another) forward declaration or we
16382         // have a definition.  Just create a new decl.
16383 
16384       } else {
16385         // If we get here, this is a definition of a new tag type in a nested
16386         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16387         // new decl/type.  We set PrevDecl to NULL so that the entities
16388         // have distinct types.
16389         Previous.clear();
16390       }
16391       // If we get here, we're going to create a new Decl. If PrevDecl
16392       // is non-NULL, it's a definition of the tag declared by
16393       // PrevDecl. If it's NULL, we have a new definition.
16394 
16395     // Otherwise, PrevDecl is not a tag, but was found with tag
16396     // lookup.  This is only actually possible in C++, where a few
16397     // things like templates still live in the tag namespace.
16398     } else {
16399       // Use a better diagnostic if an elaborated-type-specifier
16400       // found the wrong kind of type on the first
16401       // (non-redeclaration) lookup.
16402       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16403           !Previous.isForRedeclaration()) {
16404         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16405         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16406                                                        << Kind;
16407         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16408         Invalid = true;
16409 
16410       // Otherwise, only diagnose if the declaration is in scope.
16411       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16412                                 SS.isNotEmpty() || isMemberSpecialization)) {
16413         // do nothing
16414 
16415       // Diagnose implicit declarations introduced by elaborated types.
16416       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16417         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16418         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16419         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16420         Invalid = true;
16421 
16422       // Otherwise it's a declaration.  Call out a particularly common
16423       // case here.
16424       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16425         unsigned Kind = 0;
16426         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16427         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16428           << Name << Kind << TND->getUnderlyingType();
16429         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16430         Invalid = true;
16431 
16432       // Otherwise, diagnose.
16433       } else {
16434         // The tag name clashes with something else in the target scope,
16435         // issue an error and recover by making this tag be anonymous.
16436         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16437         notePreviousDefinition(PrevDecl, NameLoc);
16438         Name = nullptr;
16439         Invalid = true;
16440       }
16441 
16442       // The existing declaration isn't relevant to us; we're in a
16443       // new scope, so clear out the previous declaration.
16444       Previous.clear();
16445     }
16446   }
16447 
16448 CreateNewDecl:
16449 
16450   TagDecl *PrevDecl = nullptr;
16451   if (Previous.isSingleResult())
16452     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16453 
16454   // If there is an identifier, use the location of the identifier as the
16455   // location of the decl, otherwise use the location of the struct/union
16456   // keyword.
16457   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16458 
16459   // Otherwise, create a new declaration. If there is a previous
16460   // declaration of the same entity, the two will be linked via
16461   // PrevDecl.
16462   TagDecl *New;
16463 
16464   if (Kind == TTK_Enum) {
16465     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16466     // enum X { A, B, C } D;    D should chain to X.
16467     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16468                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16469                            ScopedEnumUsesClassTag, IsFixed);
16470 
16471     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16472       StdAlignValT = cast<EnumDecl>(New);
16473 
16474     // If this is an undefined enum, warn.
16475     if (TUK != TUK_Definition && !Invalid) {
16476       TagDecl *Def;
16477       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16478         // C++0x: 7.2p2: opaque-enum-declaration.
16479         // Conflicts are diagnosed above. Do nothing.
16480       }
16481       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16482         Diag(Loc, diag::ext_forward_ref_enum_def)
16483           << New;
16484         Diag(Def->getLocation(), diag::note_previous_definition);
16485       } else {
16486         unsigned DiagID = diag::ext_forward_ref_enum;
16487         if (getLangOpts().MSVCCompat)
16488           DiagID = diag::ext_ms_forward_ref_enum;
16489         else if (getLangOpts().CPlusPlus)
16490           DiagID = diag::err_forward_ref_enum;
16491         Diag(Loc, DiagID);
16492       }
16493     }
16494 
16495     if (EnumUnderlying) {
16496       EnumDecl *ED = cast<EnumDecl>(New);
16497       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16498         ED->setIntegerTypeSourceInfo(TI);
16499       else
16500         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16501       ED->setPromotionType(ED->getIntegerType());
16502       assert(ED->isComplete() && "enum with type should be complete");
16503     }
16504   } else {
16505     // struct/union/class
16506 
16507     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16508     // struct X { int A; } D;    D should chain to X.
16509     if (getLangOpts().CPlusPlus) {
16510       // FIXME: Look for a way to use RecordDecl for simple structs.
16511       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16512                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16513 
16514       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16515         StdBadAlloc = cast<CXXRecordDecl>(New);
16516     } else
16517       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16518                                cast_or_null<RecordDecl>(PrevDecl));
16519   }
16520 
16521   // C++11 [dcl.type]p3:
16522   //   A type-specifier-seq shall not define a class or enumeration [...].
16523   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16524       TUK == TUK_Definition) {
16525     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16526       << Context.getTagDeclType(New);
16527     Invalid = true;
16528   }
16529 
16530   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16531       DC->getDeclKind() == Decl::Enum) {
16532     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16533       << Context.getTagDeclType(New);
16534     Invalid = true;
16535   }
16536 
16537   // Maybe add qualifier info.
16538   if (SS.isNotEmpty()) {
16539     if (SS.isSet()) {
16540       // If this is either a declaration or a definition, check the
16541       // nested-name-specifier against the current context.
16542       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16543           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16544                                        isMemberSpecialization))
16545         Invalid = true;
16546 
16547       New->setQualifierInfo(SS.getWithLocInContext(Context));
16548       if (TemplateParameterLists.size() > 0) {
16549         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16550       }
16551     }
16552     else
16553       Invalid = true;
16554   }
16555 
16556   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16557     // Add alignment attributes if necessary; these attributes are checked when
16558     // the ASTContext lays out the structure.
16559     //
16560     // It is important for implementing the correct semantics that this
16561     // happen here (in ActOnTag). The #pragma pack stack is
16562     // maintained as a result of parser callbacks which can occur at
16563     // many points during the parsing of a struct declaration (because
16564     // the #pragma tokens are effectively skipped over during the
16565     // parsing of the struct).
16566     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16567       AddAlignmentAttributesForRecord(RD);
16568       AddMsStructLayoutForRecord(RD);
16569     }
16570   }
16571 
16572   if (ModulePrivateLoc.isValid()) {
16573     if (isMemberSpecialization)
16574       Diag(New->getLocation(), diag::err_module_private_specialization)
16575         << 2
16576         << FixItHint::CreateRemoval(ModulePrivateLoc);
16577     // __module_private__ does not apply to local classes. However, we only
16578     // diagnose this as an error when the declaration specifiers are
16579     // freestanding. Here, we just ignore the __module_private__.
16580     else if (!SearchDC->isFunctionOrMethod())
16581       New->setModulePrivate();
16582   }
16583 
16584   // If this is a specialization of a member class (of a class template),
16585   // check the specialization.
16586   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16587     Invalid = true;
16588 
16589   // If we're declaring or defining a tag in function prototype scope in C,
16590   // note that this type can only be used within the function and add it to
16591   // the list of decls to inject into the function definition scope.
16592   if ((Name || Kind == TTK_Enum) &&
16593       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16594     if (getLangOpts().CPlusPlus) {
16595       // C++ [dcl.fct]p6:
16596       //   Types shall not be defined in return or parameter types.
16597       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16598         Diag(Loc, diag::err_type_defined_in_param_type)
16599             << Name;
16600         Invalid = true;
16601       }
16602     } else if (!PrevDecl) {
16603       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16604     }
16605   }
16606 
16607   if (Invalid)
16608     New->setInvalidDecl();
16609 
16610   // Set the lexical context. If the tag has a C++ scope specifier, the
16611   // lexical context will be different from the semantic context.
16612   New->setLexicalDeclContext(CurContext);
16613 
16614   // Mark this as a friend decl if applicable.
16615   // In Microsoft mode, a friend declaration also acts as a forward
16616   // declaration so we always pass true to setObjectOfFriendDecl to make
16617   // the tag name visible.
16618   if (TUK == TUK_Friend)
16619     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16620 
16621   // Set the access specifier.
16622   if (!Invalid && SearchDC->isRecord())
16623     SetMemberAccessSpecifier(New, PrevDecl, AS);
16624 
16625   if (PrevDecl)
16626     CheckRedeclarationInModule(New, PrevDecl);
16627 
16628   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16629     New->startDefinition();
16630 
16631   ProcessDeclAttributeList(S, New, Attrs);
16632   AddPragmaAttributes(S, New);
16633 
16634   // If this has an identifier, add it to the scope stack.
16635   if (TUK == TUK_Friend) {
16636     // We might be replacing an existing declaration in the lookup tables;
16637     // if so, borrow its access specifier.
16638     if (PrevDecl)
16639       New->setAccess(PrevDecl->getAccess());
16640 
16641     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16642     DC->makeDeclVisibleInContext(New);
16643     if (Name) // can be null along some error paths
16644       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16645         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16646   } else if (Name) {
16647     S = getNonFieldDeclScope(S);
16648     PushOnScopeChains(New, S, true);
16649   } else {
16650     CurContext->addDecl(New);
16651   }
16652 
16653   // If this is the C FILE type, notify the AST context.
16654   if (IdentifierInfo *II = New->getIdentifier())
16655     if (!New->isInvalidDecl() &&
16656         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16657         II->isStr("FILE"))
16658       Context.setFILEDecl(New);
16659 
16660   if (PrevDecl)
16661     mergeDeclAttributes(New, PrevDecl);
16662 
16663   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16664     inferGslOwnerPointerAttribute(CXXRD);
16665 
16666   // If there's a #pragma GCC visibility in scope, set the visibility of this
16667   // record.
16668   AddPushedVisibilityAttribute(New);
16669 
16670   if (isMemberSpecialization && !New->isInvalidDecl())
16671     CompleteMemberSpecialization(New, Previous);
16672 
16673   OwnedDecl = true;
16674   // In C++, don't return an invalid declaration. We can't recover well from
16675   // the cases where we make the type anonymous.
16676   if (Invalid && getLangOpts().CPlusPlus) {
16677     if (New->isBeingDefined())
16678       if (auto RD = dyn_cast<RecordDecl>(New))
16679         RD->completeDefinition();
16680     return nullptr;
16681   } else if (SkipBody && SkipBody->ShouldSkip) {
16682     return SkipBody->Previous;
16683   } else {
16684     return New;
16685   }
16686 }
16687 
16688 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16689   AdjustDeclIfTemplate(TagD);
16690   TagDecl *Tag = cast<TagDecl>(TagD);
16691 
16692   // Enter the tag context.
16693   PushDeclContext(S, Tag);
16694 
16695   ActOnDocumentableDecl(TagD);
16696 
16697   // If there's a #pragma GCC visibility in scope, set the visibility of this
16698   // record.
16699   AddPushedVisibilityAttribute(Tag);
16700 }
16701 
16702 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16703                                     SkipBodyInfo &SkipBody) {
16704   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16705     return false;
16706 
16707   // Make the previous decl visible.
16708   makeMergedDefinitionVisible(SkipBody.Previous);
16709   return true;
16710 }
16711 
16712 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16713   assert(isa<ObjCContainerDecl>(IDecl) &&
16714          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16715   DeclContext *OCD = cast<DeclContext>(IDecl);
16716   assert(OCD->getLexicalParent() == CurContext &&
16717       "The next DeclContext should be lexically contained in the current one.");
16718   CurContext = OCD;
16719   return IDecl;
16720 }
16721 
16722 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16723                                            SourceLocation FinalLoc,
16724                                            bool IsFinalSpelledSealed,
16725                                            bool IsAbstract,
16726                                            SourceLocation LBraceLoc) {
16727   AdjustDeclIfTemplate(TagD);
16728   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16729 
16730   FieldCollector->StartClass();
16731 
16732   if (!Record->getIdentifier())
16733     return;
16734 
16735   if (IsAbstract)
16736     Record->markAbstract();
16737 
16738   if (FinalLoc.isValid()) {
16739     Record->addAttr(FinalAttr::Create(
16740         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16741         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16742   }
16743   // C++ [class]p2:
16744   //   [...] The class-name is also inserted into the scope of the
16745   //   class itself; this is known as the injected-class-name. For
16746   //   purposes of access checking, the injected-class-name is treated
16747   //   as if it were a public member name.
16748   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16749       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16750       Record->getLocation(), Record->getIdentifier(),
16751       /*PrevDecl=*/nullptr,
16752       /*DelayTypeCreation=*/true);
16753   Context.getTypeDeclType(InjectedClassName, Record);
16754   InjectedClassName->setImplicit();
16755   InjectedClassName->setAccess(AS_public);
16756   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16757       InjectedClassName->setDescribedClassTemplate(Template);
16758   PushOnScopeChains(InjectedClassName, S);
16759   assert(InjectedClassName->isInjectedClassName() &&
16760          "Broken injected-class-name");
16761 }
16762 
16763 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16764                                     SourceRange BraceRange) {
16765   AdjustDeclIfTemplate(TagD);
16766   TagDecl *Tag = cast<TagDecl>(TagD);
16767   Tag->setBraceRange(BraceRange);
16768 
16769   // Make sure we "complete" the definition even it is invalid.
16770   if (Tag->isBeingDefined()) {
16771     assert(Tag->isInvalidDecl() && "We should already have completed it");
16772     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16773       RD->completeDefinition();
16774   }
16775 
16776   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16777     FieldCollector->FinishClass();
16778     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16779       auto *Def = RD->getDefinition();
16780       assert(Def && "The record is expected to have a completed definition");
16781       unsigned NumInitMethods = 0;
16782       for (auto *Method : Def->methods()) {
16783         if (!Method->getIdentifier())
16784             continue;
16785         if (Method->getName() == "__init")
16786           NumInitMethods++;
16787       }
16788       if (NumInitMethods > 1 || !Def->hasInitMethod())
16789         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16790     }
16791   }
16792 
16793   // Exit this scope of this tag's definition.
16794   PopDeclContext();
16795 
16796   if (getCurLexicalContext()->isObjCContainer() &&
16797       Tag->getDeclContext()->isFileContext())
16798     Tag->setTopLevelDeclInObjCContainer();
16799 
16800   // Notify the consumer that we've defined a tag.
16801   if (!Tag->isInvalidDecl())
16802     Consumer.HandleTagDeclDefinition(Tag);
16803 
16804   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16805   // from XLs and instead matches the XL #pragma pack(1) behavior.
16806   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16807       AlignPackStack.hasValue()) {
16808     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16809     // Only diagnose #pragma align(packed).
16810     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16811       return;
16812     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16813     if (!RD)
16814       return;
16815     // Only warn if there is at least 1 bitfield member.
16816     if (llvm::any_of(RD->fields(),
16817                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16818       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16819   }
16820 }
16821 
16822 void Sema::ActOnObjCContainerFinishDefinition() {
16823   // Exit this scope of this interface definition.
16824   PopDeclContext();
16825 }
16826 
16827 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16828   assert(DC == CurContext && "Mismatch of container contexts");
16829   OriginalLexicalContext = DC;
16830   ActOnObjCContainerFinishDefinition();
16831 }
16832 
16833 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16834   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16835   OriginalLexicalContext = nullptr;
16836 }
16837 
16838 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16839   AdjustDeclIfTemplate(TagD);
16840   TagDecl *Tag = cast<TagDecl>(TagD);
16841   Tag->setInvalidDecl();
16842 
16843   // Make sure we "complete" the definition even it is invalid.
16844   if (Tag->isBeingDefined()) {
16845     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16846       RD->completeDefinition();
16847   }
16848 
16849   // We're undoing ActOnTagStartDefinition here, not
16850   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16851   // the FieldCollector.
16852 
16853   PopDeclContext();
16854 }
16855 
16856 // Note that FieldName may be null for anonymous bitfields.
16857 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16858                                 IdentifierInfo *FieldName,
16859                                 QualType FieldTy, bool IsMsStruct,
16860                                 Expr *BitWidth, bool *ZeroWidth) {
16861   assert(BitWidth);
16862   if (BitWidth->containsErrors())
16863     return ExprError();
16864 
16865   // Default to true; that shouldn't confuse checks for emptiness
16866   if (ZeroWidth)
16867     *ZeroWidth = true;
16868 
16869   // C99 6.7.2.1p4 - verify the field type.
16870   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16871   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16872     // Handle incomplete and sizeless types with a specific error.
16873     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16874                                  diag::err_field_incomplete_or_sizeless))
16875       return ExprError();
16876     if (FieldName)
16877       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16878         << FieldName << FieldTy << BitWidth->getSourceRange();
16879     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16880       << FieldTy << BitWidth->getSourceRange();
16881   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16882                                              UPPC_BitFieldWidth))
16883     return ExprError();
16884 
16885   // If the bit-width is type- or value-dependent, don't try to check
16886   // it now.
16887   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16888     return BitWidth;
16889 
16890   llvm::APSInt Value;
16891   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16892   if (ICE.isInvalid())
16893     return ICE;
16894   BitWidth = ICE.get();
16895 
16896   if (Value != 0 && ZeroWidth)
16897     *ZeroWidth = false;
16898 
16899   // Zero-width bitfield is ok for anonymous field.
16900   if (Value == 0 && FieldName)
16901     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16902 
16903   if (Value.isSigned() && Value.isNegative()) {
16904     if (FieldName)
16905       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16906                << FieldName << toString(Value, 10);
16907     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16908       << toString(Value, 10);
16909   }
16910 
16911   // The size of the bit-field must not exceed our maximum permitted object
16912   // size.
16913   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16914     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16915            << !FieldName << FieldName << toString(Value, 10);
16916   }
16917 
16918   if (!FieldTy->isDependentType()) {
16919     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16920     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16921     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16922 
16923     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16924     // ABI.
16925     bool CStdConstraintViolation =
16926         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16927     bool MSBitfieldViolation =
16928         Value.ugt(TypeStorageSize) &&
16929         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16930     if (CStdConstraintViolation || MSBitfieldViolation) {
16931       unsigned DiagWidth =
16932           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16933       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16934              << (bool)FieldName << FieldName << toString(Value, 10)
16935              << !CStdConstraintViolation << DiagWidth;
16936     }
16937 
16938     // Warn on types where the user might conceivably expect to get all
16939     // specified bits as value bits: that's all integral types other than
16940     // 'bool'.
16941     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16942       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16943           << FieldName << toString(Value, 10)
16944           << (unsigned)TypeWidth;
16945     }
16946   }
16947 
16948   return BitWidth;
16949 }
16950 
16951 /// ActOnField - Each field of a C struct/union is passed into this in order
16952 /// to create a FieldDecl object for it.
16953 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16954                        Declarator &D, Expr *BitfieldWidth) {
16955   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16956                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16957                                /*InitStyle=*/ICIS_NoInit, AS_public);
16958   return Res;
16959 }
16960 
16961 /// HandleField - Analyze a field of a C struct or a C++ data member.
16962 ///
16963 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16964                              SourceLocation DeclStart,
16965                              Declarator &D, Expr *BitWidth,
16966                              InClassInitStyle InitStyle,
16967                              AccessSpecifier AS) {
16968   if (D.isDecompositionDeclarator()) {
16969     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16970     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16971       << Decomp.getSourceRange();
16972     return nullptr;
16973   }
16974 
16975   IdentifierInfo *II = D.getIdentifier();
16976   SourceLocation Loc = DeclStart;
16977   if (II) Loc = D.getIdentifierLoc();
16978 
16979   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16980   QualType T = TInfo->getType();
16981   if (getLangOpts().CPlusPlus) {
16982     CheckExtraCXXDefaultArguments(D);
16983 
16984     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16985                                         UPPC_DataMemberType)) {
16986       D.setInvalidType();
16987       T = Context.IntTy;
16988       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16989     }
16990   }
16991 
16992   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16993 
16994   if (D.getDeclSpec().isInlineSpecified())
16995     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16996         << getLangOpts().CPlusPlus17;
16997   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16998     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16999          diag::err_invalid_thread)
17000       << DeclSpec::getSpecifierName(TSCS);
17001 
17002   // Check to see if this name was declared as a member previously
17003   NamedDecl *PrevDecl = nullptr;
17004   LookupResult Previous(*this, II, Loc, LookupMemberName,
17005                         ForVisibleRedeclaration);
17006   LookupName(Previous, S);
17007   switch (Previous.getResultKind()) {
17008     case LookupResult::Found:
17009     case LookupResult::FoundUnresolvedValue:
17010       PrevDecl = Previous.getAsSingle<NamedDecl>();
17011       break;
17012 
17013     case LookupResult::FoundOverloaded:
17014       PrevDecl = Previous.getRepresentativeDecl();
17015       break;
17016 
17017     case LookupResult::NotFound:
17018     case LookupResult::NotFoundInCurrentInstantiation:
17019     case LookupResult::Ambiguous:
17020       break;
17021   }
17022   Previous.suppressDiagnostics();
17023 
17024   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17025     // Maybe we will complain about the shadowed template parameter.
17026     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17027     // Just pretend that we didn't see the previous declaration.
17028     PrevDecl = nullptr;
17029   }
17030 
17031   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17032     PrevDecl = nullptr;
17033 
17034   bool Mutable
17035     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17036   SourceLocation TSSL = D.getBeginLoc();
17037   FieldDecl *NewFD
17038     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17039                      TSSL, AS, PrevDecl, &D);
17040 
17041   if (NewFD->isInvalidDecl())
17042     Record->setInvalidDecl();
17043 
17044   if (D.getDeclSpec().isModulePrivateSpecified())
17045     NewFD->setModulePrivate();
17046 
17047   if (NewFD->isInvalidDecl() && PrevDecl) {
17048     // Don't introduce NewFD into scope; there's already something
17049     // with the same name in the same scope.
17050   } else if (II) {
17051     PushOnScopeChains(NewFD, S);
17052   } else
17053     Record->addDecl(NewFD);
17054 
17055   return NewFD;
17056 }
17057 
17058 /// Build a new FieldDecl and check its well-formedness.
17059 ///
17060 /// This routine builds a new FieldDecl given the fields name, type,
17061 /// record, etc. \p PrevDecl should refer to any previous declaration
17062 /// with the same name and in the same scope as the field to be
17063 /// created.
17064 ///
17065 /// \returns a new FieldDecl.
17066 ///
17067 /// \todo The Declarator argument is a hack. It will be removed once
17068 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17069                                 TypeSourceInfo *TInfo,
17070                                 RecordDecl *Record, SourceLocation Loc,
17071                                 bool Mutable, Expr *BitWidth,
17072                                 InClassInitStyle InitStyle,
17073                                 SourceLocation TSSL,
17074                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17075                                 Declarator *D) {
17076   IdentifierInfo *II = Name.getAsIdentifierInfo();
17077   bool InvalidDecl = false;
17078   if (D) InvalidDecl = D->isInvalidType();
17079 
17080   // If we receive a broken type, recover by assuming 'int' and
17081   // marking this declaration as invalid.
17082   if (T.isNull() || T->containsErrors()) {
17083     InvalidDecl = true;
17084     T = Context.IntTy;
17085   }
17086 
17087   QualType EltTy = Context.getBaseElementType(T);
17088   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17089     if (RequireCompleteSizedType(Loc, EltTy,
17090                                  diag::err_field_incomplete_or_sizeless)) {
17091       // Fields of incomplete type force their record to be invalid.
17092       Record->setInvalidDecl();
17093       InvalidDecl = true;
17094     } else {
17095       NamedDecl *Def;
17096       EltTy->isIncompleteType(&Def);
17097       if (Def && Def->isInvalidDecl()) {
17098         Record->setInvalidDecl();
17099         InvalidDecl = true;
17100       }
17101     }
17102   }
17103 
17104   // TR 18037 does not allow fields to be declared with address space
17105   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17106       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17107     Diag(Loc, diag::err_field_with_address_space);
17108     Record->setInvalidDecl();
17109     InvalidDecl = true;
17110   }
17111 
17112   if (LangOpts.OpenCL) {
17113     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17114     // used as structure or union field: image, sampler, event or block types.
17115     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17116         T->isBlockPointerType()) {
17117       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17118       Record->setInvalidDecl();
17119       InvalidDecl = true;
17120     }
17121     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17122     // is enabled.
17123     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17124                         "__cl_clang_bitfields", LangOpts)) {
17125       Diag(Loc, diag::err_opencl_bitfields);
17126       InvalidDecl = true;
17127     }
17128   }
17129 
17130   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17131   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17132       T.hasQualifiers()) {
17133     InvalidDecl = true;
17134     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17135   }
17136 
17137   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17138   // than a variably modified type.
17139   if (!InvalidDecl && T->isVariablyModifiedType()) {
17140     if (!tryToFixVariablyModifiedVarType(
17141             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17142       InvalidDecl = true;
17143   }
17144 
17145   // Fields can not have abstract class types
17146   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17147                                              diag::err_abstract_type_in_decl,
17148                                              AbstractFieldType))
17149     InvalidDecl = true;
17150 
17151   bool ZeroWidth = false;
17152   if (InvalidDecl)
17153     BitWidth = nullptr;
17154   // If this is declared as a bit-field, check the bit-field.
17155   if (BitWidth) {
17156     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17157                               &ZeroWidth).get();
17158     if (!BitWidth) {
17159       InvalidDecl = true;
17160       BitWidth = nullptr;
17161       ZeroWidth = false;
17162     }
17163   }
17164 
17165   // Check that 'mutable' is consistent with the type of the declaration.
17166   if (!InvalidDecl && Mutable) {
17167     unsigned DiagID = 0;
17168     if (T->isReferenceType())
17169       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17170                                         : diag::err_mutable_reference;
17171     else if (T.isConstQualified())
17172       DiagID = diag::err_mutable_const;
17173 
17174     if (DiagID) {
17175       SourceLocation ErrLoc = Loc;
17176       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17177         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17178       Diag(ErrLoc, DiagID);
17179       if (DiagID != diag::ext_mutable_reference) {
17180         Mutable = false;
17181         InvalidDecl = true;
17182       }
17183     }
17184   }
17185 
17186   // C++11 [class.union]p8 (DR1460):
17187   //   At most one variant member of a union may have a
17188   //   brace-or-equal-initializer.
17189   if (InitStyle != ICIS_NoInit)
17190     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17191 
17192   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17193                                        BitWidth, Mutable, InitStyle);
17194   if (InvalidDecl)
17195     NewFD->setInvalidDecl();
17196 
17197   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17198     Diag(Loc, diag::err_duplicate_member) << II;
17199     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17200     NewFD->setInvalidDecl();
17201   }
17202 
17203   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17204     if (Record->isUnion()) {
17205       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17206         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17207         if (RDecl->getDefinition()) {
17208           // C++ [class.union]p1: An object of a class with a non-trivial
17209           // constructor, a non-trivial copy constructor, a non-trivial
17210           // destructor, or a non-trivial copy assignment operator
17211           // cannot be a member of a union, nor can an array of such
17212           // objects.
17213           if (CheckNontrivialField(NewFD))
17214             NewFD->setInvalidDecl();
17215         }
17216       }
17217 
17218       // C++ [class.union]p1: If a union contains a member of reference type,
17219       // the program is ill-formed, except when compiling with MSVC extensions
17220       // enabled.
17221       if (EltTy->isReferenceType()) {
17222         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17223                                     diag::ext_union_member_of_reference_type :
17224                                     diag::err_union_member_of_reference_type)
17225           << NewFD->getDeclName() << EltTy;
17226         if (!getLangOpts().MicrosoftExt)
17227           NewFD->setInvalidDecl();
17228       }
17229     }
17230   }
17231 
17232   // FIXME: We need to pass in the attributes given an AST
17233   // representation, not a parser representation.
17234   if (D) {
17235     // FIXME: The current scope is almost... but not entirely... correct here.
17236     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17237 
17238     if (NewFD->hasAttrs())
17239       CheckAlignasUnderalignment(NewFD);
17240   }
17241 
17242   // In auto-retain/release, infer strong retension for fields of
17243   // retainable type.
17244   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17245     NewFD->setInvalidDecl();
17246 
17247   if (T.isObjCGCWeak())
17248     Diag(Loc, diag::warn_attribute_weak_on_field);
17249 
17250   // PPC MMA non-pointer types are not allowed as field types.
17251   if (Context.getTargetInfo().getTriple().isPPC64() &&
17252       CheckPPCMMAType(T, NewFD->getLocation()))
17253     NewFD->setInvalidDecl();
17254 
17255   NewFD->setAccess(AS);
17256   return NewFD;
17257 }
17258 
17259 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17260   assert(FD);
17261   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17262 
17263   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17264     return false;
17265 
17266   QualType EltTy = Context.getBaseElementType(FD->getType());
17267   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17268     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17269     if (RDecl->getDefinition()) {
17270       // We check for copy constructors before constructors
17271       // because otherwise we'll never get complaints about
17272       // copy constructors.
17273 
17274       CXXSpecialMember member = CXXInvalid;
17275       // We're required to check for any non-trivial constructors. Since the
17276       // implicit default constructor is suppressed if there are any
17277       // user-declared constructors, we just need to check that there is a
17278       // trivial default constructor and a trivial copy constructor. (We don't
17279       // worry about move constructors here, since this is a C++98 check.)
17280       if (RDecl->hasNonTrivialCopyConstructor())
17281         member = CXXCopyConstructor;
17282       else if (!RDecl->hasTrivialDefaultConstructor())
17283         member = CXXDefaultConstructor;
17284       else if (RDecl->hasNonTrivialCopyAssignment())
17285         member = CXXCopyAssignment;
17286       else if (RDecl->hasNonTrivialDestructor())
17287         member = CXXDestructor;
17288 
17289       if (member != CXXInvalid) {
17290         if (!getLangOpts().CPlusPlus11 &&
17291             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17292           // Objective-C++ ARC: it is an error to have a non-trivial field of
17293           // a union. However, system headers in Objective-C programs
17294           // occasionally have Objective-C lifetime objects within unions,
17295           // and rather than cause the program to fail, we make those
17296           // members unavailable.
17297           SourceLocation Loc = FD->getLocation();
17298           if (getSourceManager().isInSystemHeader(Loc)) {
17299             if (!FD->hasAttr<UnavailableAttr>())
17300               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17301                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17302             return false;
17303           }
17304         }
17305 
17306         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17307                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17308                diag::err_illegal_union_or_anon_struct_member)
17309           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17310         DiagnoseNontrivial(RDecl, member);
17311         return !getLangOpts().CPlusPlus11;
17312       }
17313     }
17314   }
17315 
17316   return false;
17317 }
17318 
17319 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17320 ///  AST enum value.
17321 static ObjCIvarDecl::AccessControl
17322 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17323   switch (ivarVisibility) {
17324   default: llvm_unreachable("Unknown visitibility kind");
17325   case tok::objc_private: return ObjCIvarDecl::Private;
17326   case tok::objc_public: return ObjCIvarDecl::Public;
17327   case tok::objc_protected: return ObjCIvarDecl::Protected;
17328   case tok::objc_package: return ObjCIvarDecl::Package;
17329   }
17330 }
17331 
17332 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17333 /// in order to create an IvarDecl object for it.
17334 Decl *Sema::ActOnIvar(Scope *S,
17335                                 SourceLocation DeclStart,
17336                                 Declarator &D, Expr *BitfieldWidth,
17337                                 tok::ObjCKeywordKind Visibility) {
17338 
17339   IdentifierInfo *II = D.getIdentifier();
17340   Expr *BitWidth = (Expr*)BitfieldWidth;
17341   SourceLocation Loc = DeclStart;
17342   if (II) Loc = D.getIdentifierLoc();
17343 
17344   // FIXME: Unnamed fields can be handled in various different ways, for
17345   // example, unnamed unions inject all members into the struct namespace!
17346 
17347   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17348   QualType T = TInfo->getType();
17349 
17350   if (BitWidth) {
17351     // 6.7.2.1p3, 6.7.2.1p4
17352     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17353     if (!BitWidth)
17354       D.setInvalidType();
17355   } else {
17356     // Not a bitfield.
17357 
17358     // validate II.
17359 
17360   }
17361   if (T->isReferenceType()) {
17362     Diag(Loc, diag::err_ivar_reference_type);
17363     D.setInvalidType();
17364   }
17365   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17366   // than a variably modified type.
17367   else if (T->isVariablyModifiedType()) {
17368     if (!tryToFixVariablyModifiedVarType(
17369             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17370       D.setInvalidType();
17371   }
17372 
17373   // Get the visibility (access control) for this ivar.
17374   ObjCIvarDecl::AccessControl ac =
17375     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17376                                         : ObjCIvarDecl::None;
17377   // Must set ivar's DeclContext to its enclosing interface.
17378   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17379   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17380     return nullptr;
17381   ObjCContainerDecl *EnclosingContext;
17382   if (ObjCImplementationDecl *IMPDecl =
17383       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17384     if (LangOpts.ObjCRuntime.isFragile()) {
17385     // Case of ivar declared in an implementation. Context is that of its class.
17386       EnclosingContext = IMPDecl->getClassInterface();
17387       assert(EnclosingContext && "Implementation has no class interface!");
17388     }
17389     else
17390       EnclosingContext = EnclosingDecl;
17391   } else {
17392     if (ObjCCategoryDecl *CDecl =
17393         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17394       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17395         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17396         return nullptr;
17397       }
17398     }
17399     EnclosingContext = EnclosingDecl;
17400   }
17401 
17402   // Construct the decl.
17403   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17404                                              DeclStart, Loc, II, T,
17405                                              TInfo, ac, (Expr *)BitfieldWidth);
17406 
17407   if (II) {
17408     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17409                                            ForVisibleRedeclaration);
17410     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17411         && !isa<TagDecl>(PrevDecl)) {
17412       Diag(Loc, diag::err_duplicate_member) << II;
17413       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17414       NewID->setInvalidDecl();
17415     }
17416   }
17417 
17418   // Process attributes attached to the ivar.
17419   ProcessDeclAttributes(S, NewID, D);
17420 
17421   if (D.isInvalidType())
17422     NewID->setInvalidDecl();
17423 
17424   // In ARC, infer 'retaining' for ivars of retainable type.
17425   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17426     NewID->setInvalidDecl();
17427 
17428   if (D.getDeclSpec().isModulePrivateSpecified())
17429     NewID->setModulePrivate();
17430 
17431   if (II) {
17432     // FIXME: When interfaces are DeclContexts, we'll need to add
17433     // these to the interface.
17434     S->AddDecl(NewID);
17435     IdResolver.AddDecl(NewID);
17436   }
17437 
17438   if (LangOpts.ObjCRuntime.isNonFragile() &&
17439       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17440     Diag(Loc, diag::warn_ivars_in_interface);
17441 
17442   return NewID;
17443 }
17444 
17445 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17446 /// class and class extensions. For every class \@interface and class
17447 /// extension \@interface, if the last ivar is a bitfield of any type,
17448 /// then add an implicit `char :0` ivar to the end of that interface.
17449 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17450                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17451   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17452     return;
17453 
17454   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17455   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17456 
17457   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17458     return;
17459   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17460   if (!ID) {
17461     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17462       if (!CD->IsClassExtension())
17463         return;
17464     }
17465     // No need to add this to end of @implementation.
17466     else
17467       return;
17468   }
17469   // All conditions are met. Add a new bitfield to the tail end of ivars.
17470   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17471   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17472 
17473   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17474                               DeclLoc, DeclLoc, nullptr,
17475                               Context.CharTy,
17476                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17477                                                                DeclLoc),
17478                               ObjCIvarDecl::Private, BW,
17479                               true);
17480   AllIvarDecls.push_back(Ivar);
17481 }
17482 
17483 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17484                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17485                        SourceLocation RBrac,
17486                        const ParsedAttributesView &Attrs) {
17487   assert(EnclosingDecl && "missing record or interface decl");
17488 
17489   // If this is an Objective-C @implementation or category and we have
17490   // new fields here we should reset the layout of the interface since
17491   // it will now change.
17492   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17493     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17494     switch (DC->getKind()) {
17495     default: break;
17496     case Decl::ObjCCategory:
17497       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17498       break;
17499     case Decl::ObjCImplementation:
17500       Context.
17501         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17502       break;
17503     }
17504   }
17505 
17506   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17507   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17508 
17509   // Start counting up the number of named members; make sure to include
17510   // members of anonymous structs and unions in the total.
17511   unsigned NumNamedMembers = 0;
17512   if (Record) {
17513     for (const auto *I : Record->decls()) {
17514       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17515         if (IFD->getDeclName())
17516           ++NumNamedMembers;
17517     }
17518   }
17519 
17520   // Verify that all the fields are okay.
17521   SmallVector<FieldDecl*, 32> RecFields;
17522 
17523   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17524        i != end; ++i) {
17525     FieldDecl *FD = cast<FieldDecl>(*i);
17526 
17527     // Get the type for the field.
17528     const Type *FDTy = FD->getType().getTypePtr();
17529 
17530     if (!FD->isAnonymousStructOrUnion()) {
17531       // Remember all fields written by the user.
17532       RecFields.push_back(FD);
17533     }
17534 
17535     // If the field is already invalid for some reason, don't emit more
17536     // diagnostics about it.
17537     if (FD->isInvalidDecl()) {
17538       EnclosingDecl->setInvalidDecl();
17539       continue;
17540     }
17541 
17542     // C99 6.7.2.1p2:
17543     //   A structure or union shall not contain a member with
17544     //   incomplete or function type (hence, a structure shall not
17545     //   contain an instance of itself, but may contain a pointer to
17546     //   an instance of itself), except that the last member of a
17547     //   structure with more than one named member may have incomplete
17548     //   array type; such a structure (and any union containing,
17549     //   possibly recursively, a member that is such a structure)
17550     //   shall not be a member of a structure or an element of an
17551     //   array.
17552     bool IsLastField = (i + 1 == Fields.end());
17553     if (FDTy->isFunctionType()) {
17554       // Field declared as a function.
17555       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17556         << FD->getDeclName();
17557       FD->setInvalidDecl();
17558       EnclosingDecl->setInvalidDecl();
17559       continue;
17560     } else if (FDTy->isIncompleteArrayType() &&
17561                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17562       if (Record) {
17563         // Flexible array member.
17564         // Microsoft and g++ is more permissive regarding flexible array.
17565         // It will accept flexible array in union and also
17566         // as the sole element of a struct/class.
17567         unsigned DiagID = 0;
17568         if (!Record->isUnion() && !IsLastField) {
17569           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17570             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17571           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17572           FD->setInvalidDecl();
17573           EnclosingDecl->setInvalidDecl();
17574           continue;
17575         } else if (Record->isUnion())
17576           DiagID = getLangOpts().MicrosoftExt
17577                        ? diag::ext_flexible_array_union_ms
17578                        : getLangOpts().CPlusPlus
17579                              ? diag::ext_flexible_array_union_gnu
17580                              : diag::err_flexible_array_union;
17581         else if (NumNamedMembers < 1)
17582           DiagID = getLangOpts().MicrosoftExt
17583                        ? diag::ext_flexible_array_empty_aggregate_ms
17584                        : getLangOpts().CPlusPlus
17585                              ? diag::ext_flexible_array_empty_aggregate_gnu
17586                              : diag::err_flexible_array_empty_aggregate;
17587 
17588         if (DiagID)
17589           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17590                                           << Record->getTagKind();
17591         // While the layout of types that contain virtual bases is not specified
17592         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17593         // virtual bases after the derived members.  This would make a flexible
17594         // array member declared at the end of an object not adjacent to the end
17595         // of the type.
17596         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17597           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17598               << FD->getDeclName() << Record->getTagKind();
17599         if (!getLangOpts().C99)
17600           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17601             << FD->getDeclName() << Record->getTagKind();
17602 
17603         // If the element type has a non-trivial destructor, we would not
17604         // implicitly destroy the elements, so disallow it for now.
17605         //
17606         // FIXME: GCC allows this. We should probably either implicitly delete
17607         // the destructor of the containing class, or just allow this.
17608         QualType BaseElem = Context.getBaseElementType(FD->getType());
17609         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17610           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17611             << FD->getDeclName() << FD->getType();
17612           FD->setInvalidDecl();
17613           EnclosingDecl->setInvalidDecl();
17614           continue;
17615         }
17616         // Okay, we have a legal flexible array member at the end of the struct.
17617         Record->setHasFlexibleArrayMember(true);
17618       } else {
17619         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17620         // unless they are followed by another ivar. That check is done
17621         // elsewhere, after synthesized ivars are known.
17622       }
17623     } else if (!FDTy->isDependentType() &&
17624                RequireCompleteSizedType(
17625                    FD->getLocation(), FD->getType(),
17626                    diag::err_field_incomplete_or_sizeless)) {
17627       // Incomplete type
17628       FD->setInvalidDecl();
17629       EnclosingDecl->setInvalidDecl();
17630       continue;
17631     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17632       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17633         // A type which contains a flexible array member is considered to be a
17634         // flexible array member.
17635         Record->setHasFlexibleArrayMember(true);
17636         if (!Record->isUnion()) {
17637           // If this is a struct/class and this is not the last element, reject
17638           // it.  Note that GCC supports variable sized arrays in the middle of
17639           // structures.
17640           if (!IsLastField)
17641             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17642               << FD->getDeclName() << FD->getType();
17643           else {
17644             // We support flexible arrays at the end of structs in
17645             // other structs as an extension.
17646             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17647               << FD->getDeclName();
17648           }
17649         }
17650       }
17651       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17652           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17653                                  diag::err_abstract_type_in_decl,
17654                                  AbstractIvarType)) {
17655         // Ivars can not have abstract class types
17656         FD->setInvalidDecl();
17657       }
17658       if (Record && FDTTy->getDecl()->hasObjectMember())
17659         Record->setHasObjectMember(true);
17660       if (Record && FDTTy->getDecl()->hasVolatileMember())
17661         Record->setHasVolatileMember(true);
17662     } else if (FDTy->isObjCObjectType()) {
17663       /// A field cannot be an Objective-c object
17664       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17665         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17666       QualType T = Context.getObjCObjectPointerType(FD->getType());
17667       FD->setType(T);
17668     } else if (Record && Record->isUnion() &&
17669                FD->getType().hasNonTrivialObjCLifetime() &&
17670                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17671                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17672                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17673                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17674       // For backward compatibility, fields of C unions declared in system
17675       // headers that have non-trivial ObjC ownership qualifications are marked
17676       // as unavailable unless the qualifier is explicit and __strong. This can
17677       // break ABI compatibility between programs compiled with ARC and MRR, but
17678       // is a better option than rejecting programs using those unions under
17679       // ARC.
17680       FD->addAttr(UnavailableAttr::CreateImplicit(
17681           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17682           FD->getLocation()));
17683     } else if (getLangOpts().ObjC &&
17684                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17685                !Record->hasObjectMember()) {
17686       if (FD->getType()->isObjCObjectPointerType() ||
17687           FD->getType().isObjCGCStrong())
17688         Record->setHasObjectMember(true);
17689       else if (Context.getAsArrayType(FD->getType())) {
17690         QualType BaseType = Context.getBaseElementType(FD->getType());
17691         if (BaseType->isRecordType() &&
17692             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17693           Record->setHasObjectMember(true);
17694         else if (BaseType->isObjCObjectPointerType() ||
17695                  BaseType.isObjCGCStrong())
17696                Record->setHasObjectMember(true);
17697       }
17698     }
17699 
17700     if (Record && !getLangOpts().CPlusPlus &&
17701         !shouldIgnoreForRecordTriviality(FD)) {
17702       QualType FT = FD->getType();
17703       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17704         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17705         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17706             Record->isUnion())
17707           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17708       }
17709       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17710       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17711         Record->setNonTrivialToPrimitiveCopy(true);
17712         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17713           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17714       }
17715       if (FT.isDestructedType()) {
17716         Record->setNonTrivialToPrimitiveDestroy(true);
17717         Record->setParamDestroyedInCallee(true);
17718         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17719           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17720       }
17721 
17722       if (const auto *RT = FT->getAs<RecordType>()) {
17723         if (RT->getDecl()->getArgPassingRestrictions() ==
17724             RecordDecl::APK_CanNeverPassInRegs)
17725           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17726       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17727         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17728     }
17729 
17730     if (Record && FD->getType().isVolatileQualified())
17731       Record->setHasVolatileMember(true);
17732     // Keep track of the number of named members.
17733     if (FD->getIdentifier())
17734       ++NumNamedMembers;
17735   }
17736 
17737   // Okay, we successfully defined 'Record'.
17738   if (Record) {
17739     bool Completed = false;
17740     if (CXXRecord) {
17741       if (!CXXRecord->isInvalidDecl()) {
17742         // Set access bits correctly on the directly-declared conversions.
17743         for (CXXRecordDecl::conversion_iterator
17744                I = CXXRecord->conversion_begin(),
17745                E = CXXRecord->conversion_end(); I != E; ++I)
17746           I.setAccess((*I)->getAccess());
17747       }
17748 
17749       // Add any implicitly-declared members to this class.
17750       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17751 
17752       if (!CXXRecord->isDependentType()) {
17753         if (!CXXRecord->isInvalidDecl()) {
17754           // If we have virtual base classes, we may end up finding multiple
17755           // final overriders for a given virtual function. Check for this
17756           // problem now.
17757           if (CXXRecord->getNumVBases()) {
17758             CXXFinalOverriderMap FinalOverriders;
17759             CXXRecord->getFinalOverriders(FinalOverriders);
17760 
17761             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17762                                              MEnd = FinalOverriders.end();
17763                  M != MEnd; ++M) {
17764               for (OverridingMethods::iterator SO = M->second.begin(),
17765                                             SOEnd = M->second.end();
17766                    SO != SOEnd; ++SO) {
17767                 assert(SO->second.size() > 0 &&
17768                        "Virtual function without overriding functions?");
17769                 if (SO->second.size() == 1)
17770                   continue;
17771 
17772                 // C++ [class.virtual]p2:
17773                 //   In a derived class, if a virtual member function of a base
17774                 //   class subobject has more than one final overrider the
17775                 //   program is ill-formed.
17776                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17777                   << (const NamedDecl *)M->first << Record;
17778                 Diag(M->first->getLocation(),
17779                      diag::note_overridden_virtual_function);
17780                 for (OverridingMethods::overriding_iterator
17781                           OM = SO->second.begin(),
17782                        OMEnd = SO->second.end();
17783                      OM != OMEnd; ++OM)
17784                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17785                     << (const NamedDecl *)M->first << OM->Method->getParent();
17786 
17787                 Record->setInvalidDecl();
17788               }
17789             }
17790             CXXRecord->completeDefinition(&FinalOverriders);
17791             Completed = true;
17792           }
17793         }
17794       }
17795     }
17796 
17797     if (!Completed)
17798       Record->completeDefinition();
17799 
17800     // Handle attributes before checking the layout.
17801     ProcessDeclAttributeList(S, Record, Attrs);
17802 
17803     // We may have deferred checking for a deleted destructor. Check now.
17804     if (CXXRecord) {
17805       auto *Dtor = CXXRecord->getDestructor();
17806       if (Dtor && Dtor->isImplicit() &&
17807           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17808         CXXRecord->setImplicitDestructorIsDeleted();
17809         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17810       }
17811     }
17812 
17813     if (Record->hasAttrs()) {
17814       CheckAlignasUnderalignment(Record);
17815 
17816       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17817         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17818                                            IA->getRange(), IA->getBestCase(),
17819                                            IA->getInheritanceModel());
17820     }
17821 
17822     // Check if the structure/union declaration is a type that can have zero
17823     // size in C. For C this is a language extension, for C++ it may cause
17824     // compatibility problems.
17825     bool CheckForZeroSize;
17826     if (!getLangOpts().CPlusPlus) {
17827       CheckForZeroSize = true;
17828     } else {
17829       // For C++ filter out types that cannot be referenced in C code.
17830       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17831       CheckForZeroSize =
17832           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17833           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17834           CXXRecord->isCLike();
17835     }
17836     if (CheckForZeroSize) {
17837       bool ZeroSize = true;
17838       bool IsEmpty = true;
17839       unsigned NonBitFields = 0;
17840       for (RecordDecl::field_iterator I = Record->field_begin(),
17841                                       E = Record->field_end();
17842            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17843         IsEmpty = false;
17844         if (I->isUnnamedBitfield()) {
17845           if (!I->isZeroLengthBitField(Context))
17846             ZeroSize = false;
17847         } else {
17848           ++NonBitFields;
17849           QualType FieldType = I->getType();
17850           if (FieldType->isIncompleteType() ||
17851               !Context.getTypeSizeInChars(FieldType).isZero())
17852             ZeroSize = false;
17853         }
17854       }
17855 
17856       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17857       // allowed in C++, but warn if its declaration is inside
17858       // extern "C" block.
17859       if (ZeroSize) {
17860         Diag(RecLoc, getLangOpts().CPlusPlus ?
17861                          diag::warn_zero_size_struct_union_in_extern_c :
17862                          diag::warn_zero_size_struct_union_compat)
17863           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17864       }
17865 
17866       // Structs without named members are extension in C (C99 6.7.2.1p7),
17867       // but are accepted by GCC.
17868       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17869         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17870                                diag::ext_no_named_members_in_struct_union)
17871           << Record->isUnion();
17872       }
17873     }
17874   } else {
17875     ObjCIvarDecl **ClsFields =
17876       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17877     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17878       ID->setEndOfDefinitionLoc(RBrac);
17879       // Add ivar's to class's DeclContext.
17880       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17881         ClsFields[i]->setLexicalDeclContext(ID);
17882         ID->addDecl(ClsFields[i]);
17883       }
17884       // Must enforce the rule that ivars in the base classes may not be
17885       // duplicates.
17886       if (ID->getSuperClass())
17887         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17888     } else if (ObjCImplementationDecl *IMPDecl =
17889                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17890       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17891       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17892         // Ivar declared in @implementation never belongs to the implementation.
17893         // Only it is in implementation's lexical context.
17894         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17895       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17896       IMPDecl->setIvarLBraceLoc(LBrac);
17897       IMPDecl->setIvarRBraceLoc(RBrac);
17898     } else if (ObjCCategoryDecl *CDecl =
17899                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17900       // case of ivars in class extension; all other cases have been
17901       // reported as errors elsewhere.
17902       // FIXME. Class extension does not have a LocEnd field.
17903       // CDecl->setLocEnd(RBrac);
17904       // Add ivar's to class extension's DeclContext.
17905       // Diagnose redeclaration of private ivars.
17906       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17907       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17908         if (IDecl) {
17909           if (const ObjCIvarDecl *ClsIvar =
17910               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17911             Diag(ClsFields[i]->getLocation(),
17912                  diag::err_duplicate_ivar_declaration);
17913             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17914             continue;
17915           }
17916           for (const auto *Ext : IDecl->known_extensions()) {
17917             if (const ObjCIvarDecl *ClsExtIvar
17918                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17919               Diag(ClsFields[i]->getLocation(),
17920                    diag::err_duplicate_ivar_declaration);
17921               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17922               continue;
17923             }
17924           }
17925         }
17926         ClsFields[i]->setLexicalDeclContext(CDecl);
17927         CDecl->addDecl(ClsFields[i]);
17928       }
17929       CDecl->setIvarLBraceLoc(LBrac);
17930       CDecl->setIvarRBraceLoc(RBrac);
17931     }
17932   }
17933 }
17934 
17935 /// Determine whether the given integral value is representable within
17936 /// the given type T.
17937 static bool isRepresentableIntegerValue(ASTContext &Context,
17938                                         llvm::APSInt &Value,
17939                                         QualType T) {
17940   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17941          "Integral type required!");
17942   unsigned BitWidth = Context.getIntWidth(T);
17943 
17944   if (Value.isUnsigned() || Value.isNonNegative()) {
17945     if (T->isSignedIntegerOrEnumerationType())
17946       --BitWidth;
17947     return Value.getActiveBits() <= BitWidth;
17948   }
17949   return Value.getMinSignedBits() <= BitWidth;
17950 }
17951 
17952 // Given an integral type, return the next larger integral type
17953 // (or a NULL type of no such type exists).
17954 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17955   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17956   // enum checking below.
17957   assert((T->isIntegralType(Context) ||
17958          T->isEnumeralType()) && "Integral type required!");
17959   const unsigned NumTypes = 4;
17960   QualType SignedIntegralTypes[NumTypes] = {
17961     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17962   };
17963   QualType UnsignedIntegralTypes[NumTypes] = {
17964     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17965     Context.UnsignedLongLongTy
17966   };
17967 
17968   unsigned BitWidth = Context.getTypeSize(T);
17969   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17970                                                         : UnsignedIntegralTypes;
17971   for (unsigned I = 0; I != NumTypes; ++I)
17972     if (Context.getTypeSize(Types[I]) > BitWidth)
17973       return Types[I];
17974 
17975   return QualType();
17976 }
17977 
17978 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17979                                           EnumConstantDecl *LastEnumConst,
17980                                           SourceLocation IdLoc,
17981                                           IdentifierInfo *Id,
17982                                           Expr *Val) {
17983   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17984   llvm::APSInt EnumVal(IntWidth);
17985   QualType EltTy;
17986 
17987   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17988     Val = nullptr;
17989 
17990   if (Val)
17991     Val = DefaultLvalueConversion(Val).get();
17992 
17993   if (Val) {
17994     if (Enum->isDependentType() || Val->isTypeDependent() ||
17995         Val->containsErrors())
17996       EltTy = Context.DependentTy;
17997     else {
17998       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17999       // underlying type, but do allow it in all other contexts.
18000       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18001         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18002         // constant-expression in the enumerator-definition shall be a converted
18003         // constant expression of the underlying type.
18004         EltTy = Enum->getIntegerType();
18005         ExprResult Converted =
18006           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18007                                            CCEK_Enumerator);
18008         if (Converted.isInvalid())
18009           Val = nullptr;
18010         else
18011           Val = Converted.get();
18012       } else if (!Val->isValueDependent() &&
18013                  !(Val =
18014                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18015                            .get())) {
18016         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18017       } else {
18018         if (Enum->isComplete()) {
18019           EltTy = Enum->getIntegerType();
18020 
18021           // In Obj-C and Microsoft mode, require the enumeration value to be
18022           // representable in the underlying type of the enumeration. In C++11,
18023           // we perform a non-narrowing conversion as part of converted constant
18024           // expression checking.
18025           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18026             if (Context.getTargetInfo()
18027                     .getTriple()
18028                     .isWindowsMSVCEnvironment()) {
18029               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18030             } else {
18031               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18032             }
18033           }
18034 
18035           // Cast to the underlying type.
18036           Val = ImpCastExprToType(Val, EltTy,
18037                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18038                                                          : CK_IntegralCast)
18039                     .get();
18040         } else if (getLangOpts().CPlusPlus) {
18041           // C++11 [dcl.enum]p5:
18042           //   If the underlying type is not fixed, the type of each enumerator
18043           //   is the type of its initializing value:
18044           //     - If an initializer is specified for an enumerator, the
18045           //       initializing value has the same type as the expression.
18046           EltTy = Val->getType();
18047         } else {
18048           // C99 6.7.2.2p2:
18049           //   The expression that defines the value of an enumeration constant
18050           //   shall be an integer constant expression that has a value
18051           //   representable as an int.
18052 
18053           // Complain if the value is not representable in an int.
18054           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18055             Diag(IdLoc, diag::ext_enum_value_not_int)
18056               << toString(EnumVal, 10) << Val->getSourceRange()
18057               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18058           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18059             // Force the type of the expression to 'int'.
18060             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18061           }
18062           EltTy = Val->getType();
18063         }
18064       }
18065     }
18066   }
18067 
18068   if (!Val) {
18069     if (Enum->isDependentType())
18070       EltTy = Context.DependentTy;
18071     else if (!LastEnumConst) {
18072       // C++0x [dcl.enum]p5:
18073       //   If the underlying type is not fixed, the type of each enumerator
18074       //   is the type of its initializing value:
18075       //     - If no initializer is specified for the first enumerator, the
18076       //       initializing value has an unspecified integral type.
18077       //
18078       // GCC uses 'int' for its unspecified integral type, as does
18079       // C99 6.7.2.2p3.
18080       if (Enum->isFixed()) {
18081         EltTy = Enum->getIntegerType();
18082       }
18083       else {
18084         EltTy = Context.IntTy;
18085       }
18086     } else {
18087       // Assign the last value + 1.
18088       EnumVal = LastEnumConst->getInitVal();
18089       ++EnumVal;
18090       EltTy = LastEnumConst->getType();
18091 
18092       // Check for overflow on increment.
18093       if (EnumVal < LastEnumConst->getInitVal()) {
18094         // C++0x [dcl.enum]p5:
18095         //   If the underlying type is not fixed, the type of each enumerator
18096         //   is the type of its initializing value:
18097         //
18098         //     - Otherwise the type of the initializing value is the same as
18099         //       the type of the initializing value of the preceding enumerator
18100         //       unless the incremented value is not representable in that type,
18101         //       in which case the type is an unspecified integral type
18102         //       sufficient to contain the incremented value. If no such type
18103         //       exists, the program is ill-formed.
18104         QualType T = getNextLargerIntegralType(Context, EltTy);
18105         if (T.isNull() || Enum->isFixed()) {
18106           // There is no integral type larger enough to represent this
18107           // value. Complain, then allow the value to wrap around.
18108           EnumVal = LastEnumConst->getInitVal();
18109           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18110           ++EnumVal;
18111           if (Enum->isFixed())
18112             // When the underlying type is fixed, this is ill-formed.
18113             Diag(IdLoc, diag::err_enumerator_wrapped)
18114               << toString(EnumVal, 10)
18115               << EltTy;
18116           else
18117             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18118               << toString(EnumVal, 10);
18119         } else {
18120           EltTy = T;
18121         }
18122 
18123         // Retrieve the last enumerator's value, extent that type to the
18124         // type that is supposed to be large enough to represent the incremented
18125         // value, then increment.
18126         EnumVal = LastEnumConst->getInitVal();
18127         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18128         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18129         ++EnumVal;
18130 
18131         // If we're not in C++, diagnose the overflow of enumerator values,
18132         // which in C99 means that the enumerator value is not representable in
18133         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18134         // permits enumerator values that are representable in some larger
18135         // integral type.
18136         if (!getLangOpts().CPlusPlus && !T.isNull())
18137           Diag(IdLoc, diag::warn_enum_value_overflow);
18138       } else if (!getLangOpts().CPlusPlus &&
18139                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18140         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18141         Diag(IdLoc, diag::ext_enum_value_not_int)
18142           << toString(EnumVal, 10) << 1;
18143       }
18144     }
18145   }
18146 
18147   if (!EltTy->isDependentType()) {
18148     // Make the enumerator value match the signedness and size of the
18149     // enumerator's type.
18150     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18151     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18152   }
18153 
18154   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18155                                   Val, EnumVal);
18156 }
18157 
18158 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18159                                                 SourceLocation IILoc) {
18160   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18161       !getLangOpts().CPlusPlus)
18162     return SkipBodyInfo();
18163 
18164   // We have an anonymous enum definition. Look up the first enumerator to
18165   // determine if we should merge the definition with an existing one and
18166   // skip the body.
18167   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18168                                          forRedeclarationInCurContext());
18169   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18170   if (!PrevECD)
18171     return SkipBodyInfo();
18172 
18173   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18174   NamedDecl *Hidden;
18175   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18176     SkipBodyInfo Skip;
18177     Skip.Previous = Hidden;
18178     return Skip;
18179   }
18180 
18181   return SkipBodyInfo();
18182 }
18183 
18184 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18185                               SourceLocation IdLoc, IdentifierInfo *Id,
18186                               const ParsedAttributesView &Attrs,
18187                               SourceLocation EqualLoc, Expr *Val) {
18188   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18189   EnumConstantDecl *LastEnumConst =
18190     cast_or_null<EnumConstantDecl>(lastEnumConst);
18191 
18192   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18193   // we find one that is.
18194   S = getNonFieldDeclScope(S);
18195 
18196   // Verify that there isn't already something declared with this name in this
18197   // scope.
18198   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18199   LookupName(R, S);
18200   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18201 
18202   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18203     // Maybe we will complain about the shadowed template parameter.
18204     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18205     // Just pretend that we didn't see the previous declaration.
18206     PrevDecl = nullptr;
18207   }
18208 
18209   // C++ [class.mem]p15:
18210   // If T is the name of a class, then each of the following shall have a name
18211   // different from T:
18212   // - every enumerator of every member of class T that is an unscoped
18213   // enumerated type
18214   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18215     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18216                             DeclarationNameInfo(Id, IdLoc));
18217 
18218   EnumConstantDecl *New =
18219     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18220   if (!New)
18221     return nullptr;
18222 
18223   if (PrevDecl) {
18224     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18225       // Check for other kinds of shadowing not already handled.
18226       CheckShadow(New, PrevDecl, R);
18227     }
18228 
18229     // When in C++, we may get a TagDecl with the same name; in this case the
18230     // enum constant will 'hide' the tag.
18231     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18232            "Received TagDecl when not in C++!");
18233     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18234       if (isa<EnumConstantDecl>(PrevDecl))
18235         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18236       else
18237         Diag(IdLoc, diag::err_redefinition) << Id;
18238       notePreviousDefinition(PrevDecl, IdLoc);
18239       return nullptr;
18240     }
18241   }
18242 
18243   // Process attributes.
18244   ProcessDeclAttributeList(S, New, Attrs);
18245   AddPragmaAttributes(S, New);
18246 
18247   // Register this decl in the current scope stack.
18248   New->setAccess(TheEnumDecl->getAccess());
18249   PushOnScopeChains(New, S);
18250 
18251   ActOnDocumentableDecl(New);
18252 
18253   return New;
18254 }
18255 
18256 // Returns true when the enum initial expression does not trigger the
18257 // duplicate enum warning.  A few common cases are exempted as follows:
18258 // Element2 = Element1
18259 // Element2 = Element1 + 1
18260 // Element2 = Element1 - 1
18261 // Where Element2 and Element1 are from the same enum.
18262 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18263   Expr *InitExpr = ECD->getInitExpr();
18264   if (!InitExpr)
18265     return true;
18266   InitExpr = InitExpr->IgnoreImpCasts();
18267 
18268   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18269     if (!BO->isAdditiveOp())
18270       return true;
18271     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18272     if (!IL)
18273       return true;
18274     if (IL->getValue() != 1)
18275       return true;
18276 
18277     InitExpr = BO->getLHS();
18278   }
18279 
18280   // This checks if the elements are from the same enum.
18281   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18282   if (!DRE)
18283     return true;
18284 
18285   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18286   if (!EnumConstant)
18287     return true;
18288 
18289   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18290       Enum)
18291     return true;
18292 
18293   return false;
18294 }
18295 
18296 // Emits a warning when an element is implicitly set a value that
18297 // a previous element has already been set to.
18298 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18299                                         EnumDecl *Enum, QualType EnumType) {
18300   // Avoid anonymous enums
18301   if (!Enum->getIdentifier())
18302     return;
18303 
18304   // Only check for small enums.
18305   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18306     return;
18307 
18308   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18309     return;
18310 
18311   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18312   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18313 
18314   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18315 
18316   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18317   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18318 
18319   // Use int64_t as a key to avoid needing special handling for map keys.
18320   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18321     llvm::APSInt Val = D->getInitVal();
18322     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18323   };
18324 
18325   DuplicatesVector DupVector;
18326   ValueToVectorMap EnumMap;
18327 
18328   // Populate the EnumMap with all values represented by enum constants without
18329   // an initializer.
18330   for (auto *Element : Elements) {
18331     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18332 
18333     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18334     // this constant.  Skip this enum since it may be ill-formed.
18335     if (!ECD) {
18336       return;
18337     }
18338 
18339     // Constants with initalizers are handled in the next loop.
18340     if (ECD->getInitExpr())
18341       continue;
18342 
18343     // Duplicate values are handled in the next loop.
18344     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18345   }
18346 
18347   if (EnumMap.size() == 0)
18348     return;
18349 
18350   // Create vectors for any values that has duplicates.
18351   for (auto *Element : Elements) {
18352     // The last loop returned if any constant was null.
18353     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18354     if (!ValidDuplicateEnum(ECD, Enum))
18355       continue;
18356 
18357     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18358     if (Iter == EnumMap.end())
18359       continue;
18360 
18361     DeclOrVector& Entry = Iter->second;
18362     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18363       // Ensure constants are different.
18364       if (D == ECD)
18365         continue;
18366 
18367       // Create new vector and push values onto it.
18368       auto Vec = std::make_unique<ECDVector>();
18369       Vec->push_back(D);
18370       Vec->push_back(ECD);
18371 
18372       // Update entry to point to the duplicates vector.
18373       Entry = Vec.get();
18374 
18375       // Store the vector somewhere we can consult later for quick emission of
18376       // diagnostics.
18377       DupVector.emplace_back(std::move(Vec));
18378       continue;
18379     }
18380 
18381     ECDVector *Vec = Entry.get<ECDVector*>();
18382     // Make sure constants are not added more than once.
18383     if (*Vec->begin() == ECD)
18384       continue;
18385 
18386     Vec->push_back(ECD);
18387   }
18388 
18389   // Emit diagnostics.
18390   for (const auto &Vec : DupVector) {
18391     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18392 
18393     // Emit warning for one enum constant.
18394     auto *FirstECD = Vec->front();
18395     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18396       << FirstECD << toString(FirstECD->getInitVal(), 10)
18397       << FirstECD->getSourceRange();
18398 
18399     // Emit one note for each of the remaining enum constants with
18400     // the same value.
18401     for (auto *ECD : llvm::drop_begin(*Vec))
18402       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18403         << ECD << toString(ECD->getInitVal(), 10)
18404         << ECD->getSourceRange();
18405   }
18406 }
18407 
18408 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18409                              bool AllowMask) const {
18410   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18411   assert(ED->isCompleteDefinition() && "expected enum definition");
18412 
18413   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18414   llvm::APInt &FlagBits = R.first->second;
18415 
18416   if (R.second) {
18417     for (auto *E : ED->enumerators()) {
18418       const auto &EVal = E->getInitVal();
18419       // Only single-bit enumerators introduce new flag values.
18420       if (EVal.isPowerOf2())
18421         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18422     }
18423   }
18424 
18425   // A value is in a flag enum if either its bits are a subset of the enum's
18426   // flag bits (the first condition) or we are allowing masks and the same is
18427   // true of its complement (the second condition). When masks are allowed, we
18428   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18429   //
18430   // While it's true that any value could be used as a mask, the assumption is
18431   // that a mask will have all of the insignificant bits set. Anything else is
18432   // likely a logic error.
18433   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18434   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18435 }
18436 
18437 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18438                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18439                          const ParsedAttributesView &Attrs) {
18440   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18441   QualType EnumType = Context.getTypeDeclType(Enum);
18442 
18443   ProcessDeclAttributeList(S, Enum, Attrs);
18444 
18445   if (Enum->isDependentType()) {
18446     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18447       EnumConstantDecl *ECD =
18448         cast_or_null<EnumConstantDecl>(Elements[i]);
18449       if (!ECD) continue;
18450 
18451       ECD->setType(EnumType);
18452     }
18453 
18454     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18455     return;
18456   }
18457 
18458   // TODO: If the result value doesn't fit in an int, it must be a long or long
18459   // long value.  ISO C does not support this, but GCC does as an extension,
18460   // emit a warning.
18461   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18462   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18463   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18464 
18465   // Verify that all the values are okay, compute the size of the values, and
18466   // reverse the list.
18467   unsigned NumNegativeBits = 0;
18468   unsigned NumPositiveBits = 0;
18469 
18470   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18471     EnumConstantDecl *ECD =
18472       cast_or_null<EnumConstantDecl>(Elements[i]);
18473     if (!ECD) continue;  // Already issued a diagnostic.
18474 
18475     const llvm::APSInt &InitVal = ECD->getInitVal();
18476 
18477     // Keep track of the size of positive and negative values.
18478     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18479       NumPositiveBits = std::max(NumPositiveBits,
18480                                  (unsigned)InitVal.getActiveBits());
18481     else
18482       NumNegativeBits = std::max(NumNegativeBits,
18483                                  (unsigned)InitVal.getMinSignedBits());
18484   }
18485 
18486   // Figure out the type that should be used for this enum.
18487   QualType BestType;
18488   unsigned BestWidth;
18489 
18490   // C++0x N3000 [conv.prom]p3:
18491   //   An rvalue of an unscoped enumeration type whose underlying
18492   //   type is not fixed can be converted to an rvalue of the first
18493   //   of the following types that can represent all the values of
18494   //   the enumeration: int, unsigned int, long int, unsigned long
18495   //   int, long long int, or unsigned long long int.
18496   // C99 6.4.4.3p2:
18497   //   An identifier declared as an enumeration constant has type int.
18498   // The C99 rule is modified by a gcc extension
18499   QualType BestPromotionType;
18500 
18501   bool Packed = Enum->hasAttr<PackedAttr>();
18502   // -fshort-enums is the equivalent to specifying the packed attribute on all
18503   // enum definitions.
18504   if (LangOpts.ShortEnums)
18505     Packed = true;
18506 
18507   // If the enum already has a type because it is fixed or dictated by the
18508   // target, promote that type instead of analyzing the enumerators.
18509   if (Enum->isComplete()) {
18510     BestType = Enum->getIntegerType();
18511     if (BestType->isPromotableIntegerType())
18512       BestPromotionType = Context.getPromotedIntegerType(BestType);
18513     else
18514       BestPromotionType = BestType;
18515 
18516     BestWidth = Context.getIntWidth(BestType);
18517   }
18518   else if (NumNegativeBits) {
18519     // If there is a negative value, figure out the smallest integer type (of
18520     // int/long/longlong) that fits.
18521     // If it's packed, check also if it fits a char or a short.
18522     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18523       BestType = Context.SignedCharTy;
18524       BestWidth = CharWidth;
18525     } else if (Packed && NumNegativeBits <= ShortWidth &&
18526                NumPositiveBits < ShortWidth) {
18527       BestType = Context.ShortTy;
18528       BestWidth = ShortWidth;
18529     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18530       BestType = Context.IntTy;
18531       BestWidth = IntWidth;
18532     } else {
18533       BestWidth = Context.getTargetInfo().getLongWidth();
18534 
18535       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18536         BestType = Context.LongTy;
18537       } else {
18538         BestWidth = Context.getTargetInfo().getLongLongWidth();
18539 
18540         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18541           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18542         BestType = Context.LongLongTy;
18543       }
18544     }
18545     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18546   } else {
18547     // If there is no negative value, figure out the smallest type that fits
18548     // all of the enumerator values.
18549     // If it's packed, check also if it fits a char or a short.
18550     if (Packed && NumPositiveBits <= CharWidth) {
18551       BestType = Context.UnsignedCharTy;
18552       BestPromotionType = Context.IntTy;
18553       BestWidth = CharWidth;
18554     } else if (Packed && NumPositiveBits <= ShortWidth) {
18555       BestType = Context.UnsignedShortTy;
18556       BestPromotionType = Context.IntTy;
18557       BestWidth = ShortWidth;
18558     } else if (NumPositiveBits <= IntWidth) {
18559       BestType = Context.UnsignedIntTy;
18560       BestWidth = IntWidth;
18561       BestPromotionType
18562         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18563                            ? Context.UnsignedIntTy : Context.IntTy;
18564     } else if (NumPositiveBits <=
18565                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18566       BestType = Context.UnsignedLongTy;
18567       BestPromotionType
18568         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18569                            ? Context.UnsignedLongTy : Context.LongTy;
18570     } else {
18571       BestWidth = Context.getTargetInfo().getLongLongWidth();
18572       assert(NumPositiveBits <= BestWidth &&
18573              "How could an initializer get larger than ULL?");
18574       BestType = Context.UnsignedLongLongTy;
18575       BestPromotionType
18576         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18577                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18578     }
18579   }
18580 
18581   // Loop over all of the enumerator constants, changing their types to match
18582   // the type of the enum if needed.
18583   for (auto *D : Elements) {
18584     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18585     if (!ECD) continue;  // Already issued a diagnostic.
18586 
18587     // Standard C says the enumerators have int type, but we allow, as an
18588     // extension, the enumerators to be larger than int size.  If each
18589     // enumerator value fits in an int, type it as an int, otherwise type it the
18590     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18591     // that X has type 'int', not 'unsigned'.
18592 
18593     // Determine whether the value fits into an int.
18594     llvm::APSInt InitVal = ECD->getInitVal();
18595 
18596     // If it fits into an integer type, force it.  Otherwise force it to match
18597     // the enum decl type.
18598     QualType NewTy;
18599     unsigned NewWidth;
18600     bool NewSign;
18601     if (!getLangOpts().CPlusPlus &&
18602         !Enum->isFixed() &&
18603         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18604       NewTy = Context.IntTy;
18605       NewWidth = IntWidth;
18606       NewSign = true;
18607     } else if (ECD->getType() == BestType) {
18608       // Already the right type!
18609       if (getLangOpts().CPlusPlus)
18610         // C++ [dcl.enum]p4: Following the closing brace of an
18611         // enum-specifier, each enumerator has the type of its
18612         // enumeration.
18613         ECD->setType(EnumType);
18614       continue;
18615     } else {
18616       NewTy = BestType;
18617       NewWidth = BestWidth;
18618       NewSign = BestType->isSignedIntegerOrEnumerationType();
18619     }
18620 
18621     // Adjust the APSInt value.
18622     InitVal = InitVal.extOrTrunc(NewWidth);
18623     InitVal.setIsSigned(NewSign);
18624     ECD->setInitVal(InitVal);
18625 
18626     // Adjust the Expr initializer and type.
18627     if (ECD->getInitExpr() &&
18628         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18629       ECD->setInitExpr(ImplicitCastExpr::Create(
18630           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18631           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18632     if (getLangOpts().CPlusPlus)
18633       // C++ [dcl.enum]p4: Following the closing brace of an
18634       // enum-specifier, each enumerator has the type of its
18635       // enumeration.
18636       ECD->setType(EnumType);
18637     else
18638       ECD->setType(NewTy);
18639   }
18640 
18641   Enum->completeDefinition(BestType, BestPromotionType,
18642                            NumPositiveBits, NumNegativeBits);
18643 
18644   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18645 
18646   if (Enum->isClosedFlag()) {
18647     for (Decl *D : Elements) {
18648       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18649       if (!ECD) continue;  // Already issued a diagnostic.
18650 
18651       llvm::APSInt InitVal = ECD->getInitVal();
18652       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18653           !IsValueInFlagEnum(Enum, InitVal, true))
18654         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18655           << ECD << Enum;
18656     }
18657   }
18658 
18659   // Now that the enum type is defined, ensure it's not been underaligned.
18660   if (Enum->hasAttrs())
18661     CheckAlignasUnderalignment(Enum);
18662 }
18663 
18664 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18665                                   SourceLocation StartLoc,
18666                                   SourceLocation EndLoc) {
18667   StringLiteral *AsmString = cast<StringLiteral>(expr);
18668 
18669   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18670                                                    AsmString, StartLoc,
18671                                                    EndLoc);
18672   CurContext->addDecl(New);
18673   return New;
18674 }
18675 
18676 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18677                                       IdentifierInfo* AliasName,
18678                                       SourceLocation PragmaLoc,
18679                                       SourceLocation NameLoc,
18680                                       SourceLocation AliasNameLoc) {
18681   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18682                                          LookupOrdinaryName);
18683   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18684                            AttributeCommonInfo::AS_Pragma);
18685   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18686       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18687 
18688   // If a declaration that:
18689   // 1) declares a function or a variable
18690   // 2) has external linkage
18691   // already exists, add a label attribute to it.
18692   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18693     if (isDeclExternC(PrevDecl))
18694       PrevDecl->addAttr(Attr);
18695     else
18696       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18697           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18698   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18699   } else
18700     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18701 }
18702 
18703 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18704                              SourceLocation PragmaLoc,
18705                              SourceLocation NameLoc) {
18706   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18707 
18708   if (PrevDecl) {
18709     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18710   } else {
18711     (void)WeakUndeclaredIdentifiers.insert(
18712       std::pair<IdentifierInfo*,WeakInfo>
18713         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18714   }
18715 }
18716 
18717 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18718                                 IdentifierInfo* AliasName,
18719                                 SourceLocation PragmaLoc,
18720                                 SourceLocation NameLoc,
18721                                 SourceLocation AliasNameLoc) {
18722   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18723                                     LookupOrdinaryName);
18724   WeakInfo W = WeakInfo(Name, NameLoc);
18725 
18726   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18727     if (!PrevDecl->hasAttr<AliasAttr>())
18728       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18729         DeclApplyPragmaWeak(TUScope, ND, W);
18730   } else {
18731     (void)WeakUndeclaredIdentifiers.insert(
18732       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18733   }
18734 }
18735 
18736 Decl *Sema::getObjCDeclContext() const {
18737   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18738 }
18739 
18740 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18741                                                      bool Final) {
18742   assert(FD && "Expected non-null FunctionDecl");
18743 
18744   // SYCL functions can be template, so we check if they have appropriate
18745   // attribute prior to checking if it is a template.
18746   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18747     return FunctionEmissionStatus::Emitted;
18748 
18749   // Templates are emitted when they're instantiated.
18750   if (FD->isDependentContext())
18751     return FunctionEmissionStatus::TemplateDiscarded;
18752 
18753   // Check whether this function is an externally visible definition.
18754   auto IsEmittedForExternalSymbol = [this, FD]() {
18755     // We have to check the GVA linkage of the function's *definition* -- if we
18756     // only have a declaration, we don't know whether or not the function will
18757     // be emitted, because (say) the definition could include "inline".
18758     FunctionDecl *Def = FD->getDefinition();
18759 
18760     return Def && !isDiscardableGVALinkage(
18761                       getASTContext().GetGVALinkageForFunction(Def));
18762   };
18763 
18764   if (LangOpts.OpenMPIsDevice) {
18765     // In OpenMP device mode we will not emit host only functions, or functions
18766     // we don't need due to their linkage.
18767     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18768         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18769     // DevTy may be changed later by
18770     //  #pragma omp declare target to(*) device_type(*).
18771     // Therefore DevTy having no value does not imply host. The emission status
18772     // will be checked again at the end of compilation unit with Final = true.
18773     if (DevTy.hasValue())
18774       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18775         return FunctionEmissionStatus::OMPDiscarded;
18776     // If we have an explicit value for the device type, or we are in a target
18777     // declare context, we need to emit all extern and used symbols.
18778     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18779       if (IsEmittedForExternalSymbol())
18780         return FunctionEmissionStatus::Emitted;
18781     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18782     // we'll omit it.
18783     if (Final)
18784       return FunctionEmissionStatus::OMPDiscarded;
18785   } else if (LangOpts.OpenMP > 45) {
18786     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18787     // function. In 5.0, no_host was introduced which might cause a function to
18788     // be ommitted.
18789     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18790         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18791     if (DevTy.hasValue())
18792       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18793         return FunctionEmissionStatus::OMPDiscarded;
18794   }
18795 
18796   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18797     return FunctionEmissionStatus::Emitted;
18798 
18799   if (LangOpts.CUDA) {
18800     // When compiling for device, host functions are never emitted.  Similarly,
18801     // when compiling for host, device and global functions are never emitted.
18802     // (Technically, we do emit a host-side stub for global functions, but this
18803     // doesn't count for our purposes here.)
18804     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18805     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18806       return FunctionEmissionStatus::CUDADiscarded;
18807     if (!LangOpts.CUDAIsDevice &&
18808         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18809       return FunctionEmissionStatus::CUDADiscarded;
18810 
18811     if (IsEmittedForExternalSymbol())
18812       return FunctionEmissionStatus::Emitted;
18813   }
18814 
18815   // Otherwise, the function is known-emitted if it's in our set of
18816   // known-emitted functions.
18817   return FunctionEmissionStatus::Unknown;
18818 }
18819 
18820 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18821   // Host-side references to a __global__ function refer to the stub, so the
18822   // function itself is never emitted and therefore should not be marked.
18823   // If we have host fn calls kernel fn calls host+device, the HD function
18824   // does not get instantiated on the host. We model this by omitting at the
18825   // call to the kernel from the callgraph. This ensures that, when compiling
18826   // for host, only HD functions actually called from the host get marked as
18827   // known-emitted.
18828   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18829          IdentifyCUDATarget(Callee) == CFT_Global;
18830 }
18831