1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
110     return std::make_unique<TypeNameValidatorCCC>(*this);
111   }
112 
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119 
120 } // end anonymous namespace
121 
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146 
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154 
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157 
158   default:
159     break;
160   }
161 
162   return false;
163 }
164 
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172 
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229 
230   return FoundTypeDecl;
231 }
232 
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251 
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256 
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261 
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264 
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272 
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293 
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302 
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316 
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321 
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327 
328       return nullptr;
329     }
330 
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335 
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347 
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360 
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369 
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419 
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430 
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442 
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453 
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459 
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464 
465   assert(IIDecl && "Didn't find decl");
466 
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479 
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481 
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493 
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499 
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509 
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519 
520   return ParsedType::make(T);
521 }
522 
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539 
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554 
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559 
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577 
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586 
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588 
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594 
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602 
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623 
624   return DeclSpec::TST_unspecified;
625 }
626 
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645 
646     const Type *Ty = SS->getScopeRep()->getAsType();
647 
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656 
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668 
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706 
707       if (!CanRecover)
708         return;
709 
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723 
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738 
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741 
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754 
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766 
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772 
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776 
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780 
781   return false;
782 }
783 
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796 
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800 
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804 
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808 
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813 
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818 
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823 
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837 
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840 
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847 
848 Sema::NameClassification
849 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
850                    SourceLocation NameLoc, const Token &NextToken,
851                    bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
922       // In C++20 onwards, this could be an ADL-only call to a function
923       // template, and we're required to assume that this is a template name.
924       //
925       // FIXME: Find a way to still do typo correction in this case.
926       TemplateName Template =
927           Context.getAssumedTemplateName(NameInfo.getName());
928       return NameClassification::UndeclaredTemplate(Template);
929     }
930 
931     // In C, we first see whether there is a tag type by the same name, in
932     // which case it's likely that the user just forgot to write "enum",
933     // "struct", or "union".
934     if (!getLangOpts().CPlusPlus && !SecondTry &&
935         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
936       break;
937     }
938 
939     // Perform typo correction to determine if there is another name that is
940     // close to this name.
941     if (!SecondTry && CCC) {
942       SecondTry = true;
943       if (TypoCorrection Corrected =
944               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
945                           &SS, *CCC, CTK_ErrorRecovery)) {
946         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
947         unsigned QualifiedDiag = diag::err_no_member_suggest;
948 
949         NamedDecl *FirstDecl = Corrected.getFoundDecl();
950         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
951         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
952             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
953           UnqualifiedDiag = diag::err_no_template_suggest;
954           QualifiedDiag = diag::err_no_member_template_suggest;
955         } else if (UnderlyingFirstDecl &&
956                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
957                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
958                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
959           UnqualifiedDiag = diag::err_unknown_typename_suggest;
960           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
961         }
962 
963         if (SS.isEmpty()) {
964           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
965         } else {// FIXME: is this even reachable? Test it.
966           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
967           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
968                                   Name->getName().equals(CorrectedStr);
969           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
970                                     << Name << computeDeclContext(SS, false)
971                                     << DroppedSpecifier << SS.getRange());
972         }
973 
974         // Update the name, so that the caller has the new name.
975         Name = Corrected.getCorrectionAsIdentifierInfo();
976 
977         // Typo correction corrected to a keyword.
978         if (Corrected.isKeyword())
979           return Name;
980 
981         // Also update the LookupResult...
982         // FIXME: This should probably go away at some point
983         Result.clear();
984         Result.setLookupName(Corrected.getCorrection());
985         if (FirstDecl)
986           Result.addDecl(FirstDecl);
987 
988         // If we found an Objective-C instance variable, let
989         // LookupInObjCMethod build the appropriate expression to
990         // reference the ivar.
991         // FIXME: This is a gross hack.
992         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
993           Result.clear();
994           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
995           return E;
996         }
997 
998         goto Corrected;
999       }
1000     }
1001 
1002     // We failed to correct; just fall through and let the parser deal with it.
1003     Result.suppressDiagnostics();
1004     return NameClassification::Unknown();
1005 
1006   case LookupResult::NotFoundInCurrentInstantiation: {
1007     // We performed name lookup into the current instantiation, and there were
1008     // dependent bases, so we treat this result the same way as any other
1009     // dependent nested-name-specifier.
1010 
1011     // C++ [temp.res]p2:
1012     //   A name used in a template declaration or definition and that is
1013     //   dependent on a template-parameter is assumed not to name a type
1014     //   unless the applicable name lookup finds a type name or the name is
1015     //   qualified by the keyword typename.
1016     //
1017     // FIXME: If the next token is '<', we might want to ask the parser to
1018     // perform some heroics to see if we actually have a
1019     // template-argument-list, which would indicate a missing 'template'
1020     // keyword here.
1021     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1022                                       NameInfo, IsAddressOfOperand,
1023                                       /*TemplateArgs=*/nullptr);
1024   }
1025 
1026   case LookupResult::Found:
1027   case LookupResult::FoundOverloaded:
1028   case LookupResult::FoundUnresolvedValue:
1029     break;
1030 
1031   case LookupResult::Ambiguous:
1032     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1033         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1034                                       /*AllowDependent=*/false)) {
1035       // C++ [temp.local]p3:
1036       //   A lookup that finds an injected-class-name (10.2) can result in an
1037       //   ambiguity in certain cases (for example, if it is found in more than
1038       //   one base class). If all of the injected-class-names that are found
1039       //   refer to specializations of the same class template, and if the name
1040       //   is followed by a template-argument-list, the reference refers to the
1041       //   class template itself and not a specialization thereof, and is not
1042       //   ambiguous.
1043       //
1044       // This filtering can make an ambiguous result into an unambiguous one,
1045       // so try again after filtering out template names.
1046       FilterAcceptableTemplateNames(Result);
1047       if (!Result.isAmbiguous()) {
1048         IsFilteredTemplateName = true;
1049         break;
1050       }
1051     }
1052 
1053     // Diagnose the ambiguity and return an error.
1054     return NameClassification::Error();
1055   }
1056 
1057   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058       (IsFilteredTemplateName ||
1059        hasAnyAcceptableTemplateNames(
1060            Result, /*AllowFunctionTemplates=*/true,
1061            /*AllowDependent=*/false,
1062            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1063                getLangOpts().CPlusPlus2a))) {
1064     // C++ [temp.names]p3:
1065     //   After name lookup (3.4) finds that a name is a template-name or that
1066     //   an operator-function-id or a literal- operator-id refers to a set of
1067     //   overloaded functions any member of which is a function template if
1068     //   this is followed by a <, the < is always taken as the delimiter of a
1069     //   template-argument-list and never as the less-than operator.
1070     // C++2a [temp.names]p2:
1071     //   A name is also considered to refer to a template if it is an
1072     //   unqualified-id followed by a < and name lookup finds either one
1073     //   or more functions or finds nothing.
1074     if (!IsFilteredTemplateName)
1075       FilterAcceptableTemplateNames(Result);
1076 
1077     bool IsFunctionTemplate;
1078     bool IsVarTemplate;
1079     TemplateName Template;
1080     if (Result.end() - Result.begin() > 1) {
1081       IsFunctionTemplate = true;
1082       Template = Context.getOverloadedTemplateName(Result.begin(),
1083                                                    Result.end());
1084     } else if (!Result.empty()) {
1085       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1086           *Result.begin(), /*AllowFunctionTemplates=*/true,
1087           /*AllowDependent=*/false));
1088       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1089       IsVarTemplate = isa<VarTemplateDecl>(TD);
1090 
1091       if (SS.isSet() && !SS.isInvalid())
1092         Template =
1093             Context.getQualifiedTemplateName(SS.getScopeRep(),
1094                                              /*TemplateKeyword=*/false, TD);
1095       else
1096         Template = TemplateName(TD);
1097     } else {
1098       // All results were non-template functions. This is a function template
1099       // name.
1100       IsFunctionTemplate = true;
1101       Template = Context.getAssumedTemplateName(NameInfo.getName());
1102     }
1103 
1104     if (IsFunctionTemplate) {
1105       // Function templates always go through overload resolution, at which
1106       // point we'll perform the various checks (e.g., accessibility) we need
1107       // to based on which function we selected.
1108       Result.suppressDiagnostics();
1109 
1110       return NameClassification::FunctionTemplate(Template);
1111     }
1112 
1113     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1114                          : NameClassification::TypeTemplate(Template);
1115   }
1116 
1117   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1118   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1119     DiagnoseUseOfDecl(Type, NameLoc);
1120     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1121     QualType T = Context.getTypeDeclType(Type);
1122     if (SS.isNotEmpty())
1123       return buildNestedType(*this, SS, T, NameLoc);
1124     return ParsedType::make(T);
1125   }
1126 
1127   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1128   if (!Class) {
1129     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1130     if (ObjCCompatibleAliasDecl *Alias =
1131             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1132       Class = Alias->getClassInterface();
1133   }
1134 
1135   if (Class) {
1136     DiagnoseUseOfDecl(Class, NameLoc);
1137 
1138     if (NextToken.is(tok::period)) {
1139       // Interface. <something> is parsed as a property reference expression.
1140       // Just return "unknown" as a fall-through for now.
1141       Result.suppressDiagnostics();
1142       return NameClassification::Unknown();
1143     }
1144 
1145     QualType T = Context.getObjCInterfaceType(Class);
1146     return ParsedType::make(T);
1147   }
1148 
1149   // We can have a type template here if we're classifying a template argument.
1150   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1151       !isa<VarTemplateDecl>(FirstDecl))
1152     return NameClassification::TypeTemplate(
1153         TemplateName(cast<TemplateDecl>(FirstDecl)));
1154 
1155   // Check for a tag type hidden by a non-type decl in a few cases where it
1156   // seems likely a type is wanted instead of the non-type that was found.
1157   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1158   if ((NextToken.is(tok::identifier) ||
1159        (NextIsOp &&
1160         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1161       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1162     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1163     DiagnoseUseOfDecl(Type, NameLoc);
1164     QualType T = Context.getTypeDeclType(Type);
1165     if (SS.isNotEmpty())
1166       return buildNestedType(*this, SS, T, NameLoc);
1167     return ParsedType::make(T);
1168   }
1169 
1170   if (FirstDecl->isCXXClassMember())
1171     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1172                                            nullptr, S);
1173 
1174   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1175   return BuildDeclarationNameExpr(SS, Result, ADL);
1176 }
1177 
1178 Sema::TemplateNameKindForDiagnostics
1179 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1180   auto *TD = Name.getAsTemplateDecl();
1181   if (!TD)
1182     return TemplateNameKindForDiagnostics::DependentTemplate;
1183   if (isa<ClassTemplateDecl>(TD))
1184     return TemplateNameKindForDiagnostics::ClassTemplate;
1185   if (isa<FunctionTemplateDecl>(TD))
1186     return TemplateNameKindForDiagnostics::FunctionTemplate;
1187   if (isa<VarTemplateDecl>(TD))
1188     return TemplateNameKindForDiagnostics::VarTemplate;
1189   if (isa<TypeAliasTemplateDecl>(TD))
1190     return TemplateNameKindForDiagnostics::AliasTemplate;
1191   if (isa<TemplateTemplateParmDecl>(TD))
1192     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1193   if (isa<ConceptDecl>(TD))
1194     return TemplateNameKindForDiagnostics::Concept;
1195   return TemplateNameKindForDiagnostics::DependentTemplate;
1196 }
1197 
1198 // Determines the context to return to after temporarily entering a
1199 // context.  This depends in an unnecessarily complicated way on the
1200 // exact ordering of callbacks from the parser.
1201 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1202 
1203   // Functions defined inline within classes aren't parsed until we've
1204   // finished parsing the top-level class, so the top-level class is
1205   // the context we'll need to return to.
1206   // A Lambda call operator whose parent is a class must not be treated
1207   // as an inline member function.  A Lambda can be used legally
1208   // either as an in-class member initializer or a default argument.  These
1209   // are parsed once the class has been marked complete and so the containing
1210   // context would be the nested class (when the lambda is defined in one);
1211   // If the class is not complete, then the lambda is being used in an
1212   // ill-formed fashion (such as to specify the width of a bit-field, or
1213   // in an array-bound) - in which case we still want to return the
1214   // lexically containing DC (which could be a nested class).
1215   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1216     DC = DC->getLexicalParent();
1217 
1218     // A function not defined within a class will always return to its
1219     // lexical context.
1220     if (!isa<CXXRecordDecl>(DC))
1221       return DC;
1222 
1223     // A C++ inline method/friend is parsed *after* the topmost class
1224     // it was declared in is fully parsed ("complete");  the topmost
1225     // class is the context we need to return to.
1226     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1227       DC = RD;
1228 
1229     // Return the declaration context of the topmost class the inline method is
1230     // declared in.
1231     return DC;
1232   }
1233 
1234   return DC->getLexicalParent();
1235 }
1236 
1237 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1238   assert(getContainingDC(DC) == CurContext &&
1239       "The next DeclContext should be lexically contained in the current one.");
1240   CurContext = DC;
1241   S->setEntity(DC);
1242 }
1243 
1244 void Sema::PopDeclContext() {
1245   assert(CurContext && "DeclContext imbalance!");
1246 
1247   CurContext = getContainingDC(CurContext);
1248   assert(CurContext && "Popped translation unit!");
1249 }
1250 
1251 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1252                                                                     Decl *D) {
1253   // Unlike PushDeclContext, the context to which we return is not necessarily
1254   // the containing DC of TD, because the new context will be some pre-existing
1255   // TagDecl definition instead of a fresh one.
1256   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1257   CurContext = cast<TagDecl>(D)->getDefinition();
1258   assert(CurContext && "skipping definition of undefined tag");
1259   // Start lookups from the parent of the current context; we don't want to look
1260   // into the pre-existing complete definition.
1261   S->setEntity(CurContext->getLookupParent());
1262   return Result;
1263 }
1264 
1265 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1266   CurContext = static_cast<decltype(CurContext)>(Context);
1267 }
1268 
1269 /// EnterDeclaratorContext - Used when we must lookup names in the context
1270 /// of a declarator's nested name specifier.
1271 ///
1272 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1273   // C++0x [basic.lookup.unqual]p13:
1274   //   A name used in the definition of a static data member of class
1275   //   X (after the qualified-id of the static member) is looked up as
1276   //   if the name was used in a member function of X.
1277   // C++0x [basic.lookup.unqual]p14:
1278   //   If a variable member of a namespace is defined outside of the
1279   //   scope of its namespace then any name used in the definition of
1280   //   the variable member (after the declarator-id) is looked up as
1281   //   if the definition of the variable member occurred in its
1282   //   namespace.
1283   // Both of these imply that we should push a scope whose context
1284   // is the semantic context of the declaration.  We can't use
1285   // PushDeclContext here because that context is not necessarily
1286   // lexically contained in the current context.  Fortunately,
1287   // the containing scope should have the appropriate information.
1288 
1289   assert(!S->getEntity() && "scope already has entity");
1290 
1291 #ifndef NDEBUG
1292   Scope *Ancestor = S->getParent();
1293   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1294   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1295 #endif
1296 
1297   CurContext = DC;
1298   S->setEntity(DC);
1299 }
1300 
1301 void Sema::ExitDeclaratorContext(Scope *S) {
1302   assert(S->getEntity() == CurContext && "Context imbalance!");
1303 
1304   // Switch back to the lexical context.  The safety of this is
1305   // enforced by an assert in EnterDeclaratorContext.
1306   Scope *Ancestor = S->getParent();
1307   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1308   CurContext = Ancestor->getEntity();
1309 
1310   // We don't need to do anything with the scope, which is going to
1311   // disappear.
1312 }
1313 
1314 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1315   // We assume that the caller has already called
1316   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1317   FunctionDecl *FD = D->getAsFunction();
1318   if (!FD)
1319     return;
1320 
1321   // Same implementation as PushDeclContext, but enters the context
1322   // from the lexical parent, rather than the top-level class.
1323   assert(CurContext == FD->getLexicalParent() &&
1324     "The next DeclContext should be lexically contained in the current one.");
1325   CurContext = FD;
1326   S->setEntity(CurContext);
1327 
1328   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1329     ParmVarDecl *Param = FD->getParamDecl(P);
1330     // If the parameter has an identifier, then add it to the scope
1331     if (Param->getIdentifier()) {
1332       S->AddDecl(Param);
1333       IdResolver.AddDecl(Param);
1334     }
1335   }
1336 }
1337 
1338 void Sema::ActOnExitFunctionContext() {
1339   // Same implementation as PopDeclContext, but returns to the lexical parent,
1340   // rather than the top-level class.
1341   assert(CurContext && "DeclContext imbalance!");
1342   CurContext = CurContext->getLexicalParent();
1343   assert(CurContext && "Popped translation unit!");
1344 }
1345 
1346 /// Determine whether we allow overloading of the function
1347 /// PrevDecl with another declaration.
1348 ///
1349 /// This routine determines whether overloading is possible, not
1350 /// whether some new function is actually an overload. It will return
1351 /// true in C++ (where we can always provide overloads) or, as an
1352 /// extension, in C when the previous function is already an
1353 /// overloaded function declaration or has the "overloadable"
1354 /// attribute.
1355 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1356                                        ASTContext &Context,
1357                                        const FunctionDecl *New) {
1358   if (Context.getLangOpts().CPlusPlus)
1359     return true;
1360 
1361   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1362     return true;
1363 
1364   return Previous.getResultKind() == LookupResult::Found &&
1365          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1366           New->hasAttr<OverloadableAttr>());
1367 }
1368 
1369 /// Add this decl to the scope shadowed decl chains.
1370 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1371   // Move up the scope chain until we find the nearest enclosing
1372   // non-transparent context. The declaration will be introduced into this
1373   // scope.
1374   while (S->getEntity() && S->getEntity()->isTransparentContext())
1375     S = S->getParent();
1376 
1377   // Add scoped declarations into their context, so that they can be
1378   // found later. Declarations without a context won't be inserted
1379   // into any context.
1380   if (AddToContext)
1381     CurContext->addDecl(D);
1382 
1383   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1384   // are function-local declarations.
1385   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1386       !D->getDeclContext()->getRedeclContext()->Equals(
1387         D->getLexicalDeclContext()->getRedeclContext()) &&
1388       !D->getLexicalDeclContext()->isFunctionOrMethod())
1389     return;
1390 
1391   // Template instantiations should also not be pushed into scope.
1392   if (isa<FunctionDecl>(D) &&
1393       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1394     return;
1395 
1396   // If this replaces anything in the current scope,
1397   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1398                                IEnd = IdResolver.end();
1399   for (; I != IEnd; ++I) {
1400     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1401       S->RemoveDecl(*I);
1402       IdResolver.RemoveDecl(*I);
1403 
1404       // Should only need to replace one decl.
1405       break;
1406     }
1407   }
1408 
1409   S->AddDecl(D);
1410 
1411   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1412     // Implicitly-generated labels may end up getting generated in an order that
1413     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1414     // the label at the appropriate place in the identifier chain.
1415     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1416       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1417       if (IDC == CurContext) {
1418         if (!S->isDeclScope(*I))
1419           continue;
1420       } else if (IDC->Encloses(CurContext))
1421         break;
1422     }
1423 
1424     IdResolver.InsertDeclAfter(I, D);
1425   } else {
1426     IdResolver.AddDecl(D);
1427   }
1428 }
1429 
1430 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1431                          bool AllowInlineNamespace) {
1432   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1433 }
1434 
1435 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1436   DeclContext *TargetDC = DC->getPrimaryContext();
1437   do {
1438     if (DeclContext *ScopeDC = S->getEntity())
1439       if (ScopeDC->getPrimaryContext() == TargetDC)
1440         return S;
1441   } while ((S = S->getParent()));
1442 
1443   return nullptr;
1444 }
1445 
1446 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1447                                             DeclContext*,
1448                                             ASTContext&);
1449 
1450 /// Filters out lookup results that don't fall within the given scope
1451 /// as determined by isDeclInScope.
1452 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1453                                 bool ConsiderLinkage,
1454                                 bool AllowInlineNamespace) {
1455   LookupResult::Filter F = R.makeFilter();
1456   while (F.hasNext()) {
1457     NamedDecl *D = F.next();
1458 
1459     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1460       continue;
1461 
1462     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1463       continue;
1464 
1465     F.erase();
1466   }
1467 
1468   F.done();
1469 }
1470 
1471 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1472 /// have compatible owning modules.
1473 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1474   // FIXME: The Modules TS is not clear about how friend declarations are
1475   // to be treated. It's not meaningful to have different owning modules for
1476   // linkage in redeclarations of the same entity, so for now allow the
1477   // redeclaration and change the owning modules to match.
1478   if (New->getFriendObjectKind() &&
1479       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1480     New->setLocalOwningModule(Old->getOwningModule());
1481     makeMergedDefinitionVisible(New);
1482     return false;
1483   }
1484 
1485   Module *NewM = New->getOwningModule();
1486   Module *OldM = Old->getOwningModule();
1487 
1488   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1489     NewM = NewM->Parent;
1490   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1491     OldM = OldM->Parent;
1492 
1493   if (NewM == OldM)
1494     return false;
1495 
1496   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1497   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1498   if (NewIsModuleInterface || OldIsModuleInterface) {
1499     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1500     //   if a declaration of D [...] appears in the purview of a module, all
1501     //   other such declarations shall appear in the purview of the same module
1502     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1503       << New
1504       << NewIsModuleInterface
1505       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1506       << OldIsModuleInterface
1507       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1508     Diag(Old->getLocation(), diag::note_previous_declaration);
1509     New->setInvalidDecl();
1510     return true;
1511   }
1512 
1513   return false;
1514 }
1515 
1516 static bool isUsingDecl(NamedDecl *D) {
1517   return isa<UsingShadowDecl>(D) ||
1518          isa<UnresolvedUsingTypenameDecl>(D) ||
1519          isa<UnresolvedUsingValueDecl>(D);
1520 }
1521 
1522 /// Removes using shadow declarations from the lookup results.
1523 static void RemoveUsingDecls(LookupResult &R) {
1524   LookupResult::Filter F = R.makeFilter();
1525   while (F.hasNext())
1526     if (isUsingDecl(F.next()))
1527       F.erase();
1528 
1529   F.done();
1530 }
1531 
1532 /// Check for this common pattern:
1533 /// @code
1534 /// class S {
1535 ///   S(const S&); // DO NOT IMPLEMENT
1536 ///   void operator=(const S&); // DO NOT IMPLEMENT
1537 /// };
1538 /// @endcode
1539 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1540   // FIXME: Should check for private access too but access is set after we get
1541   // the decl here.
1542   if (D->doesThisDeclarationHaveABody())
1543     return false;
1544 
1545   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1546     return CD->isCopyConstructor();
1547   return D->isCopyAssignmentOperator();
1548 }
1549 
1550 // We need this to handle
1551 //
1552 // typedef struct {
1553 //   void *foo() { return 0; }
1554 // } A;
1555 //
1556 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1557 // for example. If 'A', foo will have external linkage. If we have '*A',
1558 // foo will have no linkage. Since we can't know until we get to the end
1559 // of the typedef, this function finds out if D might have non-external linkage.
1560 // Callers should verify at the end of the TU if it D has external linkage or
1561 // not.
1562 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1563   const DeclContext *DC = D->getDeclContext();
1564   while (!DC->isTranslationUnit()) {
1565     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1566       if (!RD->hasNameForLinkage())
1567         return true;
1568     }
1569     DC = DC->getParent();
1570   }
1571 
1572   return !D->isExternallyVisible();
1573 }
1574 
1575 // FIXME: This needs to be refactored; some other isInMainFile users want
1576 // these semantics.
1577 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1578   if (S.TUKind != TU_Complete)
1579     return false;
1580   return S.SourceMgr.isInMainFile(Loc);
1581 }
1582 
1583 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1584   assert(D);
1585 
1586   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1587     return false;
1588 
1589   // Ignore all entities declared within templates, and out-of-line definitions
1590   // of members of class templates.
1591   if (D->getDeclContext()->isDependentContext() ||
1592       D->getLexicalDeclContext()->isDependentContext())
1593     return false;
1594 
1595   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1596     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1597       return false;
1598     // A non-out-of-line declaration of a member specialization was implicitly
1599     // instantiated; it's the out-of-line declaration that we're interested in.
1600     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1601         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1602       return false;
1603 
1604     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1605       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1606         return false;
1607     } else {
1608       // 'static inline' functions are defined in headers; don't warn.
1609       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1610         return false;
1611     }
1612 
1613     if (FD->doesThisDeclarationHaveABody() &&
1614         Context.DeclMustBeEmitted(FD))
1615       return false;
1616   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1617     // Constants and utility variables are defined in headers with internal
1618     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1619     // like "inline".)
1620     if (!isMainFileLoc(*this, VD->getLocation()))
1621       return false;
1622 
1623     if (Context.DeclMustBeEmitted(VD))
1624       return false;
1625 
1626     if (VD->isStaticDataMember() &&
1627         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1628       return false;
1629     if (VD->isStaticDataMember() &&
1630         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1631         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1632       return false;
1633 
1634     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1635       return false;
1636   } else {
1637     return false;
1638   }
1639 
1640   // Only warn for unused decls internal to the translation unit.
1641   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1642   // for inline functions defined in the main source file, for instance.
1643   return mightHaveNonExternalLinkage(D);
1644 }
1645 
1646 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1647   if (!D)
1648     return;
1649 
1650   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651     const FunctionDecl *First = FD->getFirstDecl();
1652     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1653       return; // First should already be in the vector.
1654   }
1655 
1656   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1657     const VarDecl *First = VD->getFirstDecl();
1658     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1659       return; // First should already be in the vector.
1660   }
1661 
1662   if (ShouldWarnIfUnusedFileScopedDecl(D))
1663     UnusedFileScopedDecls.push_back(D);
1664 }
1665 
1666 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1667   if (D->isInvalidDecl())
1668     return false;
1669 
1670   bool Referenced = false;
1671   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1672     // For a decomposition declaration, warn if none of the bindings are
1673     // referenced, instead of if the variable itself is referenced (which
1674     // it is, by the bindings' expressions).
1675     for (auto *BD : DD->bindings()) {
1676       if (BD->isReferenced()) {
1677         Referenced = true;
1678         break;
1679       }
1680     }
1681   } else if (!D->getDeclName()) {
1682     return false;
1683   } else if (D->isReferenced() || D->isUsed()) {
1684     Referenced = true;
1685   }
1686 
1687   if (Referenced || D->hasAttr<UnusedAttr>() ||
1688       D->hasAttr<ObjCPreciseLifetimeAttr>())
1689     return false;
1690 
1691   if (isa<LabelDecl>(D))
1692     return true;
1693 
1694   // Except for labels, we only care about unused decls that are local to
1695   // functions.
1696   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1697   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1698     // For dependent types, the diagnostic is deferred.
1699     WithinFunction =
1700         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1701   if (!WithinFunction)
1702     return false;
1703 
1704   if (isa<TypedefNameDecl>(D))
1705     return true;
1706 
1707   // White-list anything that isn't a local variable.
1708   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1709     return false;
1710 
1711   // Types of valid local variables should be complete, so this should succeed.
1712   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713 
1714     // White-list anything with an __attribute__((unused)) type.
1715     const auto *Ty = VD->getType().getTypePtr();
1716 
1717     // Only look at the outermost level of typedef.
1718     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1719       if (TT->getDecl()->hasAttr<UnusedAttr>())
1720         return false;
1721     }
1722 
1723     // If we failed to complete the type for some reason, or if the type is
1724     // dependent, don't diagnose the variable.
1725     if (Ty->isIncompleteType() || Ty->isDependentType())
1726       return false;
1727 
1728     // Look at the element type to ensure that the warning behaviour is
1729     // consistent for both scalars and arrays.
1730     Ty = Ty->getBaseElementTypeUnsafe();
1731 
1732     if (const TagType *TT = Ty->getAs<TagType>()) {
1733       const TagDecl *Tag = TT->getDecl();
1734       if (Tag->hasAttr<UnusedAttr>())
1735         return false;
1736 
1737       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1738         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1739           return false;
1740 
1741         if (const Expr *Init = VD->getInit()) {
1742           if (const ExprWithCleanups *Cleanups =
1743                   dyn_cast<ExprWithCleanups>(Init))
1744             Init = Cleanups->getSubExpr();
1745           const CXXConstructExpr *Construct =
1746             dyn_cast<CXXConstructExpr>(Init);
1747           if (Construct && !Construct->isElidable()) {
1748             CXXConstructorDecl *CD = Construct->getConstructor();
1749             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1750                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1751               return false;
1752           }
1753         }
1754       }
1755     }
1756 
1757     // TODO: __attribute__((unused)) templates?
1758   }
1759 
1760   return true;
1761 }
1762 
1763 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1764                                      FixItHint &Hint) {
1765   if (isa<LabelDecl>(D)) {
1766     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1767         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1768         true);
1769     if (AfterColon.isInvalid())
1770       return;
1771     Hint = FixItHint::CreateRemoval(
1772         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1773   }
1774 }
1775 
1776 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1777   if (D->getTypeForDecl()->isDependentType())
1778     return;
1779 
1780   for (auto *TmpD : D->decls()) {
1781     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1782       DiagnoseUnusedDecl(T);
1783     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1784       DiagnoseUnusedNestedTypedefs(R);
1785   }
1786 }
1787 
1788 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1789 /// unless they are marked attr(unused).
1790 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1791   if (!ShouldDiagnoseUnusedDecl(D))
1792     return;
1793 
1794   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1795     // typedefs can be referenced later on, so the diagnostics are emitted
1796     // at end-of-translation-unit.
1797     UnusedLocalTypedefNameCandidates.insert(TD);
1798     return;
1799   }
1800 
1801   FixItHint Hint;
1802   GenerateFixForUnusedDecl(D, Context, Hint);
1803 
1804   unsigned DiagID;
1805   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1806     DiagID = diag::warn_unused_exception_param;
1807   else if (isa<LabelDecl>(D))
1808     DiagID = diag::warn_unused_label;
1809   else
1810     DiagID = diag::warn_unused_variable;
1811 
1812   Diag(D->getLocation(), DiagID) << D << Hint;
1813 }
1814 
1815 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1816   // Verify that we have no forward references left.  If so, there was a goto
1817   // or address of a label taken, but no definition of it.  Label fwd
1818   // definitions are indicated with a null substmt which is also not a resolved
1819   // MS inline assembly label name.
1820   bool Diagnose = false;
1821   if (L->isMSAsmLabel())
1822     Diagnose = !L->isResolvedMSAsmLabel();
1823   else
1824     Diagnose = L->getStmt() == nullptr;
1825   if (Diagnose)
1826     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1827 }
1828 
1829 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1830   S->mergeNRVOIntoParent();
1831 
1832   if (S->decl_empty()) return;
1833   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1834          "Scope shouldn't contain decls!");
1835 
1836   for (auto *TmpD : S->decls()) {
1837     assert(TmpD && "This decl didn't get pushed??");
1838 
1839     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1840     NamedDecl *D = cast<NamedDecl>(TmpD);
1841 
1842     // Diagnose unused variables in this scope.
1843     if (!S->hasUnrecoverableErrorOccurred()) {
1844       DiagnoseUnusedDecl(D);
1845       if (const auto *RD = dyn_cast<RecordDecl>(D))
1846         DiagnoseUnusedNestedTypedefs(RD);
1847     }
1848 
1849     if (!D->getDeclName()) continue;
1850 
1851     // If this was a forward reference to a label, verify it was defined.
1852     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1853       CheckPoppedLabel(LD, *this);
1854 
1855     // Remove this name from our lexical scope, and warn on it if we haven't
1856     // already.
1857     IdResolver.RemoveDecl(D);
1858     auto ShadowI = ShadowingDecls.find(D);
1859     if (ShadowI != ShadowingDecls.end()) {
1860       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1861         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1862             << D << FD << FD->getParent();
1863         Diag(FD->getLocation(), diag::note_previous_declaration);
1864       }
1865       ShadowingDecls.erase(ShadowI);
1866     }
1867   }
1868 }
1869 
1870 /// Look for an Objective-C class in the translation unit.
1871 ///
1872 /// \param Id The name of the Objective-C class we're looking for. If
1873 /// typo-correction fixes this name, the Id will be updated
1874 /// to the fixed name.
1875 ///
1876 /// \param IdLoc The location of the name in the translation unit.
1877 ///
1878 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1879 /// if there is no class with the given name.
1880 ///
1881 /// \returns The declaration of the named Objective-C class, or NULL if the
1882 /// class could not be found.
1883 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1884                                               SourceLocation IdLoc,
1885                                               bool DoTypoCorrection) {
1886   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1887   // creation from this context.
1888   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1889 
1890   if (!IDecl && DoTypoCorrection) {
1891     // Perform typo correction at the given location, but only if we
1892     // find an Objective-C class name.
1893     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1894     if (TypoCorrection C =
1895             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1896                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1897       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1898       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1899       Id = IDecl->getIdentifier();
1900     }
1901   }
1902   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1903   // This routine must always return a class definition, if any.
1904   if (Def && Def->getDefinition())
1905       Def = Def->getDefinition();
1906   return Def;
1907 }
1908 
1909 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1910 /// from S, where a non-field would be declared. This routine copes
1911 /// with the difference between C and C++ scoping rules in structs and
1912 /// unions. For example, the following code is well-formed in C but
1913 /// ill-formed in C++:
1914 /// @code
1915 /// struct S6 {
1916 ///   enum { BAR } e;
1917 /// };
1918 ///
1919 /// void test_S6() {
1920 ///   struct S6 a;
1921 ///   a.e = BAR;
1922 /// }
1923 /// @endcode
1924 /// For the declaration of BAR, this routine will return a different
1925 /// scope. The scope S will be the scope of the unnamed enumeration
1926 /// within S6. In C++, this routine will return the scope associated
1927 /// with S6, because the enumeration's scope is a transparent
1928 /// context but structures can contain non-field names. In C, this
1929 /// routine will return the translation unit scope, since the
1930 /// enumeration's scope is a transparent context and structures cannot
1931 /// contain non-field names.
1932 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1933   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1934          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1935          (S->isClassScope() && !getLangOpts().CPlusPlus))
1936     S = S->getParent();
1937   return S;
1938 }
1939 
1940 /// Looks up the declaration of "struct objc_super" and
1941 /// saves it for later use in building builtin declaration of
1942 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1943 /// pre-existing declaration exists no action takes place.
1944 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1945                                         IdentifierInfo *II) {
1946   if (!II->isStr("objc_msgSendSuper"))
1947     return;
1948   ASTContext &Context = ThisSema.Context;
1949 
1950   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1951                       SourceLocation(), Sema::LookupTagName);
1952   ThisSema.LookupName(Result, S);
1953   if (Result.getResultKind() == LookupResult::Found)
1954     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1955       Context.setObjCSuperType(Context.getTagDeclType(TD));
1956 }
1957 
1958 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1959                                ASTContext::GetBuiltinTypeError Error) {
1960   switch (Error) {
1961   case ASTContext::GE_None:
1962     return "";
1963   case ASTContext::GE_Missing_type:
1964     return BuiltinInfo.getHeaderName(ID);
1965   case ASTContext::GE_Missing_stdio:
1966     return "stdio.h";
1967   case ASTContext::GE_Missing_setjmp:
1968     return "setjmp.h";
1969   case ASTContext::GE_Missing_ucontext:
1970     return "ucontext.h";
1971   }
1972   llvm_unreachable("unhandled error kind");
1973 }
1974 
1975 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1976 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1977 /// if we're creating this built-in in anticipation of redeclaring the
1978 /// built-in.
1979 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1980                                      Scope *S, bool ForRedeclaration,
1981                                      SourceLocation Loc) {
1982   LookupPredefedObjCSuperType(*this, S, II);
1983 
1984   ASTContext::GetBuiltinTypeError Error;
1985   QualType R = Context.GetBuiltinType(ID, Error);
1986   if (Error) {
1987     if (!ForRedeclaration)
1988       return nullptr;
1989 
1990     // If we have a builtin without an associated type we should not emit a
1991     // warning when we were not able to find a type for it.
1992     if (Error == ASTContext::GE_Missing_type)
1993       return nullptr;
1994 
1995     // If we could not find a type for setjmp it is because the jmp_buf type was
1996     // not defined prior to the setjmp declaration.
1997     if (Error == ASTContext::GE_Missing_setjmp) {
1998       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
1999           << Context.BuiltinInfo.getName(ID);
2000       return nullptr;
2001     }
2002 
2003     // Generally, we emit a warning that the declaration requires the
2004     // appropriate header.
2005     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2006         << getHeaderName(Context.BuiltinInfo, ID, Error)
2007         << Context.BuiltinInfo.getName(ID);
2008     return nullptr;
2009   }
2010 
2011   if (!ForRedeclaration &&
2012       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2013        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2014     Diag(Loc, diag::ext_implicit_lib_function_decl)
2015         << Context.BuiltinInfo.getName(ID) << R;
2016     if (Context.BuiltinInfo.getHeaderName(ID) &&
2017         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2018       Diag(Loc, diag::note_include_header_or_declare)
2019           << Context.BuiltinInfo.getHeaderName(ID)
2020           << Context.BuiltinInfo.getName(ID);
2021   }
2022 
2023   if (R.isNull())
2024     return nullptr;
2025 
2026   DeclContext *Parent = Context.getTranslationUnitDecl();
2027   if (getLangOpts().CPlusPlus) {
2028     LinkageSpecDecl *CLinkageDecl =
2029         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2030                                 LinkageSpecDecl::lang_c, false);
2031     CLinkageDecl->setImplicit();
2032     Parent->addDecl(CLinkageDecl);
2033     Parent = CLinkageDecl;
2034   }
2035 
2036   FunctionDecl *New = FunctionDecl::Create(Context,
2037                                            Parent,
2038                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2039                                            SC_Extern,
2040                                            false,
2041                                            R->isFunctionProtoType());
2042   New->setImplicit();
2043 
2044   // Create Decl objects for each parameter, adding them to the
2045   // FunctionDecl.
2046   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2047     SmallVector<ParmVarDecl*, 16> Params;
2048     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2049       ParmVarDecl *parm =
2050           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2051                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2052                               SC_None, nullptr);
2053       parm->setScopeInfo(0, i);
2054       Params.push_back(parm);
2055     }
2056     New->setParams(Params);
2057   }
2058 
2059   AddKnownFunctionAttributes(New);
2060   RegisterLocallyScopedExternCDecl(New, S);
2061 
2062   // TUScope is the translation-unit scope to insert this function into.
2063   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2064   // relate Scopes to DeclContexts, and probably eliminate CurContext
2065   // entirely, but we're not there yet.
2066   DeclContext *SavedContext = CurContext;
2067   CurContext = Parent;
2068   PushOnScopeChains(New, TUScope);
2069   CurContext = SavedContext;
2070   return New;
2071 }
2072 
2073 /// Typedef declarations don't have linkage, but they still denote the same
2074 /// entity if their types are the same.
2075 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2076 /// isSameEntity.
2077 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2078                                                      TypedefNameDecl *Decl,
2079                                                      LookupResult &Previous) {
2080   // This is only interesting when modules are enabled.
2081   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2082     return;
2083 
2084   // Empty sets are uninteresting.
2085   if (Previous.empty())
2086     return;
2087 
2088   LookupResult::Filter Filter = Previous.makeFilter();
2089   while (Filter.hasNext()) {
2090     NamedDecl *Old = Filter.next();
2091 
2092     // Non-hidden declarations are never ignored.
2093     if (S.isVisible(Old))
2094       continue;
2095 
2096     // Declarations of the same entity are not ignored, even if they have
2097     // different linkages.
2098     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2099       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2100                                 Decl->getUnderlyingType()))
2101         continue;
2102 
2103       // If both declarations give a tag declaration a typedef name for linkage
2104       // purposes, then they declare the same entity.
2105       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2106           Decl->getAnonDeclWithTypedefName())
2107         continue;
2108     }
2109 
2110     Filter.erase();
2111   }
2112 
2113   Filter.done();
2114 }
2115 
2116 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2117   QualType OldType;
2118   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2119     OldType = OldTypedef->getUnderlyingType();
2120   else
2121     OldType = Context.getTypeDeclType(Old);
2122   QualType NewType = New->getUnderlyingType();
2123 
2124   if (NewType->isVariablyModifiedType()) {
2125     // Must not redefine a typedef with a variably-modified type.
2126     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2127     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2128       << Kind << NewType;
2129     if (Old->getLocation().isValid())
2130       notePreviousDefinition(Old, New->getLocation());
2131     New->setInvalidDecl();
2132     return true;
2133   }
2134 
2135   if (OldType != NewType &&
2136       !OldType->isDependentType() &&
2137       !NewType->isDependentType() &&
2138       !Context.hasSameType(OldType, NewType)) {
2139     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2140     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2141       << Kind << NewType << OldType;
2142     if (Old->getLocation().isValid())
2143       notePreviousDefinition(Old, New->getLocation());
2144     New->setInvalidDecl();
2145     return true;
2146   }
2147   return false;
2148 }
2149 
2150 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2151 /// same name and scope as a previous declaration 'Old'.  Figure out
2152 /// how to resolve this situation, merging decls or emitting
2153 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2154 ///
2155 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2156                                 LookupResult &OldDecls) {
2157   // If the new decl is known invalid already, don't bother doing any
2158   // merging checks.
2159   if (New->isInvalidDecl()) return;
2160 
2161   // Allow multiple definitions for ObjC built-in typedefs.
2162   // FIXME: Verify the underlying types are equivalent!
2163   if (getLangOpts().ObjC) {
2164     const IdentifierInfo *TypeID = New->getIdentifier();
2165     switch (TypeID->getLength()) {
2166     default: break;
2167     case 2:
2168       {
2169         if (!TypeID->isStr("id"))
2170           break;
2171         QualType T = New->getUnderlyingType();
2172         if (!T->isPointerType())
2173           break;
2174         if (!T->isVoidPointerType()) {
2175           QualType PT = T->getAs<PointerType>()->getPointeeType();
2176           if (!PT->isStructureType())
2177             break;
2178         }
2179         Context.setObjCIdRedefinitionType(T);
2180         // Install the built-in type for 'id', ignoring the current definition.
2181         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2182         return;
2183       }
2184     case 5:
2185       if (!TypeID->isStr("Class"))
2186         break;
2187       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2188       // Install the built-in type for 'Class', ignoring the current definition.
2189       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2190       return;
2191     case 3:
2192       if (!TypeID->isStr("SEL"))
2193         break;
2194       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2195       // Install the built-in type for 'SEL', ignoring the current definition.
2196       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2197       return;
2198     }
2199     // Fall through - the typedef name was not a builtin type.
2200   }
2201 
2202   // Verify the old decl was also a type.
2203   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2204   if (!Old) {
2205     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2206       << New->getDeclName();
2207 
2208     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2209     if (OldD->getLocation().isValid())
2210       notePreviousDefinition(OldD, New->getLocation());
2211 
2212     return New->setInvalidDecl();
2213   }
2214 
2215   // If the old declaration is invalid, just give up here.
2216   if (Old->isInvalidDecl())
2217     return New->setInvalidDecl();
2218 
2219   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2220     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2221     auto *NewTag = New->getAnonDeclWithTypedefName();
2222     NamedDecl *Hidden = nullptr;
2223     if (OldTag && NewTag &&
2224         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2225         !hasVisibleDefinition(OldTag, &Hidden)) {
2226       // There is a definition of this tag, but it is not visible. Use it
2227       // instead of our tag.
2228       New->setTypeForDecl(OldTD->getTypeForDecl());
2229       if (OldTD->isModed())
2230         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2231                                     OldTD->getUnderlyingType());
2232       else
2233         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2234 
2235       // Make the old tag definition visible.
2236       makeMergedDefinitionVisible(Hidden);
2237 
2238       // If this was an unscoped enumeration, yank all of its enumerators
2239       // out of the scope.
2240       if (isa<EnumDecl>(NewTag)) {
2241         Scope *EnumScope = getNonFieldDeclScope(S);
2242         for (auto *D : NewTag->decls()) {
2243           auto *ED = cast<EnumConstantDecl>(D);
2244           assert(EnumScope->isDeclScope(ED));
2245           EnumScope->RemoveDecl(ED);
2246           IdResolver.RemoveDecl(ED);
2247           ED->getLexicalDeclContext()->removeDecl(ED);
2248         }
2249       }
2250     }
2251   }
2252 
2253   // If the typedef types are not identical, reject them in all languages and
2254   // with any extensions enabled.
2255   if (isIncompatibleTypedef(Old, New))
2256     return;
2257 
2258   // The types match.  Link up the redeclaration chain and merge attributes if
2259   // the old declaration was a typedef.
2260   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2261     New->setPreviousDecl(Typedef);
2262     mergeDeclAttributes(New, Old);
2263   }
2264 
2265   if (getLangOpts().MicrosoftExt)
2266     return;
2267 
2268   if (getLangOpts().CPlusPlus) {
2269     // C++ [dcl.typedef]p2:
2270     //   In a given non-class scope, a typedef specifier can be used to
2271     //   redefine the name of any type declared in that scope to refer
2272     //   to the type to which it already refers.
2273     if (!isa<CXXRecordDecl>(CurContext))
2274       return;
2275 
2276     // C++0x [dcl.typedef]p4:
2277     //   In a given class scope, a typedef specifier can be used to redefine
2278     //   any class-name declared in that scope that is not also a typedef-name
2279     //   to refer to the type to which it already refers.
2280     //
2281     // This wording came in via DR424, which was a correction to the
2282     // wording in DR56, which accidentally banned code like:
2283     //
2284     //   struct S {
2285     //     typedef struct A { } A;
2286     //   };
2287     //
2288     // in the C++03 standard. We implement the C++0x semantics, which
2289     // allow the above but disallow
2290     //
2291     //   struct S {
2292     //     typedef int I;
2293     //     typedef int I;
2294     //   };
2295     //
2296     // since that was the intent of DR56.
2297     if (!isa<TypedefNameDecl>(Old))
2298       return;
2299 
2300     Diag(New->getLocation(), diag::err_redefinition)
2301       << New->getDeclName();
2302     notePreviousDefinition(Old, New->getLocation());
2303     return New->setInvalidDecl();
2304   }
2305 
2306   // Modules always permit redefinition of typedefs, as does C11.
2307   if (getLangOpts().Modules || getLangOpts().C11)
2308     return;
2309 
2310   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2311   // is normally mapped to an error, but can be controlled with
2312   // -Wtypedef-redefinition.  If either the original or the redefinition is
2313   // in a system header, don't emit this for compatibility with GCC.
2314   if (getDiagnostics().getSuppressSystemWarnings() &&
2315       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2316       (Old->isImplicit() ||
2317        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2318        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2319     return;
2320 
2321   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2322     << New->getDeclName();
2323   notePreviousDefinition(Old, New->getLocation());
2324 }
2325 
2326 /// DeclhasAttr - returns true if decl Declaration already has the target
2327 /// attribute.
2328 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2329   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2330   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2331   for (const auto *i : D->attrs())
2332     if (i->getKind() == A->getKind()) {
2333       if (Ann) {
2334         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2335           return true;
2336         continue;
2337       }
2338       // FIXME: Don't hardcode this check
2339       if (OA && isa<OwnershipAttr>(i))
2340         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2341       return true;
2342     }
2343 
2344   return false;
2345 }
2346 
2347 static bool isAttributeTargetADefinition(Decl *D) {
2348   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2349     return VD->isThisDeclarationADefinition();
2350   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2351     return TD->isCompleteDefinition() || TD->isBeingDefined();
2352   return true;
2353 }
2354 
2355 /// Merge alignment attributes from \p Old to \p New, taking into account the
2356 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2357 ///
2358 /// \return \c true if any attributes were added to \p New.
2359 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2360   // Look for alignas attributes on Old, and pick out whichever attribute
2361   // specifies the strictest alignment requirement.
2362   AlignedAttr *OldAlignasAttr = nullptr;
2363   AlignedAttr *OldStrictestAlignAttr = nullptr;
2364   unsigned OldAlign = 0;
2365   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2366     // FIXME: We have no way of representing inherited dependent alignments
2367     // in a case like:
2368     //   template<int A, int B> struct alignas(A) X;
2369     //   template<int A, int B> struct alignas(B) X {};
2370     // For now, we just ignore any alignas attributes which are not on the
2371     // definition in such a case.
2372     if (I->isAlignmentDependent())
2373       return false;
2374 
2375     if (I->isAlignas())
2376       OldAlignasAttr = I;
2377 
2378     unsigned Align = I->getAlignment(S.Context);
2379     if (Align > OldAlign) {
2380       OldAlign = Align;
2381       OldStrictestAlignAttr = I;
2382     }
2383   }
2384 
2385   // Look for alignas attributes on New.
2386   AlignedAttr *NewAlignasAttr = nullptr;
2387   unsigned NewAlign = 0;
2388   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2389     if (I->isAlignmentDependent())
2390       return false;
2391 
2392     if (I->isAlignas())
2393       NewAlignasAttr = I;
2394 
2395     unsigned Align = I->getAlignment(S.Context);
2396     if (Align > NewAlign)
2397       NewAlign = Align;
2398   }
2399 
2400   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2401     // Both declarations have 'alignas' attributes. We require them to match.
2402     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2403     // fall short. (If two declarations both have alignas, they must both match
2404     // every definition, and so must match each other if there is a definition.)
2405 
2406     // If either declaration only contains 'alignas(0)' specifiers, then it
2407     // specifies the natural alignment for the type.
2408     if (OldAlign == 0 || NewAlign == 0) {
2409       QualType Ty;
2410       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2411         Ty = VD->getType();
2412       else
2413         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2414 
2415       if (OldAlign == 0)
2416         OldAlign = S.Context.getTypeAlign(Ty);
2417       if (NewAlign == 0)
2418         NewAlign = S.Context.getTypeAlign(Ty);
2419     }
2420 
2421     if (OldAlign != NewAlign) {
2422       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2423         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2424         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2425       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2426     }
2427   }
2428 
2429   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2430     // C++11 [dcl.align]p6:
2431     //   if any declaration of an entity has an alignment-specifier,
2432     //   every defining declaration of that entity shall specify an
2433     //   equivalent alignment.
2434     // C11 6.7.5/7:
2435     //   If the definition of an object does not have an alignment
2436     //   specifier, any other declaration of that object shall also
2437     //   have no alignment specifier.
2438     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2439       << OldAlignasAttr;
2440     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2441       << OldAlignasAttr;
2442   }
2443 
2444   bool AnyAdded = false;
2445 
2446   // Ensure we have an attribute representing the strictest alignment.
2447   if (OldAlign > NewAlign) {
2448     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2449     Clone->setInherited(true);
2450     New->addAttr(Clone);
2451     AnyAdded = true;
2452   }
2453 
2454   // Ensure we have an alignas attribute if the old declaration had one.
2455   if (OldAlignasAttr && !NewAlignasAttr &&
2456       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2457     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2458     Clone->setInherited(true);
2459     New->addAttr(Clone);
2460     AnyAdded = true;
2461   }
2462 
2463   return AnyAdded;
2464 }
2465 
2466 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2467                                const InheritableAttr *Attr,
2468                                Sema::AvailabilityMergeKind AMK) {
2469   // This function copies an attribute Attr from a previous declaration to the
2470   // new declaration D if the new declaration doesn't itself have that attribute
2471   // yet or if that attribute allows duplicates.
2472   // If you're adding a new attribute that requires logic different from
2473   // "use explicit attribute on decl if present, else use attribute from
2474   // previous decl", for example if the attribute needs to be consistent
2475   // between redeclarations, you need to call a custom merge function here.
2476   InheritableAttr *NewAttr = nullptr;
2477   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2478     NewAttr = S.mergeAvailabilityAttr(
2479         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2480         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2481         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2482         AA->getPriority());
2483   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2484     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2485   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2486     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2487   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2488     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2489   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2490     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2491   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2492     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2493                                 FA->getFirstArg());
2494   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2495     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2496   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2497     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2498   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2499     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2500                                        IA->getSemanticSpelling());
2501   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2502     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2503                                       &S.Context.Idents.get(AA->getSpelling()));
2504   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2505            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2506             isa<CUDAGlobalAttr>(Attr))) {
2507     // CUDA target attributes are part of function signature for
2508     // overloading purposes and must not be merged.
2509     return false;
2510   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2511     NewAttr = S.mergeMinSizeAttr(D, *MA);
2512   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2513     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2514   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2515     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2516   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2517     NewAttr = S.mergeCommonAttr(D, *CommonA);
2518   else if (isa<AlignedAttr>(Attr))
2519     // AlignedAttrs are handled separately, because we need to handle all
2520     // such attributes on a declaration at the same time.
2521     NewAttr = nullptr;
2522   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2523            (AMK == Sema::AMK_Override ||
2524             AMK == Sema::AMK_ProtocolImplementation))
2525     NewAttr = nullptr;
2526   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2527     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2528   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2529     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2530   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2531     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2532   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2533     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2534 
2535   if (NewAttr) {
2536     NewAttr->setInherited(true);
2537     D->addAttr(NewAttr);
2538     if (isa<MSInheritanceAttr>(NewAttr))
2539       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2540     return true;
2541   }
2542 
2543   return false;
2544 }
2545 
2546 static const NamedDecl *getDefinition(const Decl *D) {
2547   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2548     return TD->getDefinition();
2549   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2550     const VarDecl *Def = VD->getDefinition();
2551     if (Def)
2552       return Def;
2553     return VD->getActingDefinition();
2554   }
2555   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2556     return FD->getDefinition();
2557   return nullptr;
2558 }
2559 
2560 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2561   for (const auto *Attribute : D->attrs())
2562     if (Attribute->getKind() == Kind)
2563       return true;
2564   return false;
2565 }
2566 
2567 /// checkNewAttributesAfterDef - If we already have a definition, check that
2568 /// there are no new attributes in this declaration.
2569 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2570   if (!New->hasAttrs())
2571     return;
2572 
2573   const NamedDecl *Def = getDefinition(Old);
2574   if (!Def || Def == New)
2575     return;
2576 
2577   AttrVec &NewAttributes = New->getAttrs();
2578   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2579     const Attr *NewAttribute = NewAttributes[I];
2580 
2581     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2582       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2583         Sema::SkipBodyInfo SkipBody;
2584         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2585 
2586         // If we're skipping this definition, drop the "alias" attribute.
2587         if (SkipBody.ShouldSkip) {
2588           NewAttributes.erase(NewAttributes.begin() + I);
2589           --E;
2590           continue;
2591         }
2592       } else {
2593         VarDecl *VD = cast<VarDecl>(New);
2594         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2595                                 VarDecl::TentativeDefinition
2596                             ? diag::err_alias_after_tentative
2597                             : diag::err_redefinition;
2598         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2599         if (Diag == diag::err_redefinition)
2600           S.notePreviousDefinition(Def, VD->getLocation());
2601         else
2602           S.Diag(Def->getLocation(), diag::note_previous_definition);
2603         VD->setInvalidDecl();
2604       }
2605       ++I;
2606       continue;
2607     }
2608 
2609     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2610       // Tentative definitions are only interesting for the alias check above.
2611       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2612         ++I;
2613         continue;
2614       }
2615     }
2616 
2617     if (hasAttribute(Def, NewAttribute->getKind())) {
2618       ++I;
2619       continue; // regular attr merging will take care of validating this.
2620     }
2621 
2622     if (isa<C11NoReturnAttr>(NewAttribute)) {
2623       // C's _Noreturn is allowed to be added to a function after it is defined.
2624       ++I;
2625       continue;
2626     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2627       if (AA->isAlignas()) {
2628         // C++11 [dcl.align]p6:
2629         //   if any declaration of an entity has an alignment-specifier,
2630         //   every defining declaration of that entity shall specify an
2631         //   equivalent alignment.
2632         // C11 6.7.5/7:
2633         //   If the definition of an object does not have an alignment
2634         //   specifier, any other declaration of that object shall also
2635         //   have no alignment specifier.
2636         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2637           << AA;
2638         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2639           << AA;
2640         NewAttributes.erase(NewAttributes.begin() + I);
2641         --E;
2642         continue;
2643       }
2644     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2645                cast<VarDecl>(New)->isInline() &&
2646                !cast<VarDecl>(New)->isInlineSpecified()) {
2647       // Don't warn about applying selectany to implicitly inline variables.
2648       // Older compilers and language modes would require the use of selectany
2649       // to make such variables inline, and it would have no effect if we
2650       // honored it.
2651       ++I;
2652       continue;
2653     }
2654 
2655     S.Diag(NewAttribute->getLocation(),
2656            diag::warn_attribute_precede_definition);
2657     S.Diag(Def->getLocation(), diag::note_previous_definition);
2658     NewAttributes.erase(NewAttributes.begin() + I);
2659     --E;
2660   }
2661 }
2662 
2663 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2664                                      const ConstInitAttr *CIAttr,
2665                                      bool AttrBeforeInit) {
2666   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2667 
2668   // Figure out a good way to write this specifier on the old declaration.
2669   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2670   // enough of the attribute list spelling information to extract that without
2671   // heroics.
2672   std::string SuitableSpelling;
2673   if (S.getLangOpts().CPlusPlus2a)
2674     SuitableSpelling =
2675         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2676   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2677     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2678         InsertLoc,
2679         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2680          tok::coloncolon,
2681          S.PP.getIdentifierInfo("require_constant_initialization"),
2682          tok::r_square, tok::r_square});
2683   if (SuitableSpelling.empty())
2684     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2685         InsertLoc,
2686         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2687          S.PP.getIdentifierInfo("require_constant_initialization"),
2688          tok::r_paren, tok::r_paren});
2689   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2690     SuitableSpelling = "constinit";
2691   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2692     SuitableSpelling = "[[clang::require_constant_initialization]]";
2693   if (SuitableSpelling.empty())
2694     SuitableSpelling = "__attribute__((require_constant_initialization))";
2695   SuitableSpelling += " ";
2696 
2697   if (AttrBeforeInit) {
2698     // extern constinit int a;
2699     // int a = 0; // error (missing 'constinit'), accepted as extension
2700     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2701     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2702         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2703     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2704   } else {
2705     // int a = 0;
2706     // constinit extern int a; // error (missing 'constinit')
2707     S.Diag(CIAttr->getLocation(),
2708            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2709                                  : diag::warn_require_const_init_added_too_late)
2710         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2711     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2712         << CIAttr->isConstinit()
2713         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2714   }
2715 }
2716 
2717 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2718 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2719                                AvailabilityMergeKind AMK) {
2720   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2721     UsedAttr *NewAttr = OldAttr->clone(Context);
2722     NewAttr->setInherited(true);
2723     New->addAttr(NewAttr);
2724   }
2725 
2726   if (!Old->hasAttrs() && !New->hasAttrs())
2727     return;
2728 
2729   // [dcl.constinit]p1:
2730   //   If the [constinit] specifier is applied to any declaration of a
2731   //   variable, it shall be applied to the initializing declaration.
2732   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2733   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2734   if (bool(OldConstInit) != bool(NewConstInit)) {
2735     const auto *OldVD = cast<VarDecl>(Old);
2736     auto *NewVD = cast<VarDecl>(New);
2737 
2738     // Find the initializing declaration. Note that we might not have linked
2739     // the new declaration into the redeclaration chain yet.
2740     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2741     if (!InitDecl &&
2742         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2743       InitDecl = NewVD;
2744 
2745     if (InitDecl == NewVD) {
2746       // This is the initializing declaration. If it would inherit 'constinit',
2747       // that's ill-formed. (Note that we do not apply this to the attribute
2748       // form).
2749       if (OldConstInit && OldConstInit->isConstinit())
2750         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2751                                  /*AttrBeforeInit=*/true);
2752     } else if (NewConstInit) {
2753       // This is the first time we've been told that this declaration should
2754       // have a constant initializer. If we already saw the initializing
2755       // declaration, this is too late.
2756       if (InitDecl && InitDecl != NewVD) {
2757         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2758                                  /*AttrBeforeInit=*/false);
2759         NewVD->dropAttr<ConstInitAttr>();
2760       }
2761     }
2762   }
2763 
2764   // Attributes declared post-definition are currently ignored.
2765   checkNewAttributesAfterDef(*this, New, Old);
2766 
2767   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2768     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2769       if (OldA->getLabel() != NewA->getLabel()) {
2770         // This redeclaration changes __asm__ label.
2771         Diag(New->getLocation(), diag::err_different_asm_label);
2772         Diag(OldA->getLocation(), diag::note_previous_declaration);
2773       }
2774     } else if (Old->isUsed()) {
2775       // This redeclaration adds an __asm__ label to a declaration that has
2776       // already been ODR-used.
2777       Diag(New->getLocation(), diag::err_late_asm_label_name)
2778         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2779     }
2780   }
2781 
2782   // Re-declaration cannot add abi_tag's.
2783   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2784     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2785       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2786         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2787                       NewTag) == OldAbiTagAttr->tags_end()) {
2788           Diag(NewAbiTagAttr->getLocation(),
2789                diag::err_new_abi_tag_on_redeclaration)
2790               << NewTag;
2791           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2792         }
2793       }
2794     } else {
2795       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2796       Diag(Old->getLocation(), diag::note_previous_declaration);
2797     }
2798   }
2799 
2800   // This redeclaration adds a section attribute.
2801   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2802     if (auto *VD = dyn_cast<VarDecl>(New)) {
2803       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2804         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2805         Diag(Old->getLocation(), diag::note_previous_declaration);
2806       }
2807     }
2808   }
2809 
2810   // Redeclaration adds code-seg attribute.
2811   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2812   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2813       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2814     Diag(New->getLocation(), diag::warn_mismatched_section)
2815          << 0 /*codeseg*/;
2816     Diag(Old->getLocation(), diag::note_previous_declaration);
2817   }
2818 
2819   if (!Old->hasAttrs())
2820     return;
2821 
2822   bool foundAny = New->hasAttrs();
2823 
2824   // Ensure that any moving of objects within the allocated map is done before
2825   // we process them.
2826   if (!foundAny) New->setAttrs(AttrVec());
2827 
2828   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2829     // Ignore deprecated/unavailable/availability attributes if requested.
2830     AvailabilityMergeKind LocalAMK = AMK_None;
2831     if (isa<DeprecatedAttr>(I) ||
2832         isa<UnavailableAttr>(I) ||
2833         isa<AvailabilityAttr>(I)) {
2834       switch (AMK) {
2835       case AMK_None:
2836         continue;
2837 
2838       case AMK_Redeclaration:
2839       case AMK_Override:
2840       case AMK_ProtocolImplementation:
2841         LocalAMK = AMK;
2842         break;
2843       }
2844     }
2845 
2846     // Already handled.
2847     if (isa<UsedAttr>(I))
2848       continue;
2849 
2850     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2851       foundAny = true;
2852   }
2853 
2854   if (mergeAlignedAttrs(*this, New, Old))
2855     foundAny = true;
2856 
2857   if (!foundAny) New->dropAttrs();
2858 }
2859 
2860 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2861 /// to the new one.
2862 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2863                                      const ParmVarDecl *oldDecl,
2864                                      Sema &S) {
2865   // C++11 [dcl.attr.depend]p2:
2866   //   The first declaration of a function shall specify the
2867   //   carries_dependency attribute for its declarator-id if any declaration
2868   //   of the function specifies the carries_dependency attribute.
2869   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2870   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2871     S.Diag(CDA->getLocation(),
2872            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2873     // Find the first declaration of the parameter.
2874     // FIXME: Should we build redeclaration chains for function parameters?
2875     const FunctionDecl *FirstFD =
2876       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2877     const ParmVarDecl *FirstVD =
2878       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2879     S.Diag(FirstVD->getLocation(),
2880            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2881   }
2882 
2883   if (!oldDecl->hasAttrs())
2884     return;
2885 
2886   bool foundAny = newDecl->hasAttrs();
2887 
2888   // Ensure that any moving of objects within the allocated map is
2889   // done before we process them.
2890   if (!foundAny) newDecl->setAttrs(AttrVec());
2891 
2892   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2893     if (!DeclHasAttr(newDecl, I)) {
2894       InheritableAttr *newAttr =
2895         cast<InheritableParamAttr>(I->clone(S.Context));
2896       newAttr->setInherited(true);
2897       newDecl->addAttr(newAttr);
2898       foundAny = true;
2899     }
2900   }
2901 
2902   if (!foundAny) newDecl->dropAttrs();
2903 }
2904 
2905 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2906                                 const ParmVarDecl *OldParam,
2907                                 Sema &S) {
2908   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2909     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2910       if (*Oldnullability != *Newnullability) {
2911         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2912           << DiagNullabilityKind(
2913                *Newnullability,
2914                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2915                 != 0))
2916           << DiagNullabilityKind(
2917                *Oldnullability,
2918                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2919                 != 0));
2920         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2921       }
2922     } else {
2923       QualType NewT = NewParam->getType();
2924       NewT = S.Context.getAttributedType(
2925                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2926                          NewT, NewT);
2927       NewParam->setType(NewT);
2928     }
2929   }
2930 }
2931 
2932 namespace {
2933 
2934 /// Used in MergeFunctionDecl to keep track of function parameters in
2935 /// C.
2936 struct GNUCompatibleParamWarning {
2937   ParmVarDecl *OldParm;
2938   ParmVarDecl *NewParm;
2939   QualType PromotedType;
2940 };
2941 
2942 } // end anonymous namespace
2943 
2944 /// getSpecialMember - get the special member enum for a method.
2945 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2946   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2947     if (Ctor->isDefaultConstructor())
2948       return Sema::CXXDefaultConstructor;
2949 
2950     if (Ctor->isCopyConstructor())
2951       return Sema::CXXCopyConstructor;
2952 
2953     if (Ctor->isMoveConstructor())
2954       return Sema::CXXMoveConstructor;
2955   } else if (isa<CXXDestructorDecl>(MD)) {
2956     return Sema::CXXDestructor;
2957   } else if (MD->isCopyAssignmentOperator()) {
2958     return Sema::CXXCopyAssignment;
2959   } else if (MD->isMoveAssignmentOperator()) {
2960     return Sema::CXXMoveAssignment;
2961   }
2962 
2963   return Sema::CXXInvalid;
2964 }
2965 
2966 // Determine whether the previous declaration was a definition, implicit
2967 // declaration, or a declaration.
2968 template <typename T>
2969 static std::pair<diag::kind, SourceLocation>
2970 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2971   diag::kind PrevDiag;
2972   SourceLocation OldLocation = Old->getLocation();
2973   if (Old->isThisDeclarationADefinition())
2974     PrevDiag = diag::note_previous_definition;
2975   else if (Old->isImplicit()) {
2976     PrevDiag = diag::note_previous_implicit_declaration;
2977     if (OldLocation.isInvalid())
2978       OldLocation = New->getLocation();
2979   } else
2980     PrevDiag = diag::note_previous_declaration;
2981   return std::make_pair(PrevDiag, OldLocation);
2982 }
2983 
2984 /// canRedefineFunction - checks if a function can be redefined. Currently,
2985 /// only extern inline functions can be redefined, and even then only in
2986 /// GNU89 mode.
2987 static bool canRedefineFunction(const FunctionDecl *FD,
2988                                 const LangOptions& LangOpts) {
2989   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2990           !LangOpts.CPlusPlus &&
2991           FD->isInlineSpecified() &&
2992           FD->getStorageClass() == SC_Extern);
2993 }
2994 
2995 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2996   const AttributedType *AT = T->getAs<AttributedType>();
2997   while (AT && !AT->isCallingConv())
2998     AT = AT->getModifiedType()->getAs<AttributedType>();
2999   return AT;
3000 }
3001 
3002 template <typename T>
3003 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3004   const DeclContext *DC = Old->getDeclContext();
3005   if (DC->isRecord())
3006     return false;
3007 
3008   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3009   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3010     return true;
3011   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3012     return true;
3013   return false;
3014 }
3015 
3016 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3017 static bool isExternC(VarTemplateDecl *) { return false; }
3018 
3019 /// Check whether a redeclaration of an entity introduced by a
3020 /// using-declaration is valid, given that we know it's not an overload
3021 /// (nor a hidden tag declaration).
3022 template<typename ExpectedDecl>
3023 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3024                                    ExpectedDecl *New) {
3025   // C++11 [basic.scope.declarative]p4:
3026   //   Given a set of declarations in a single declarative region, each of
3027   //   which specifies the same unqualified name,
3028   //   -- they shall all refer to the same entity, or all refer to functions
3029   //      and function templates; or
3030   //   -- exactly one declaration shall declare a class name or enumeration
3031   //      name that is not a typedef name and the other declarations shall all
3032   //      refer to the same variable or enumerator, or all refer to functions
3033   //      and function templates; in this case the class name or enumeration
3034   //      name is hidden (3.3.10).
3035 
3036   // C++11 [namespace.udecl]p14:
3037   //   If a function declaration in namespace scope or block scope has the
3038   //   same name and the same parameter-type-list as a function introduced
3039   //   by a using-declaration, and the declarations do not declare the same
3040   //   function, the program is ill-formed.
3041 
3042   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3043   if (Old &&
3044       !Old->getDeclContext()->getRedeclContext()->Equals(
3045           New->getDeclContext()->getRedeclContext()) &&
3046       !(isExternC(Old) && isExternC(New)))
3047     Old = nullptr;
3048 
3049   if (!Old) {
3050     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3051     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3052     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3053     return true;
3054   }
3055   return false;
3056 }
3057 
3058 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3059                                             const FunctionDecl *B) {
3060   assert(A->getNumParams() == B->getNumParams());
3061 
3062   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3063     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3064     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3065     if (AttrA == AttrB)
3066       return true;
3067     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3068            AttrA->isDynamic() == AttrB->isDynamic();
3069   };
3070 
3071   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3072 }
3073 
3074 /// If necessary, adjust the semantic declaration context for a qualified
3075 /// declaration to name the correct inline namespace within the qualifier.
3076 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3077                                                DeclaratorDecl *OldD) {
3078   // The only case where we need to update the DeclContext is when
3079   // redeclaration lookup for a qualified name finds a declaration
3080   // in an inline namespace within the context named by the qualifier:
3081   //
3082   //   inline namespace N { int f(); }
3083   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3084   //
3085   // For unqualified declarations, the semantic context *can* change
3086   // along the redeclaration chain (for local extern declarations,
3087   // extern "C" declarations, and friend declarations in particular).
3088   if (!NewD->getQualifier())
3089     return;
3090 
3091   // NewD is probably already in the right context.
3092   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3093   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3094   if (NamedDC->Equals(SemaDC))
3095     return;
3096 
3097   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3098           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3099          "unexpected context for redeclaration");
3100 
3101   auto *LexDC = NewD->getLexicalDeclContext();
3102   auto FixSemaDC = [=](NamedDecl *D) {
3103     if (!D)
3104       return;
3105     D->setDeclContext(SemaDC);
3106     D->setLexicalDeclContext(LexDC);
3107   };
3108 
3109   FixSemaDC(NewD);
3110   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3111     FixSemaDC(FD->getDescribedFunctionTemplate());
3112   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3113     FixSemaDC(VD->getDescribedVarTemplate());
3114 }
3115 
3116 /// MergeFunctionDecl - We just parsed a function 'New' from
3117 /// declarator D which has the same name and scope as a previous
3118 /// declaration 'Old'.  Figure out how to resolve this situation,
3119 /// merging decls or emitting diagnostics as appropriate.
3120 ///
3121 /// In C++, New and Old must be declarations that are not
3122 /// overloaded. Use IsOverload to determine whether New and Old are
3123 /// overloaded, and to select the Old declaration that New should be
3124 /// merged with.
3125 ///
3126 /// Returns true if there was an error, false otherwise.
3127 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3128                              Scope *S, bool MergeTypeWithOld) {
3129   // Verify the old decl was also a function.
3130   FunctionDecl *Old = OldD->getAsFunction();
3131   if (!Old) {
3132     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3133       if (New->getFriendObjectKind()) {
3134         Diag(New->getLocation(), diag::err_using_decl_friend);
3135         Diag(Shadow->getTargetDecl()->getLocation(),
3136              diag::note_using_decl_target);
3137         Diag(Shadow->getUsingDecl()->getLocation(),
3138              diag::note_using_decl) << 0;
3139         return true;
3140       }
3141 
3142       // Check whether the two declarations might declare the same function.
3143       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3144         return true;
3145       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3146     } else {
3147       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3148         << New->getDeclName();
3149       notePreviousDefinition(OldD, New->getLocation());
3150       return true;
3151     }
3152   }
3153 
3154   // If the old declaration is invalid, just give up here.
3155   if (Old->isInvalidDecl())
3156     return true;
3157 
3158   // Disallow redeclaration of some builtins.
3159   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3160     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3161     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3162         << Old << Old->getType();
3163     return true;
3164   }
3165 
3166   diag::kind PrevDiag;
3167   SourceLocation OldLocation;
3168   std::tie(PrevDiag, OldLocation) =
3169       getNoteDiagForInvalidRedeclaration(Old, New);
3170 
3171   // Don't complain about this if we're in GNU89 mode and the old function
3172   // is an extern inline function.
3173   // Don't complain about specializations. They are not supposed to have
3174   // storage classes.
3175   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3176       New->getStorageClass() == SC_Static &&
3177       Old->hasExternalFormalLinkage() &&
3178       !New->getTemplateSpecializationInfo() &&
3179       !canRedefineFunction(Old, getLangOpts())) {
3180     if (getLangOpts().MicrosoftExt) {
3181       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3182       Diag(OldLocation, PrevDiag);
3183     } else {
3184       Diag(New->getLocation(), diag::err_static_non_static) << New;
3185       Diag(OldLocation, PrevDiag);
3186       return true;
3187     }
3188   }
3189 
3190   if (New->hasAttr<InternalLinkageAttr>() &&
3191       !Old->hasAttr<InternalLinkageAttr>()) {
3192     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3193         << New->getDeclName();
3194     notePreviousDefinition(Old, New->getLocation());
3195     New->dropAttr<InternalLinkageAttr>();
3196   }
3197 
3198   if (CheckRedeclarationModuleOwnership(New, Old))
3199     return true;
3200 
3201   if (!getLangOpts().CPlusPlus) {
3202     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3203     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3204       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3205         << New << OldOvl;
3206 
3207       // Try our best to find a decl that actually has the overloadable
3208       // attribute for the note. In most cases (e.g. programs with only one
3209       // broken declaration/definition), this won't matter.
3210       //
3211       // FIXME: We could do this if we juggled some extra state in
3212       // OverloadableAttr, rather than just removing it.
3213       const Decl *DiagOld = Old;
3214       if (OldOvl) {
3215         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3216           const auto *A = D->getAttr<OverloadableAttr>();
3217           return A && !A->isImplicit();
3218         });
3219         // If we've implicitly added *all* of the overloadable attrs to this
3220         // chain, emitting a "previous redecl" note is pointless.
3221         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3222       }
3223 
3224       if (DiagOld)
3225         Diag(DiagOld->getLocation(),
3226              diag::note_attribute_overloadable_prev_overload)
3227           << OldOvl;
3228 
3229       if (OldOvl)
3230         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3231       else
3232         New->dropAttr<OverloadableAttr>();
3233     }
3234   }
3235 
3236   // If a function is first declared with a calling convention, but is later
3237   // declared or defined without one, all following decls assume the calling
3238   // convention of the first.
3239   //
3240   // It's OK if a function is first declared without a calling convention,
3241   // but is later declared or defined with the default calling convention.
3242   //
3243   // To test if either decl has an explicit calling convention, we look for
3244   // AttributedType sugar nodes on the type as written.  If they are missing or
3245   // were canonicalized away, we assume the calling convention was implicit.
3246   //
3247   // Note also that we DO NOT return at this point, because we still have
3248   // other tests to run.
3249   QualType OldQType = Context.getCanonicalType(Old->getType());
3250   QualType NewQType = Context.getCanonicalType(New->getType());
3251   const FunctionType *OldType = cast<FunctionType>(OldQType);
3252   const FunctionType *NewType = cast<FunctionType>(NewQType);
3253   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3254   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3255   bool RequiresAdjustment = false;
3256 
3257   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3258     FunctionDecl *First = Old->getFirstDecl();
3259     const FunctionType *FT =
3260         First->getType().getCanonicalType()->castAs<FunctionType>();
3261     FunctionType::ExtInfo FI = FT->getExtInfo();
3262     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3263     if (!NewCCExplicit) {
3264       // Inherit the CC from the previous declaration if it was specified
3265       // there but not here.
3266       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3267       RequiresAdjustment = true;
3268     } else if (New->getBuiltinID()) {
3269       // Calling Conventions on a Builtin aren't really useful and setting a
3270       // default calling convention and cdecl'ing some builtin redeclarations is
3271       // common, so warn and ignore the calling convention on the redeclaration.
3272       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3273           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3274           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3275       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3276       RequiresAdjustment = true;
3277     } else {
3278       // Calling conventions aren't compatible, so complain.
3279       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3280       Diag(New->getLocation(), diag::err_cconv_change)
3281         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3282         << !FirstCCExplicit
3283         << (!FirstCCExplicit ? "" :
3284             FunctionType::getNameForCallConv(FI.getCC()));
3285 
3286       // Put the note on the first decl, since it is the one that matters.
3287       Diag(First->getLocation(), diag::note_previous_declaration);
3288       return true;
3289     }
3290   }
3291 
3292   // FIXME: diagnose the other way around?
3293   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3294     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3295     RequiresAdjustment = true;
3296   }
3297 
3298   // Merge regparm attribute.
3299   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3300       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3301     if (NewTypeInfo.getHasRegParm()) {
3302       Diag(New->getLocation(), diag::err_regparm_mismatch)
3303         << NewType->getRegParmType()
3304         << OldType->getRegParmType();
3305       Diag(OldLocation, diag::note_previous_declaration);
3306       return true;
3307     }
3308 
3309     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3310     RequiresAdjustment = true;
3311   }
3312 
3313   // Merge ns_returns_retained attribute.
3314   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3315     if (NewTypeInfo.getProducesResult()) {
3316       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3317           << "'ns_returns_retained'";
3318       Diag(OldLocation, diag::note_previous_declaration);
3319       return true;
3320     }
3321 
3322     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3323     RequiresAdjustment = true;
3324   }
3325 
3326   if (OldTypeInfo.getNoCallerSavedRegs() !=
3327       NewTypeInfo.getNoCallerSavedRegs()) {
3328     if (NewTypeInfo.getNoCallerSavedRegs()) {
3329       AnyX86NoCallerSavedRegistersAttr *Attr =
3330         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3331       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3332       Diag(OldLocation, diag::note_previous_declaration);
3333       return true;
3334     }
3335 
3336     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3337     RequiresAdjustment = true;
3338   }
3339 
3340   if (RequiresAdjustment) {
3341     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3342     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3343     New->setType(QualType(AdjustedType, 0));
3344     NewQType = Context.getCanonicalType(New->getType());
3345   }
3346 
3347   // If this redeclaration makes the function inline, we may need to add it to
3348   // UndefinedButUsed.
3349   if (!Old->isInlined() && New->isInlined() &&
3350       !New->hasAttr<GNUInlineAttr>() &&
3351       !getLangOpts().GNUInline &&
3352       Old->isUsed(false) &&
3353       !Old->isDefined() && !New->isThisDeclarationADefinition())
3354     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3355                                            SourceLocation()));
3356 
3357   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3358   // about it.
3359   if (New->hasAttr<GNUInlineAttr>() &&
3360       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3361     UndefinedButUsed.erase(Old->getCanonicalDecl());
3362   }
3363 
3364   // If pass_object_size params don't match up perfectly, this isn't a valid
3365   // redeclaration.
3366   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3367       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3368     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3369         << New->getDeclName();
3370     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3371     return true;
3372   }
3373 
3374   if (getLangOpts().CPlusPlus) {
3375     // C++1z [over.load]p2
3376     //   Certain function declarations cannot be overloaded:
3377     //     -- Function declarations that differ only in the return type,
3378     //        the exception specification, or both cannot be overloaded.
3379 
3380     // Check the exception specifications match. This may recompute the type of
3381     // both Old and New if it resolved exception specifications, so grab the
3382     // types again after this. Because this updates the type, we do this before
3383     // any of the other checks below, which may update the "de facto" NewQType
3384     // but do not necessarily update the type of New.
3385     if (CheckEquivalentExceptionSpec(Old, New))
3386       return true;
3387     OldQType = Context.getCanonicalType(Old->getType());
3388     NewQType = Context.getCanonicalType(New->getType());
3389 
3390     // Go back to the type source info to compare the declared return types,
3391     // per C++1y [dcl.type.auto]p13:
3392     //   Redeclarations or specializations of a function or function template
3393     //   with a declared return type that uses a placeholder type shall also
3394     //   use that placeholder, not a deduced type.
3395     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3396     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3397     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3398         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3399                                        OldDeclaredReturnType)) {
3400       QualType ResQT;
3401       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3402           OldDeclaredReturnType->isObjCObjectPointerType())
3403         // FIXME: This does the wrong thing for a deduced return type.
3404         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3405       if (ResQT.isNull()) {
3406         if (New->isCXXClassMember() && New->isOutOfLine())
3407           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3408               << New << New->getReturnTypeSourceRange();
3409         else
3410           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3411               << New->getReturnTypeSourceRange();
3412         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3413                                     << Old->getReturnTypeSourceRange();
3414         return true;
3415       }
3416       else
3417         NewQType = ResQT;
3418     }
3419 
3420     QualType OldReturnType = OldType->getReturnType();
3421     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3422     if (OldReturnType != NewReturnType) {
3423       // If this function has a deduced return type and has already been
3424       // defined, copy the deduced value from the old declaration.
3425       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3426       if (OldAT && OldAT->isDeduced()) {
3427         New->setType(
3428             SubstAutoType(New->getType(),
3429                           OldAT->isDependentType() ? Context.DependentTy
3430                                                    : OldAT->getDeducedType()));
3431         NewQType = Context.getCanonicalType(
3432             SubstAutoType(NewQType,
3433                           OldAT->isDependentType() ? Context.DependentTy
3434                                                    : OldAT->getDeducedType()));
3435       }
3436     }
3437 
3438     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3439     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3440     if (OldMethod && NewMethod) {
3441       // Preserve triviality.
3442       NewMethod->setTrivial(OldMethod->isTrivial());
3443 
3444       // MSVC allows explicit template specialization at class scope:
3445       // 2 CXXMethodDecls referring to the same function will be injected.
3446       // We don't want a redeclaration error.
3447       bool IsClassScopeExplicitSpecialization =
3448                               OldMethod->isFunctionTemplateSpecialization() &&
3449                               NewMethod->isFunctionTemplateSpecialization();
3450       bool isFriend = NewMethod->getFriendObjectKind();
3451 
3452       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3453           !IsClassScopeExplicitSpecialization) {
3454         //    -- Member function declarations with the same name and the
3455         //       same parameter types cannot be overloaded if any of them
3456         //       is a static member function declaration.
3457         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3458           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3459           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3460           return true;
3461         }
3462 
3463         // C++ [class.mem]p1:
3464         //   [...] A member shall not be declared twice in the
3465         //   member-specification, except that a nested class or member
3466         //   class template can be declared and then later defined.
3467         if (!inTemplateInstantiation()) {
3468           unsigned NewDiag;
3469           if (isa<CXXConstructorDecl>(OldMethod))
3470             NewDiag = diag::err_constructor_redeclared;
3471           else if (isa<CXXDestructorDecl>(NewMethod))
3472             NewDiag = diag::err_destructor_redeclared;
3473           else if (isa<CXXConversionDecl>(NewMethod))
3474             NewDiag = diag::err_conv_function_redeclared;
3475           else
3476             NewDiag = diag::err_member_redeclared;
3477 
3478           Diag(New->getLocation(), NewDiag);
3479         } else {
3480           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3481             << New << New->getType();
3482         }
3483         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3484         return true;
3485 
3486       // Complain if this is an explicit declaration of a special
3487       // member that was initially declared implicitly.
3488       //
3489       // As an exception, it's okay to befriend such methods in order
3490       // to permit the implicit constructor/destructor/operator calls.
3491       } else if (OldMethod->isImplicit()) {
3492         if (isFriend) {
3493           NewMethod->setImplicit();
3494         } else {
3495           Diag(NewMethod->getLocation(),
3496                diag::err_definition_of_implicitly_declared_member)
3497             << New << getSpecialMember(OldMethod);
3498           return true;
3499         }
3500       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3501         Diag(NewMethod->getLocation(),
3502              diag::err_definition_of_explicitly_defaulted_member)
3503           << getSpecialMember(OldMethod);
3504         return true;
3505       }
3506     }
3507 
3508     // C++11 [dcl.attr.noreturn]p1:
3509     //   The first declaration of a function shall specify the noreturn
3510     //   attribute if any declaration of that function specifies the noreturn
3511     //   attribute.
3512     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3513     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3514       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3515       Diag(Old->getFirstDecl()->getLocation(),
3516            diag::note_noreturn_missing_first_decl);
3517     }
3518 
3519     // C++11 [dcl.attr.depend]p2:
3520     //   The first declaration of a function shall specify the
3521     //   carries_dependency attribute for its declarator-id if any declaration
3522     //   of the function specifies the carries_dependency attribute.
3523     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3524     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3525       Diag(CDA->getLocation(),
3526            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3527       Diag(Old->getFirstDecl()->getLocation(),
3528            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3529     }
3530 
3531     // (C++98 8.3.5p3):
3532     //   All declarations for a function shall agree exactly in both the
3533     //   return type and the parameter-type-list.
3534     // We also want to respect all the extended bits except noreturn.
3535 
3536     // noreturn should now match unless the old type info didn't have it.
3537     QualType OldQTypeForComparison = OldQType;
3538     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3539       auto *OldType = OldQType->castAs<FunctionProtoType>();
3540       const FunctionType *OldTypeForComparison
3541         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3542       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3543       assert(OldQTypeForComparison.isCanonical());
3544     }
3545 
3546     if (haveIncompatibleLanguageLinkages(Old, New)) {
3547       // As a special case, retain the language linkage from previous
3548       // declarations of a friend function as an extension.
3549       //
3550       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3551       // and is useful because there's otherwise no way to specify language
3552       // linkage within class scope.
3553       //
3554       // Check cautiously as the friend object kind isn't yet complete.
3555       if (New->getFriendObjectKind() != Decl::FOK_None) {
3556         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3557         Diag(OldLocation, PrevDiag);
3558       } else {
3559         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3560         Diag(OldLocation, PrevDiag);
3561         return true;
3562       }
3563     }
3564 
3565     // If the function types are compatible, merge the declarations. Ignore the
3566     // exception specifier because it was already checked above in
3567     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3568     // about incompatible types under -fms-compatibility.
3569     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3570                                                          NewQType))
3571       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3572 
3573     // If the types are imprecise (due to dependent constructs in friends or
3574     // local extern declarations), it's OK if they differ. We'll check again
3575     // during instantiation.
3576     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3577       return false;
3578 
3579     // Fall through for conflicting redeclarations and redefinitions.
3580   }
3581 
3582   // C: Function types need to be compatible, not identical. This handles
3583   // duplicate function decls like "void f(int); void f(enum X);" properly.
3584   if (!getLangOpts().CPlusPlus &&
3585       Context.typesAreCompatible(OldQType, NewQType)) {
3586     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3587     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3588     const FunctionProtoType *OldProto = nullptr;
3589     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3590         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3591       // The old declaration provided a function prototype, but the
3592       // new declaration does not. Merge in the prototype.
3593       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3594       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3595       NewQType =
3596           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3597                                   OldProto->getExtProtoInfo());
3598       New->setType(NewQType);
3599       New->setHasInheritedPrototype();
3600 
3601       // Synthesize parameters with the same types.
3602       SmallVector<ParmVarDecl*, 16> Params;
3603       for (const auto &ParamType : OldProto->param_types()) {
3604         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3605                                                  SourceLocation(), nullptr,
3606                                                  ParamType, /*TInfo=*/nullptr,
3607                                                  SC_None, nullptr);
3608         Param->setScopeInfo(0, Params.size());
3609         Param->setImplicit();
3610         Params.push_back(Param);
3611       }
3612 
3613       New->setParams(Params);
3614     }
3615 
3616     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3617   }
3618 
3619   // GNU C permits a K&R definition to follow a prototype declaration
3620   // if the declared types of the parameters in the K&R definition
3621   // match the types in the prototype declaration, even when the
3622   // promoted types of the parameters from the K&R definition differ
3623   // from the types in the prototype. GCC then keeps the types from
3624   // the prototype.
3625   //
3626   // If a variadic prototype is followed by a non-variadic K&R definition,
3627   // the K&R definition becomes variadic.  This is sort of an edge case, but
3628   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3629   // C99 6.9.1p8.
3630   if (!getLangOpts().CPlusPlus &&
3631       Old->hasPrototype() && !New->hasPrototype() &&
3632       New->getType()->getAs<FunctionProtoType>() &&
3633       Old->getNumParams() == New->getNumParams()) {
3634     SmallVector<QualType, 16> ArgTypes;
3635     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3636     const FunctionProtoType *OldProto
3637       = Old->getType()->getAs<FunctionProtoType>();
3638     const FunctionProtoType *NewProto
3639       = New->getType()->getAs<FunctionProtoType>();
3640 
3641     // Determine whether this is the GNU C extension.
3642     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3643                                                NewProto->getReturnType());
3644     bool LooseCompatible = !MergedReturn.isNull();
3645     for (unsigned Idx = 0, End = Old->getNumParams();
3646          LooseCompatible && Idx != End; ++Idx) {
3647       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3648       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3649       if (Context.typesAreCompatible(OldParm->getType(),
3650                                      NewProto->getParamType(Idx))) {
3651         ArgTypes.push_back(NewParm->getType());
3652       } else if (Context.typesAreCompatible(OldParm->getType(),
3653                                             NewParm->getType(),
3654                                             /*CompareUnqualified=*/true)) {
3655         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3656                                            NewProto->getParamType(Idx) };
3657         Warnings.push_back(Warn);
3658         ArgTypes.push_back(NewParm->getType());
3659       } else
3660         LooseCompatible = false;
3661     }
3662 
3663     if (LooseCompatible) {
3664       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3665         Diag(Warnings[Warn].NewParm->getLocation(),
3666              diag::ext_param_promoted_not_compatible_with_prototype)
3667           << Warnings[Warn].PromotedType
3668           << Warnings[Warn].OldParm->getType();
3669         if (Warnings[Warn].OldParm->getLocation().isValid())
3670           Diag(Warnings[Warn].OldParm->getLocation(),
3671                diag::note_previous_declaration);
3672       }
3673 
3674       if (MergeTypeWithOld)
3675         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3676                                              OldProto->getExtProtoInfo()));
3677       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3678     }
3679 
3680     // Fall through to diagnose conflicting types.
3681   }
3682 
3683   // A function that has already been declared has been redeclared or
3684   // defined with a different type; show an appropriate diagnostic.
3685 
3686   // If the previous declaration was an implicitly-generated builtin
3687   // declaration, then at the very least we should use a specialized note.
3688   unsigned BuiltinID;
3689   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3690     // If it's actually a library-defined builtin function like 'malloc'
3691     // or 'printf', just warn about the incompatible redeclaration.
3692     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3693       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3694       Diag(OldLocation, diag::note_previous_builtin_declaration)
3695         << Old << Old->getType();
3696 
3697       // If this is a global redeclaration, just forget hereafter
3698       // about the "builtin-ness" of the function.
3699       //
3700       // Doing this for local extern declarations is problematic.  If
3701       // the builtin declaration remains visible, a second invalid
3702       // local declaration will produce a hard error; if it doesn't
3703       // remain visible, a single bogus local redeclaration (which is
3704       // actually only a warning) could break all the downstream code.
3705       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3706         New->getIdentifier()->revertBuiltin();
3707 
3708       return false;
3709     }
3710 
3711     PrevDiag = diag::note_previous_builtin_declaration;
3712   }
3713 
3714   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3715   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3716   return true;
3717 }
3718 
3719 /// Completes the merge of two function declarations that are
3720 /// known to be compatible.
3721 ///
3722 /// This routine handles the merging of attributes and other
3723 /// properties of function declarations from the old declaration to
3724 /// the new declaration, once we know that New is in fact a
3725 /// redeclaration of Old.
3726 ///
3727 /// \returns false
3728 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3729                                         Scope *S, bool MergeTypeWithOld) {
3730   // Merge the attributes
3731   mergeDeclAttributes(New, Old);
3732 
3733   // Merge "pure" flag.
3734   if (Old->isPure())
3735     New->setPure();
3736 
3737   // Merge "used" flag.
3738   if (Old->getMostRecentDecl()->isUsed(false))
3739     New->setIsUsed();
3740 
3741   // Merge attributes from the parameters.  These can mismatch with K&R
3742   // declarations.
3743   if (New->getNumParams() == Old->getNumParams())
3744       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3745         ParmVarDecl *NewParam = New->getParamDecl(i);
3746         ParmVarDecl *OldParam = Old->getParamDecl(i);
3747         mergeParamDeclAttributes(NewParam, OldParam, *this);
3748         mergeParamDeclTypes(NewParam, OldParam, *this);
3749       }
3750 
3751   if (getLangOpts().CPlusPlus)
3752     return MergeCXXFunctionDecl(New, Old, S);
3753 
3754   // Merge the function types so the we get the composite types for the return
3755   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3756   // was visible.
3757   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3758   if (!Merged.isNull() && MergeTypeWithOld)
3759     New->setType(Merged);
3760 
3761   return false;
3762 }
3763 
3764 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3765                                 ObjCMethodDecl *oldMethod) {
3766   // Merge the attributes, including deprecated/unavailable
3767   AvailabilityMergeKind MergeKind =
3768     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3769       ? AMK_ProtocolImplementation
3770       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3771                                                        : AMK_Override;
3772 
3773   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3774 
3775   // Merge attributes from the parameters.
3776   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3777                                        oe = oldMethod->param_end();
3778   for (ObjCMethodDecl::param_iterator
3779          ni = newMethod->param_begin(), ne = newMethod->param_end();
3780        ni != ne && oi != oe; ++ni, ++oi)
3781     mergeParamDeclAttributes(*ni, *oi, *this);
3782 
3783   CheckObjCMethodOverride(newMethod, oldMethod);
3784 }
3785 
3786 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3787   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3788 
3789   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3790          ? diag::err_redefinition_different_type
3791          : diag::err_redeclaration_different_type)
3792     << New->getDeclName() << New->getType() << Old->getType();
3793 
3794   diag::kind PrevDiag;
3795   SourceLocation OldLocation;
3796   std::tie(PrevDiag, OldLocation)
3797     = getNoteDiagForInvalidRedeclaration(Old, New);
3798   S.Diag(OldLocation, PrevDiag);
3799   New->setInvalidDecl();
3800 }
3801 
3802 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3803 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3804 /// emitting diagnostics as appropriate.
3805 ///
3806 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3807 /// to here in AddInitializerToDecl. We can't check them before the initializer
3808 /// is attached.
3809 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3810                              bool MergeTypeWithOld) {
3811   if (New->isInvalidDecl() || Old->isInvalidDecl())
3812     return;
3813 
3814   QualType MergedT;
3815   if (getLangOpts().CPlusPlus) {
3816     if (New->getType()->isUndeducedType()) {
3817       // We don't know what the new type is until the initializer is attached.
3818       return;
3819     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3820       // These could still be something that needs exception specs checked.
3821       return MergeVarDeclExceptionSpecs(New, Old);
3822     }
3823     // C++ [basic.link]p10:
3824     //   [...] the types specified by all declarations referring to a given
3825     //   object or function shall be identical, except that declarations for an
3826     //   array object can specify array types that differ by the presence or
3827     //   absence of a major array bound (8.3.4).
3828     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3829       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3830       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3831 
3832       // We are merging a variable declaration New into Old. If it has an array
3833       // bound, and that bound differs from Old's bound, we should diagnose the
3834       // mismatch.
3835       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3836         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3837              PrevVD = PrevVD->getPreviousDecl()) {
3838           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3839           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3840             continue;
3841 
3842           if (!Context.hasSameType(NewArray, PrevVDTy))
3843             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3844         }
3845       }
3846 
3847       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3848         if (Context.hasSameType(OldArray->getElementType(),
3849                                 NewArray->getElementType()))
3850           MergedT = New->getType();
3851       }
3852       // FIXME: Check visibility. New is hidden but has a complete type. If New
3853       // has no array bound, it should not inherit one from Old, if Old is not
3854       // visible.
3855       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3856         if (Context.hasSameType(OldArray->getElementType(),
3857                                 NewArray->getElementType()))
3858           MergedT = Old->getType();
3859       }
3860     }
3861     else if (New->getType()->isObjCObjectPointerType() &&
3862                Old->getType()->isObjCObjectPointerType()) {
3863       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3864                                               Old->getType());
3865     }
3866   } else {
3867     // C 6.2.7p2:
3868     //   All declarations that refer to the same object or function shall have
3869     //   compatible type.
3870     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3871   }
3872   if (MergedT.isNull()) {
3873     // It's OK if we couldn't merge types if either type is dependent, for a
3874     // block-scope variable. In other cases (static data members of class
3875     // templates, variable templates, ...), we require the types to be
3876     // equivalent.
3877     // FIXME: The C++ standard doesn't say anything about this.
3878     if ((New->getType()->isDependentType() ||
3879          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3880       // If the old type was dependent, we can't merge with it, so the new type
3881       // becomes dependent for now. We'll reproduce the original type when we
3882       // instantiate the TypeSourceInfo for the variable.
3883       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3884         New->setType(Context.DependentTy);
3885       return;
3886     }
3887     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3888   }
3889 
3890   // Don't actually update the type on the new declaration if the old
3891   // declaration was an extern declaration in a different scope.
3892   if (MergeTypeWithOld)
3893     New->setType(MergedT);
3894 }
3895 
3896 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3897                                   LookupResult &Previous) {
3898   // C11 6.2.7p4:
3899   //   For an identifier with internal or external linkage declared
3900   //   in a scope in which a prior declaration of that identifier is
3901   //   visible, if the prior declaration specifies internal or
3902   //   external linkage, the type of the identifier at the later
3903   //   declaration becomes the composite type.
3904   //
3905   // If the variable isn't visible, we do not merge with its type.
3906   if (Previous.isShadowed())
3907     return false;
3908 
3909   if (S.getLangOpts().CPlusPlus) {
3910     // C++11 [dcl.array]p3:
3911     //   If there is a preceding declaration of the entity in the same
3912     //   scope in which the bound was specified, an omitted array bound
3913     //   is taken to be the same as in that earlier declaration.
3914     return NewVD->isPreviousDeclInSameBlockScope() ||
3915            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3916             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3917   } else {
3918     // If the old declaration was function-local, don't merge with its
3919     // type unless we're in the same function.
3920     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3921            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3922   }
3923 }
3924 
3925 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3926 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3927 /// situation, merging decls or emitting diagnostics as appropriate.
3928 ///
3929 /// Tentative definition rules (C99 6.9.2p2) are checked by
3930 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3931 /// definitions here, since the initializer hasn't been attached.
3932 ///
3933 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3934   // If the new decl is already invalid, don't do any other checking.
3935   if (New->isInvalidDecl())
3936     return;
3937 
3938   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3939     return;
3940 
3941   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3942 
3943   // Verify the old decl was also a variable or variable template.
3944   VarDecl *Old = nullptr;
3945   VarTemplateDecl *OldTemplate = nullptr;
3946   if (Previous.isSingleResult()) {
3947     if (NewTemplate) {
3948       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3949       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3950 
3951       if (auto *Shadow =
3952               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3953         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3954           return New->setInvalidDecl();
3955     } else {
3956       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3957 
3958       if (auto *Shadow =
3959               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3960         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3961           return New->setInvalidDecl();
3962     }
3963   }
3964   if (!Old) {
3965     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3966         << New->getDeclName();
3967     notePreviousDefinition(Previous.getRepresentativeDecl(),
3968                            New->getLocation());
3969     return New->setInvalidDecl();
3970   }
3971 
3972   // Ensure the template parameters are compatible.
3973   if (NewTemplate &&
3974       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3975                                       OldTemplate->getTemplateParameters(),
3976                                       /*Complain=*/true, TPL_TemplateMatch))
3977     return New->setInvalidDecl();
3978 
3979   // C++ [class.mem]p1:
3980   //   A member shall not be declared twice in the member-specification [...]
3981   //
3982   // Here, we need only consider static data members.
3983   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3984     Diag(New->getLocation(), diag::err_duplicate_member)
3985       << New->getIdentifier();
3986     Diag(Old->getLocation(), diag::note_previous_declaration);
3987     New->setInvalidDecl();
3988   }
3989 
3990   mergeDeclAttributes(New, Old);
3991   // Warn if an already-declared variable is made a weak_import in a subsequent
3992   // declaration
3993   if (New->hasAttr<WeakImportAttr>() &&
3994       Old->getStorageClass() == SC_None &&
3995       !Old->hasAttr<WeakImportAttr>()) {
3996     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3997     notePreviousDefinition(Old, New->getLocation());
3998     // Remove weak_import attribute on new declaration.
3999     New->dropAttr<WeakImportAttr>();
4000   }
4001 
4002   if (New->hasAttr<InternalLinkageAttr>() &&
4003       !Old->hasAttr<InternalLinkageAttr>()) {
4004     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4005         << New->getDeclName();
4006     notePreviousDefinition(Old, New->getLocation());
4007     New->dropAttr<InternalLinkageAttr>();
4008   }
4009 
4010   // Merge the types.
4011   VarDecl *MostRecent = Old->getMostRecentDecl();
4012   if (MostRecent != Old) {
4013     MergeVarDeclTypes(New, MostRecent,
4014                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4015     if (New->isInvalidDecl())
4016       return;
4017   }
4018 
4019   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4020   if (New->isInvalidDecl())
4021     return;
4022 
4023   diag::kind PrevDiag;
4024   SourceLocation OldLocation;
4025   std::tie(PrevDiag, OldLocation) =
4026       getNoteDiagForInvalidRedeclaration(Old, New);
4027 
4028   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4029   if (New->getStorageClass() == SC_Static &&
4030       !New->isStaticDataMember() &&
4031       Old->hasExternalFormalLinkage()) {
4032     if (getLangOpts().MicrosoftExt) {
4033       Diag(New->getLocation(), diag::ext_static_non_static)
4034           << New->getDeclName();
4035       Diag(OldLocation, PrevDiag);
4036     } else {
4037       Diag(New->getLocation(), diag::err_static_non_static)
4038           << New->getDeclName();
4039       Diag(OldLocation, PrevDiag);
4040       return New->setInvalidDecl();
4041     }
4042   }
4043   // C99 6.2.2p4:
4044   //   For an identifier declared with the storage-class specifier
4045   //   extern in a scope in which a prior declaration of that
4046   //   identifier is visible,23) if the prior declaration specifies
4047   //   internal or external linkage, the linkage of the identifier at
4048   //   the later declaration is the same as the linkage specified at
4049   //   the prior declaration. If no prior declaration is visible, or
4050   //   if the prior declaration specifies no linkage, then the
4051   //   identifier has external linkage.
4052   if (New->hasExternalStorage() && Old->hasLinkage())
4053     /* Okay */;
4054   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4055            !New->isStaticDataMember() &&
4056            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4057     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4058     Diag(OldLocation, PrevDiag);
4059     return New->setInvalidDecl();
4060   }
4061 
4062   // Check if extern is followed by non-extern and vice-versa.
4063   if (New->hasExternalStorage() &&
4064       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4065     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4066     Diag(OldLocation, PrevDiag);
4067     return New->setInvalidDecl();
4068   }
4069   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4070       !New->hasExternalStorage()) {
4071     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4072     Diag(OldLocation, PrevDiag);
4073     return New->setInvalidDecl();
4074   }
4075 
4076   if (CheckRedeclarationModuleOwnership(New, Old))
4077     return;
4078 
4079   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4080 
4081   // FIXME: The test for external storage here seems wrong? We still
4082   // need to check for mismatches.
4083   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4084       // Don't complain about out-of-line definitions of static members.
4085       !(Old->getLexicalDeclContext()->isRecord() &&
4086         !New->getLexicalDeclContext()->isRecord())) {
4087     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4088     Diag(OldLocation, PrevDiag);
4089     return New->setInvalidDecl();
4090   }
4091 
4092   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4093     if (VarDecl *Def = Old->getDefinition()) {
4094       // C++1z [dcl.fcn.spec]p4:
4095       //   If the definition of a variable appears in a translation unit before
4096       //   its first declaration as inline, the program is ill-formed.
4097       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4098       Diag(Def->getLocation(), diag::note_previous_definition);
4099     }
4100   }
4101 
4102   // If this redeclaration makes the variable inline, we may need to add it to
4103   // UndefinedButUsed.
4104   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4105       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4106     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4107                                            SourceLocation()));
4108 
4109   if (New->getTLSKind() != Old->getTLSKind()) {
4110     if (!Old->getTLSKind()) {
4111       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4112       Diag(OldLocation, PrevDiag);
4113     } else if (!New->getTLSKind()) {
4114       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4115       Diag(OldLocation, PrevDiag);
4116     } else {
4117       // Do not allow redeclaration to change the variable between requiring
4118       // static and dynamic initialization.
4119       // FIXME: GCC allows this, but uses the TLS keyword on the first
4120       // declaration to determine the kind. Do we need to be compatible here?
4121       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4122         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4123       Diag(OldLocation, PrevDiag);
4124     }
4125   }
4126 
4127   // C++ doesn't have tentative definitions, so go right ahead and check here.
4128   if (getLangOpts().CPlusPlus &&
4129       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4130     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4131         Old->getCanonicalDecl()->isConstexpr()) {
4132       // This definition won't be a definition any more once it's been merged.
4133       Diag(New->getLocation(),
4134            diag::warn_deprecated_redundant_constexpr_static_def);
4135     } else if (VarDecl *Def = Old->getDefinition()) {
4136       if (checkVarDeclRedefinition(Def, New))
4137         return;
4138     }
4139   }
4140 
4141   if (haveIncompatibleLanguageLinkages(Old, New)) {
4142     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4143     Diag(OldLocation, PrevDiag);
4144     New->setInvalidDecl();
4145     return;
4146   }
4147 
4148   // Merge "used" flag.
4149   if (Old->getMostRecentDecl()->isUsed(false))
4150     New->setIsUsed();
4151 
4152   // Keep a chain of previous declarations.
4153   New->setPreviousDecl(Old);
4154   if (NewTemplate)
4155     NewTemplate->setPreviousDecl(OldTemplate);
4156   adjustDeclContextForDeclaratorDecl(New, Old);
4157 
4158   // Inherit access appropriately.
4159   New->setAccess(Old->getAccess());
4160   if (NewTemplate)
4161     NewTemplate->setAccess(New->getAccess());
4162 
4163   if (Old->isInline())
4164     New->setImplicitlyInline();
4165 }
4166 
4167 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4168   SourceManager &SrcMgr = getSourceManager();
4169   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4170   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4171   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4172   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4173   auto &HSI = PP.getHeaderSearchInfo();
4174   StringRef HdrFilename =
4175       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4176 
4177   auto noteFromModuleOrInclude = [&](Module *Mod,
4178                                      SourceLocation IncLoc) -> bool {
4179     // Redefinition errors with modules are common with non modular mapped
4180     // headers, example: a non-modular header H in module A that also gets
4181     // included directly in a TU. Pointing twice to the same header/definition
4182     // is confusing, try to get better diagnostics when modules is on.
4183     if (IncLoc.isValid()) {
4184       if (Mod) {
4185         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4186             << HdrFilename.str() << Mod->getFullModuleName();
4187         if (!Mod->DefinitionLoc.isInvalid())
4188           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4189               << Mod->getFullModuleName();
4190       } else {
4191         Diag(IncLoc, diag::note_redefinition_include_same_file)
4192             << HdrFilename.str();
4193       }
4194       return true;
4195     }
4196 
4197     return false;
4198   };
4199 
4200   // Is it the same file and same offset? Provide more information on why
4201   // this leads to a redefinition error.
4202   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4203     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4204     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4205     bool EmittedDiag =
4206         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4207     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4208 
4209     // If the header has no guards, emit a note suggesting one.
4210     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4211       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4212 
4213     if (EmittedDiag)
4214       return;
4215   }
4216 
4217   // Redefinition coming from different files or couldn't do better above.
4218   if (Old->getLocation().isValid())
4219     Diag(Old->getLocation(), diag::note_previous_definition);
4220 }
4221 
4222 /// We've just determined that \p Old and \p New both appear to be definitions
4223 /// of the same variable. Either diagnose or fix the problem.
4224 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4225   if (!hasVisibleDefinition(Old) &&
4226       (New->getFormalLinkage() == InternalLinkage ||
4227        New->isInline() ||
4228        New->getDescribedVarTemplate() ||
4229        New->getNumTemplateParameterLists() ||
4230        New->getDeclContext()->isDependentContext())) {
4231     // The previous definition is hidden, and multiple definitions are
4232     // permitted (in separate TUs). Demote this to a declaration.
4233     New->demoteThisDefinitionToDeclaration();
4234 
4235     // Make the canonical definition visible.
4236     if (auto *OldTD = Old->getDescribedVarTemplate())
4237       makeMergedDefinitionVisible(OldTD);
4238     makeMergedDefinitionVisible(Old);
4239     return false;
4240   } else {
4241     Diag(New->getLocation(), diag::err_redefinition) << New;
4242     notePreviousDefinition(Old, New->getLocation());
4243     New->setInvalidDecl();
4244     return true;
4245   }
4246 }
4247 
4248 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4249 /// no declarator (e.g. "struct foo;") is parsed.
4250 Decl *
4251 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4252                                  RecordDecl *&AnonRecord) {
4253   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4254                                     AnonRecord);
4255 }
4256 
4257 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4258 // disambiguate entities defined in different scopes.
4259 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4260 // compatibility.
4261 // We will pick our mangling number depending on which version of MSVC is being
4262 // targeted.
4263 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4264   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4265              ? S->getMSCurManglingNumber()
4266              : S->getMSLastManglingNumber();
4267 }
4268 
4269 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4270   if (!Context.getLangOpts().CPlusPlus)
4271     return;
4272 
4273   if (isa<CXXRecordDecl>(Tag->getParent())) {
4274     // If this tag is the direct child of a class, number it if
4275     // it is anonymous.
4276     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4277       return;
4278     MangleNumberingContext &MCtx =
4279         Context.getManglingNumberContext(Tag->getParent());
4280     Context.setManglingNumber(
4281         Tag, MCtx.getManglingNumber(
4282                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4283     return;
4284   }
4285 
4286   // If this tag isn't a direct child of a class, number it if it is local.
4287   Decl *ManglingContextDecl;
4288   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4289           Tag->getDeclContext(), ManglingContextDecl)) {
4290     Context.setManglingNumber(
4291         Tag, MCtx->getManglingNumber(
4292                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4293   }
4294 }
4295 
4296 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4297                                         TypedefNameDecl *NewTD) {
4298   if (TagFromDeclSpec->isInvalidDecl())
4299     return;
4300 
4301   // Do nothing if the tag already has a name for linkage purposes.
4302   if (TagFromDeclSpec->hasNameForLinkage())
4303     return;
4304 
4305   // A well-formed anonymous tag must always be a TUK_Definition.
4306   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4307 
4308   // The type must match the tag exactly;  no qualifiers allowed.
4309   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4310                            Context.getTagDeclType(TagFromDeclSpec))) {
4311     if (getLangOpts().CPlusPlus)
4312       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4313     return;
4314   }
4315 
4316   // If we've already computed linkage for the anonymous tag, then
4317   // adding a typedef name for the anonymous decl can change that
4318   // linkage, which might be a serious problem.  Diagnose this as
4319   // unsupported and ignore the typedef name.  TODO: we should
4320   // pursue this as a language defect and establish a formal rule
4321   // for how to handle it.
4322   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4323     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4324 
4325     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4326     tagLoc = getLocForEndOfToken(tagLoc);
4327 
4328     llvm::SmallString<40> textToInsert;
4329     textToInsert += ' ';
4330     textToInsert += NewTD->getIdentifier()->getName();
4331     Diag(tagLoc, diag::note_typedef_changes_linkage)
4332         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4333     return;
4334   }
4335 
4336   // Otherwise, set this is the anon-decl typedef for the tag.
4337   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4338 }
4339 
4340 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4341   switch (T) {
4342   case DeclSpec::TST_class:
4343     return 0;
4344   case DeclSpec::TST_struct:
4345     return 1;
4346   case DeclSpec::TST_interface:
4347     return 2;
4348   case DeclSpec::TST_union:
4349     return 3;
4350   case DeclSpec::TST_enum:
4351     return 4;
4352   default:
4353     llvm_unreachable("unexpected type specifier");
4354   }
4355 }
4356 
4357 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4358 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4359 /// parameters to cope with template friend declarations.
4360 Decl *
4361 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4362                                  MultiTemplateParamsArg TemplateParams,
4363                                  bool IsExplicitInstantiation,
4364                                  RecordDecl *&AnonRecord) {
4365   Decl *TagD = nullptr;
4366   TagDecl *Tag = nullptr;
4367   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4368       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4369       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4370       DS.getTypeSpecType() == DeclSpec::TST_union ||
4371       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4372     TagD = DS.getRepAsDecl();
4373 
4374     if (!TagD) // We probably had an error
4375       return nullptr;
4376 
4377     // Note that the above type specs guarantee that the
4378     // type rep is a Decl, whereas in many of the others
4379     // it's a Type.
4380     if (isa<TagDecl>(TagD))
4381       Tag = cast<TagDecl>(TagD);
4382     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4383       Tag = CTD->getTemplatedDecl();
4384   }
4385 
4386   if (Tag) {
4387     handleTagNumbering(Tag, S);
4388     Tag->setFreeStanding();
4389     if (Tag->isInvalidDecl())
4390       return Tag;
4391   }
4392 
4393   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4394     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4395     // or incomplete types shall not be restrict-qualified."
4396     if (TypeQuals & DeclSpec::TQ_restrict)
4397       Diag(DS.getRestrictSpecLoc(),
4398            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4399            << DS.getSourceRange();
4400   }
4401 
4402   if (DS.isInlineSpecified())
4403     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4404         << getLangOpts().CPlusPlus17;
4405 
4406   if (DS.hasConstexprSpecifier()) {
4407     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4408     // and definitions of functions and variables.
4409     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4410     // the declaration of a function or function template
4411     if (Tag)
4412       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4413           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4414           << DS.getConstexprSpecifier();
4415     else
4416       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4417           << DS.getConstexprSpecifier();
4418     // Don't emit warnings after this error.
4419     return TagD;
4420   }
4421 
4422   DiagnoseFunctionSpecifiers(DS);
4423 
4424   if (DS.isFriendSpecified()) {
4425     // If we're dealing with a decl but not a TagDecl, assume that
4426     // whatever routines created it handled the friendship aspect.
4427     if (TagD && !Tag)
4428       return nullptr;
4429     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4430   }
4431 
4432   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4433   bool IsExplicitSpecialization =
4434     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4435   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4436       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4437       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4438     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4439     // nested-name-specifier unless it is an explicit instantiation
4440     // or an explicit specialization.
4441     //
4442     // FIXME: We allow class template partial specializations here too, per the
4443     // obvious intent of DR1819.
4444     //
4445     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4446     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4447         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4448     return nullptr;
4449   }
4450 
4451   // Track whether this decl-specifier declares anything.
4452   bool DeclaresAnything = true;
4453 
4454   // Handle anonymous struct definitions.
4455   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4456     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4457         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4458       if (getLangOpts().CPlusPlus ||
4459           Record->getDeclContext()->isRecord()) {
4460         // If CurContext is a DeclContext that can contain statements,
4461         // RecursiveASTVisitor won't visit the decls that
4462         // BuildAnonymousStructOrUnion() will put into CurContext.
4463         // Also store them here so that they can be part of the
4464         // DeclStmt that gets created in this case.
4465         // FIXME: Also return the IndirectFieldDecls created by
4466         // BuildAnonymousStructOr union, for the same reason?
4467         if (CurContext->isFunctionOrMethod())
4468           AnonRecord = Record;
4469         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4470                                            Context.getPrintingPolicy());
4471       }
4472 
4473       DeclaresAnything = false;
4474     }
4475   }
4476 
4477   // C11 6.7.2.1p2:
4478   //   A struct-declaration that does not declare an anonymous structure or
4479   //   anonymous union shall contain a struct-declarator-list.
4480   //
4481   // This rule also existed in C89 and C99; the grammar for struct-declaration
4482   // did not permit a struct-declaration without a struct-declarator-list.
4483   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4484       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4485     // Check for Microsoft C extension: anonymous struct/union member.
4486     // Handle 2 kinds of anonymous struct/union:
4487     //   struct STRUCT;
4488     //   union UNION;
4489     // and
4490     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4491     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4492     if ((Tag && Tag->getDeclName()) ||
4493         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4494       RecordDecl *Record = nullptr;
4495       if (Tag)
4496         Record = dyn_cast<RecordDecl>(Tag);
4497       else if (const RecordType *RT =
4498                    DS.getRepAsType().get()->getAsStructureType())
4499         Record = RT->getDecl();
4500       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4501         Record = UT->getDecl();
4502 
4503       if (Record && getLangOpts().MicrosoftExt) {
4504         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4505             << Record->isUnion() << DS.getSourceRange();
4506         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4507       }
4508 
4509       DeclaresAnything = false;
4510     }
4511   }
4512 
4513   // Skip all the checks below if we have a type error.
4514   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4515       (TagD && TagD->isInvalidDecl()))
4516     return TagD;
4517 
4518   if (getLangOpts().CPlusPlus &&
4519       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4520     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4521       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4522           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4523         DeclaresAnything = false;
4524 
4525   if (!DS.isMissingDeclaratorOk()) {
4526     // Customize diagnostic for a typedef missing a name.
4527     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4528       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4529           << DS.getSourceRange();
4530     else
4531       DeclaresAnything = false;
4532   }
4533 
4534   if (DS.isModulePrivateSpecified() &&
4535       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4536     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4537       << Tag->getTagKind()
4538       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4539 
4540   ActOnDocumentableDecl(TagD);
4541 
4542   // C 6.7/2:
4543   //   A declaration [...] shall declare at least a declarator [...], a tag,
4544   //   or the members of an enumeration.
4545   // C++ [dcl.dcl]p3:
4546   //   [If there are no declarators], and except for the declaration of an
4547   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4548   //   names into the program, or shall redeclare a name introduced by a
4549   //   previous declaration.
4550   if (!DeclaresAnything) {
4551     // In C, we allow this as a (popular) extension / bug. Don't bother
4552     // producing further diagnostics for redundant qualifiers after this.
4553     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4554     return TagD;
4555   }
4556 
4557   // C++ [dcl.stc]p1:
4558   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4559   //   init-declarator-list of the declaration shall not be empty.
4560   // C++ [dcl.fct.spec]p1:
4561   //   If a cv-qualifier appears in a decl-specifier-seq, the
4562   //   init-declarator-list of the declaration shall not be empty.
4563   //
4564   // Spurious qualifiers here appear to be valid in C.
4565   unsigned DiagID = diag::warn_standalone_specifier;
4566   if (getLangOpts().CPlusPlus)
4567     DiagID = diag::ext_standalone_specifier;
4568 
4569   // Note that a linkage-specification sets a storage class, but
4570   // 'extern "C" struct foo;' is actually valid and not theoretically
4571   // useless.
4572   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4573     if (SCS == DeclSpec::SCS_mutable)
4574       // Since mutable is not a viable storage class specifier in C, there is
4575       // no reason to treat it as an extension. Instead, diagnose as an error.
4576       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4577     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4578       Diag(DS.getStorageClassSpecLoc(), DiagID)
4579         << DeclSpec::getSpecifierName(SCS);
4580   }
4581 
4582   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4583     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4584       << DeclSpec::getSpecifierName(TSCS);
4585   if (DS.getTypeQualifiers()) {
4586     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4587       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4588     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4589       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4590     // Restrict is covered above.
4591     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4592       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4593     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4594       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4595   }
4596 
4597   // Warn about ignored type attributes, for example:
4598   // __attribute__((aligned)) struct A;
4599   // Attributes should be placed after tag to apply to type declaration.
4600   if (!DS.getAttributes().empty()) {
4601     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4602     if (TypeSpecType == DeclSpec::TST_class ||
4603         TypeSpecType == DeclSpec::TST_struct ||
4604         TypeSpecType == DeclSpec::TST_interface ||
4605         TypeSpecType == DeclSpec::TST_union ||
4606         TypeSpecType == DeclSpec::TST_enum) {
4607       for (const ParsedAttr &AL : DS.getAttributes())
4608         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4609             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4610     }
4611   }
4612 
4613   return TagD;
4614 }
4615 
4616 /// We are trying to inject an anonymous member into the given scope;
4617 /// check if there's an existing declaration that can't be overloaded.
4618 ///
4619 /// \return true if this is a forbidden redeclaration
4620 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4621                                          Scope *S,
4622                                          DeclContext *Owner,
4623                                          DeclarationName Name,
4624                                          SourceLocation NameLoc,
4625                                          bool IsUnion) {
4626   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4627                  Sema::ForVisibleRedeclaration);
4628   if (!SemaRef.LookupName(R, S)) return false;
4629 
4630   // Pick a representative declaration.
4631   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4632   assert(PrevDecl && "Expected a non-null Decl");
4633 
4634   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4635     return false;
4636 
4637   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4638     << IsUnion << Name;
4639   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4640 
4641   return true;
4642 }
4643 
4644 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4645 /// anonymous struct or union AnonRecord into the owning context Owner
4646 /// and scope S. This routine will be invoked just after we realize
4647 /// that an unnamed union or struct is actually an anonymous union or
4648 /// struct, e.g.,
4649 ///
4650 /// @code
4651 /// union {
4652 ///   int i;
4653 ///   float f;
4654 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4655 ///    // f into the surrounding scope.x
4656 /// @endcode
4657 ///
4658 /// This routine is recursive, injecting the names of nested anonymous
4659 /// structs/unions into the owning context and scope as well.
4660 static bool
4661 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4662                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4663                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4664   bool Invalid = false;
4665 
4666   // Look every FieldDecl and IndirectFieldDecl with a name.
4667   for (auto *D : AnonRecord->decls()) {
4668     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4669         cast<NamedDecl>(D)->getDeclName()) {
4670       ValueDecl *VD = cast<ValueDecl>(D);
4671       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4672                                        VD->getLocation(),
4673                                        AnonRecord->isUnion())) {
4674         // C++ [class.union]p2:
4675         //   The names of the members of an anonymous union shall be
4676         //   distinct from the names of any other entity in the
4677         //   scope in which the anonymous union is declared.
4678         Invalid = true;
4679       } else {
4680         // C++ [class.union]p2:
4681         //   For the purpose of name lookup, after the anonymous union
4682         //   definition, the members of the anonymous union are
4683         //   considered to have been defined in the scope in which the
4684         //   anonymous union is declared.
4685         unsigned OldChainingSize = Chaining.size();
4686         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4687           Chaining.append(IF->chain_begin(), IF->chain_end());
4688         else
4689           Chaining.push_back(VD);
4690 
4691         assert(Chaining.size() >= 2);
4692         NamedDecl **NamedChain =
4693           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4694         for (unsigned i = 0; i < Chaining.size(); i++)
4695           NamedChain[i] = Chaining[i];
4696 
4697         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4698             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4699             VD->getType(), {NamedChain, Chaining.size()});
4700 
4701         for (const auto *Attr : VD->attrs())
4702           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4703 
4704         IndirectField->setAccess(AS);
4705         IndirectField->setImplicit();
4706         SemaRef.PushOnScopeChains(IndirectField, S);
4707 
4708         // That includes picking up the appropriate access specifier.
4709         if (AS != AS_none) IndirectField->setAccess(AS);
4710 
4711         Chaining.resize(OldChainingSize);
4712       }
4713     }
4714   }
4715 
4716   return Invalid;
4717 }
4718 
4719 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4720 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4721 /// illegal input values are mapped to SC_None.
4722 static StorageClass
4723 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4724   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4725   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4726          "Parser allowed 'typedef' as storage class VarDecl.");
4727   switch (StorageClassSpec) {
4728   case DeclSpec::SCS_unspecified:    return SC_None;
4729   case DeclSpec::SCS_extern:
4730     if (DS.isExternInLinkageSpec())
4731       return SC_None;
4732     return SC_Extern;
4733   case DeclSpec::SCS_static:         return SC_Static;
4734   case DeclSpec::SCS_auto:           return SC_Auto;
4735   case DeclSpec::SCS_register:       return SC_Register;
4736   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4737     // Illegal SCSs map to None: error reporting is up to the caller.
4738   case DeclSpec::SCS_mutable:        // Fall through.
4739   case DeclSpec::SCS_typedef:        return SC_None;
4740   }
4741   llvm_unreachable("unknown storage class specifier");
4742 }
4743 
4744 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4745   assert(Record->hasInClassInitializer());
4746 
4747   for (const auto *I : Record->decls()) {
4748     const auto *FD = dyn_cast<FieldDecl>(I);
4749     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4750       FD = IFD->getAnonField();
4751     if (FD && FD->hasInClassInitializer())
4752       return FD->getLocation();
4753   }
4754 
4755   llvm_unreachable("couldn't find in-class initializer");
4756 }
4757 
4758 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4759                                       SourceLocation DefaultInitLoc) {
4760   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4761     return;
4762 
4763   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4764   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4765 }
4766 
4767 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4768                                       CXXRecordDecl *AnonUnion) {
4769   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4770     return;
4771 
4772   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4773 }
4774 
4775 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4776 /// anonymous structure or union. Anonymous unions are a C++ feature
4777 /// (C++ [class.union]) and a C11 feature; anonymous structures
4778 /// are a C11 feature and GNU C++ extension.
4779 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4780                                         AccessSpecifier AS,
4781                                         RecordDecl *Record,
4782                                         const PrintingPolicy &Policy) {
4783   DeclContext *Owner = Record->getDeclContext();
4784 
4785   // Diagnose whether this anonymous struct/union is an extension.
4786   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4787     Diag(Record->getLocation(), diag::ext_anonymous_union);
4788   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4789     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4790   else if (!Record->isUnion() && !getLangOpts().C11)
4791     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4792 
4793   // C and C++ require different kinds of checks for anonymous
4794   // structs/unions.
4795   bool Invalid = false;
4796   if (getLangOpts().CPlusPlus) {
4797     const char *PrevSpec = nullptr;
4798     if (Record->isUnion()) {
4799       // C++ [class.union]p6:
4800       // C++17 [class.union.anon]p2:
4801       //   Anonymous unions declared in a named namespace or in the
4802       //   global namespace shall be declared static.
4803       unsigned DiagID;
4804       DeclContext *OwnerScope = Owner->getRedeclContext();
4805       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4806           (OwnerScope->isTranslationUnit() ||
4807            (OwnerScope->isNamespace() &&
4808             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4809         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4810           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4811 
4812         // Recover by adding 'static'.
4813         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4814                                PrevSpec, DiagID, Policy);
4815       }
4816       // C++ [class.union]p6:
4817       //   A storage class is not allowed in a declaration of an
4818       //   anonymous union in a class scope.
4819       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4820                isa<RecordDecl>(Owner)) {
4821         Diag(DS.getStorageClassSpecLoc(),
4822              diag::err_anonymous_union_with_storage_spec)
4823           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4824 
4825         // Recover by removing the storage specifier.
4826         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4827                                SourceLocation(),
4828                                PrevSpec, DiagID, Context.getPrintingPolicy());
4829       }
4830     }
4831 
4832     // Ignore const/volatile/restrict qualifiers.
4833     if (DS.getTypeQualifiers()) {
4834       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4835         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4836           << Record->isUnion() << "const"
4837           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4838       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4839         Diag(DS.getVolatileSpecLoc(),
4840              diag::ext_anonymous_struct_union_qualified)
4841           << Record->isUnion() << "volatile"
4842           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4843       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4844         Diag(DS.getRestrictSpecLoc(),
4845              diag::ext_anonymous_struct_union_qualified)
4846           << Record->isUnion() << "restrict"
4847           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4848       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4849         Diag(DS.getAtomicSpecLoc(),
4850              diag::ext_anonymous_struct_union_qualified)
4851           << Record->isUnion() << "_Atomic"
4852           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4853       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4854         Diag(DS.getUnalignedSpecLoc(),
4855              diag::ext_anonymous_struct_union_qualified)
4856           << Record->isUnion() << "__unaligned"
4857           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4858 
4859       DS.ClearTypeQualifiers();
4860     }
4861 
4862     // C++ [class.union]p2:
4863     //   The member-specification of an anonymous union shall only
4864     //   define non-static data members. [Note: nested types and
4865     //   functions cannot be declared within an anonymous union. ]
4866     for (auto *Mem : Record->decls()) {
4867       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4868         // C++ [class.union]p3:
4869         //   An anonymous union shall not have private or protected
4870         //   members (clause 11).
4871         assert(FD->getAccess() != AS_none);
4872         if (FD->getAccess() != AS_public) {
4873           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4874             << Record->isUnion() << (FD->getAccess() == AS_protected);
4875           Invalid = true;
4876         }
4877 
4878         // C++ [class.union]p1
4879         //   An object of a class with a non-trivial constructor, a non-trivial
4880         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4881         //   assignment operator cannot be a member of a union, nor can an
4882         //   array of such objects.
4883         if (CheckNontrivialField(FD))
4884           Invalid = true;
4885       } else if (Mem->isImplicit()) {
4886         // Any implicit members are fine.
4887       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4888         // This is a type that showed up in an
4889         // elaborated-type-specifier inside the anonymous struct or
4890         // union, but which actually declares a type outside of the
4891         // anonymous struct or union. It's okay.
4892       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4893         if (!MemRecord->isAnonymousStructOrUnion() &&
4894             MemRecord->getDeclName()) {
4895           // Visual C++ allows type definition in anonymous struct or union.
4896           if (getLangOpts().MicrosoftExt)
4897             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4898               << Record->isUnion();
4899           else {
4900             // This is a nested type declaration.
4901             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4902               << Record->isUnion();
4903             Invalid = true;
4904           }
4905         } else {
4906           // This is an anonymous type definition within another anonymous type.
4907           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4908           // not part of standard C++.
4909           Diag(MemRecord->getLocation(),
4910                diag::ext_anonymous_record_with_anonymous_type)
4911             << Record->isUnion();
4912         }
4913       } else if (isa<AccessSpecDecl>(Mem)) {
4914         // Any access specifier is fine.
4915       } else if (isa<StaticAssertDecl>(Mem)) {
4916         // In C++1z, static_assert declarations are also fine.
4917       } else {
4918         // We have something that isn't a non-static data
4919         // member. Complain about it.
4920         unsigned DK = diag::err_anonymous_record_bad_member;
4921         if (isa<TypeDecl>(Mem))
4922           DK = diag::err_anonymous_record_with_type;
4923         else if (isa<FunctionDecl>(Mem))
4924           DK = diag::err_anonymous_record_with_function;
4925         else if (isa<VarDecl>(Mem))
4926           DK = diag::err_anonymous_record_with_static;
4927 
4928         // Visual C++ allows type definition in anonymous struct or union.
4929         if (getLangOpts().MicrosoftExt &&
4930             DK == diag::err_anonymous_record_with_type)
4931           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4932             << Record->isUnion();
4933         else {
4934           Diag(Mem->getLocation(), DK) << Record->isUnion();
4935           Invalid = true;
4936         }
4937       }
4938     }
4939 
4940     // C++11 [class.union]p8 (DR1460):
4941     //   At most one variant member of a union may have a
4942     //   brace-or-equal-initializer.
4943     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4944         Owner->isRecord())
4945       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4946                                 cast<CXXRecordDecl>(Record));
4947   }
4948 
4949   if (!Record->isUnion() && !Owner->isRecord()) {
4950     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4951       << getLangOpts().CPlusPlus;
4952     Invalid = true;
4953   }
4954 
4955   // C++ [dcl.dcl]p3:
4956   //   [If there are no declarators], and except for the declaration of an
4957   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4958   //   names into the program
4959   // C++ [class.mem]p2:
4960   //   each such member-declaration shall either declare at least one member
4961   //   name of the class or declare at least one unnamed bit-field
4962   //
4963   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4964   if (getLangOpts().CPlusPlus && Record->field_empty())
4965     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4966 
4967   // Mock up a declarator.
4968   Declarator Dc(DS, DeclaratorContext::MemberContext);
4969   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4970   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4971 
4972   // Create a declaration for this anonymous struct/union.
4973   NamedDecl *Anon = nullptr;
4974   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4975     Anon = FieldDecl::Create(
4976         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4977         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4978         /*BitWidth=*/nullptr, /*Mutable=*/false,
4979         /*InitStyle=*/ICIS_NoInit);
4980     Anon->setAccess(AS);
4981     if (getLangOpts().CPlusPlus)
4982       FieldCollector->Add(cast<FieldDecl>(Anon));
4983   } else {
4984     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4985     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4986     if (SCSpec == DeclSpec::SCS_mutable) {
4987       // mutable can only appear on non-static class members, so it's always
4988       // an error here
4989       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4990       Invalid = true;
4991       SC = SC_None;
4992     }
4993 
4994     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4995                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4996                            Context.getTypeDeclType(Record), TInfo, SC);
4997 
4998     // Default-initialize the implicit variable. This initialization will be
4999     // trivial in almost all cases, except if a union member has an in-class
5000     // initializer:
5001     //   union { int n = 0; };
5002     ActOnUninitializedDecl(Anon);
5003   }
5004   Anon->setImplicit();
5005 
5006   // Mark this as an anonymous struct/union type.
5007   Record->setAnonymousStructOrUnion(true);
5008 
5009   // Add the anonymous struct/union object to the current
5010   // context. We'll be referencing this object when we refer to one of
5011   // its members.
5012   Owner->addDecl(Anon);
5013 
5014   // Inject the members of the anonymous struct/union into the owning
5015   // context and into the identifier resolver chain for name lookup
5016   // purposes.
5017   SmallVector<NamedDecl*, 2> Chain;
5018   Chain.push_back(Anon);
5019 
5020   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5021     Invalid = true;
5022 
5023   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5024     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5025       Decl *ManglingContextDecl;
5026       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
5027               NewVD->getDeclContext(), ManglingContextDecl)) {
5028         Context.setManglingNumber(
5029             NewVD, MCtx->getManglingNumber(
5030                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5031         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5032       }
5033     }
5034   }
5035 
5036   if (Invalid)
5037     Anon->setInvalidDecl();
5038 
5039   return Anon;
5040 }
5041 
5042 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5043 /// Microsoft C anonymous structure.
5044 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5045 /// Example:
5046 ///
5047 /// struct A { int a; };
5048 /// struct B { struct A; int b; };
5049 ///
5050 /// void foo() {
5051 ///   B var;
5052 ///   var.a = 3;
5053 /// }
5054 ///
5055 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5056                                            RecordDecl *Record) {
5057   assert(Record && "expected a record!");
5058 
5059   // Mock up a declarator.
5060   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5061   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5062   assert(TInfo && "couldn't build declarator info for anonymous struct");
5063 
5064   auto *ParentDecl = cast<RecordDecl>(CurContext);
5065   QualType RecTy = Context.getTypeDeclType(Record);
5066 
5067   // Create a declaration for this anonymous struct.
5068   NamedDecl *Anon =
5069       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5070                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5071                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5072                         /*InitStyle=*/ICIS_NoInit);
5073   Anon->setImplicit();
5074 
5075   // Add the anonymous struct object to the current context.
5076   CurContext->addDecl(Anon);
5077 
5078   // Inject the members of the anonymous struct into the current
5079   // context and into the identifier resolver chain for name lookup
5080   // purposes.
5081   SmallVector<NamedDecl*, 2> Chain;
5082   Chain.push_back(Anon);
5083 
5084   RecordDecl *RecordDef = Record->getDefinition();
5085   if (RequireCompleteType(Anon->getLocation(), RecTy,
5086                           diag::err_field_incomplete) ||
5087       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5088                                           AS_none, Chain)) {
5089     Anon->setInvalidDecl();
5090     ParentDecl->setInvalidDecl();
5091   }
5092 
5093   return Anon;
5094 }
5095 
5096 /// GetNameForDeclarator - Determine the full declaration name for the
5097 /// given Declarator.
5098 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5099   return GetNameFromUnqualifiedId(D.getName());
5100 }
5101 
5102 /// Retrieves the declaration name from a parsed unqualified-id.
5103 DeclarationNameInfo
5104 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5105   DeclarationNameInfo NameInfo;
5106   NameInfo.setLoc(Name.StartLocation);
5107 
5108   switch (Name.getKind()) {
5109 
5110   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5111   case UnqualifiedIdKind::IK_Identifier:
5112     NameInfo.setName(Name.Identifier);
5113     return NameInfo;
5114 
5115   case UnqualifiedIdKind::IK_DeductionGuideName: {
5116     // C++ [temp.deduct.guide]p3:
5117     //   The simple-template-id shall name a class template specialization.
5118     //   The template-name shall be the same identifier as the template-name
5119     //   of the simple-template-id.
5120     // These together intend to imply that the template-name shall name a
5121     // class template.
5122     // FIXME: template<typename T> struct X {};
5123     //        template<typename T> using Y = X<T>;
5124     //        Y(int) -> Y<int>;
5125     //   satisfies these rules but does not name a class template.
5126     TemplateName TN = Name.TemplateName.get().get();
5127     auto *Template = TN.getAsTemplateDecl();
5128     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5129       Diag(Name.StartLocation,
5130            diag::err_deduction_guide_name_not_class_template)
5131         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5132       if (Template)
5133         Diag(Template->getLocation(), diag::note_template_decl_here);
5134       return DeclarationNameInfo();
5135     }
5136 
5137     NameInfo.setName(
5138         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5139     return NameInfo;
5140   }
5141 
5142   case UnqualifiedIdKind::IK_OperatorFunctionId:
5143     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5144                                            Name.OperatorFunctionId.Operator));
5145     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5146       = Name.OperatorFunctionId.SymbolLocations[0];
5147     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5148       = Name.EndLocation.getRawEncoding();
5149     return NameInfo;
5150 
5151   case UnqualifiedIdKind::IK_LiteralOperatorId:
5152     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5153                                                            Name.Identifier));
5154     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5155     return NameInfo;
5156 
5157   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5158     TypeSourceInfo *TInfo;
5159     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5160     if (Ty.isNull())
5161       return DeclarationNameInfo();
5162     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5163                                                Context.getCanonicalType(Ty)));
5164     NameInfo.setNamedTypeInfo(TInfo);
5165     return NameInfo;
5166   }
5167 
5168   case UnqualifiedIdKind::IK_ConstructorName: {
5169     TypeSourceInfo *TInfo;
5170     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5171     if (Ty.isNull())
5172       return DeclarationNameInfo();
5173     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5174                                               Context.getCanonicalType(Ty)));
5175     NameInfo.setNamedTypeInfo(TInfo);
5176     return NameInfo;
5177   }
5178 
5179   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5180     // In well-formed code, we can only have a constructor
5181     // template-id that refers to the current context, so go there
5182     // to find the actual type being constructed.
5183     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5184     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5185       return DeclarationNameInfo();
5186 
5187     // Determine the type of the class being constructed.
5188     QualType CurClassType = Context.getTypeDeclType(CurClass);
5189 
5190     // FIXME: Check two things: that the template-id names the same type as
5191     // CurClassType, and that the template-id does not occur when the name
5192     // was qualified.
5193 
5194     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5195                                     Context.getCanonicalType(CurClassType)));
5196     // FIXME: should we retrieve TypeSourceInfo?
5197     NameInfo.setNamedTypeInfo(nullptr);
5198     return NameInfo;
5199   }
5200 
5201   case UnqualifiedIdKind::IK_DestructorName: {
5202     TypeSourceInfo *TInfo;
5203     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5204     if (Ty.isNull())
5205       return DeclarationNameInfo();
5206     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5207                                               Context.getCanonicalType(Ty)));
5208     NameInfo.setNamedTypeInfo(TInfo);
5209     return NameInfo;
5210   }
5211 
5212   case UnqualifiedIdKind::IK_TemplateId: {
5213     TemplateName TName = Name.TemplateId->Template.get();
5214     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5215     return Context.getNameForTemplate(TName, TNameLoc);
5216   }
5217 
5218   } // switch (Name.getKind())
5219 
5220   llvm_unreachable("Unknown name kind");
5221 }
5222 
5223 static QualType getCoreType(QualType Ty) {
5224   do {
5225     if (Ty->isPointerType() || Ty->isReferenceType())
5226       Ty = Ty->getPointeeType();
5227     else if (Ty->isArrayType())
5228       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5229     else
5230       return Ty.withoutLocalFastQualifiers();
5231   } while (true);
5232 }
5233 
5234 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5235 /// and Definition have "nearly" matching parameters. This heuristic is
5236 /// used to improve diagnostics in the case where an out-of-line function
5237 /// definition doesn't match any declaration within the class or namespace.
5238 /// Also sets Params to the list of indices to the parameters that differ
5239 /// between the declaration and the definition. If hasSimilarParameters
5240 /// returns true and Params is empty, then all of the parameters match.
5241 static bool hasSimilarParameters(ASTContext &Context,
5242                                      FunctionDecl *Declaration,
5243                                      FunctionDecl *Definition,
5244                                      SmallVectorImpl<unsigned> &Params) {
5245   Params.clear();
5246   if (Declaration->param_size() != Definition->param_size())
5247     return false;
5248   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5249     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5250     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5251 
5252     // The parameter types are identical
5253     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5254       continue;
5255 
5256     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5257     QualType DefParamBaseTy = getCoreType(DefParamTy);
5258     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5259     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5260 
5261     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5262         (DeclTyName && DeclTyName == DefTyName))
5263       Params.push_back(Idx);
5264     else  // The two parameters aren't even close
5265       return false;
5266   }
5267 
5268   return true;
5269 }
5270 
5271 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5272 /// declarator needs to be rebuilt in the current instantiation.
5273 /// Any bits of declarator which appear before the name are valid for
5274 /// consideration here.  That's specifically the type in the decl spec
5275 /// and the base type in any member-pointer chunks.
5276 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5277                                                     DeclarationName Name) {
5278   // The types we specifically need to rebuild are:
5279   //   - typenames, typeofs, and decltypes
5280   //   - types which will become injected class names
5281   // Of course, we also need to rebuild any type referencing such a
5282   // type.  It's safest to just say "dependent", but we call out a
5283   // few cases here.
5284 
5285   DeclSpec &DS = D.getMutableDeclSpec();
5286   switch (DS.getTypeSpecType()) {
5287   case DeclSpec::TST_typename:
5288   case DeclSpec::TST_typeofType:
5289   case DeclSpec::TST_underlyingType:
5290   case DeclSpec::TST_atomic: {
5291     // Grab the type from the parser.
5292     TypeSourceInfo *TSI = nullptr;
5293     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5294     if (T.isNull() || !T->isDependentType()) break;
5295 
5296     // Make sure there's a type source info.  This isn't really much
5297     // of a waste; most dependent types should have type source info
5298     // attached already.
5299     if (!TSI)
5300       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5301 
5302     // Rebuild the type in the current instantiation.
5303     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5304     if (!TSI) return true;
5305 
5306     // Store the new type back in the decl spec.
5307     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5308     DS.UpdateTypeRep(LocType);
5309     break;
5310   }
5311 
5312   case DeclSpec::TST_decltype:
5313   case DeclSpec::TST_typeofExpr: {
5314     Expr *E = DS.getRepAsExpr();
5315     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5316     if (Result.isInvalid()) return true;
5317     DS.UpdateExprRep(Result.get());
5318     break;
5319   }
5320 
5321   default:
5322     // Nothing to do for these decl specs.
5323     break;
5324   }
5325 
5326   // It doesn't matter what order we do this in.
5327   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5328     DeclaratorChunk &Chunk = D.getTypeObject(I);
5329 
5330     // The only type information in the declarator which can come
5331     // before the declaration name is the base type of a member
5332     // pointer.
5333     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5334       continue;
5335 
5336     // Rebuild the scope specifier in-place.
5337     CXXScopeSpec &SS = Chunk.Mem.Scope();
5338     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5339       return true;
5340   }
5341 
5342   return false;
5343 }
5344 
5345 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5346   D.setFunctionDefinitionKind(FDK_Declaration);
5347   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5348 
5349   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5350       Dcl && Dcl->getDeclContext()->isFileContext())
5351     Dcl->setTopLevelDeclInObjCContainer();
5352 
5353   if (getLangOpts().OpenCL)
5354     setCurrentOpenCLExtensionForDecl(Dcl);
5355 
5356   return Dcl;
5357 }
5358 
5359 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5360 ///   If T is the name of a class, then each of the following shall have a
5361 ///   name different from T:
5362 ///     - every static data member of class T;
5363 ///     - every member function of class T
5364 ///     - every member of class T that is itself a type;
5365 /// \returns true if the declaration name violates these rules.
5366 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5367                                    DeclarationNameInfo NameInfo) {
5368   DeclarationName Name = NameInfo.getName();
5369 
5370   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5371   while (Record && Record->isAnonymousStructOrUnion())
5372     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5373   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5374     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5375     return true;
5376   }
5377 
5378   return false;
5379 }
5380 
5381 /// Diagnose a declaration whose declarator-id has the given
5382 /// nested-name-specifier.
5383 ///
5384 /// \param SS The nested-name-specifier of the declarator-id.
5385 ///
5386 /// \param DC The declaration context to which the nested-name-specifier
5387 /// resolves.
5388 ///
5389 /// \param Name The name of the entity being declared.
5390 ///
5391 /// \param Loc The location of the name of the entity being declared.
5392 ///
5393 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5394 /// we're declaring an explicit / partial specialization / instantiation.
5395 ///
5396 /// \returns true if we cannot safely recover from this error, false otherwise.
5397 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5398                                         DeclarationName Name,
5399                                         SourceLocation Loc, bool IsTemplateId) {
5400   DeclContext *Cur = CurContext;
5401   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5402     Cur = Cur->getParent();
5403 
5404   // If the user provided a superfluous scope specifier that refers back to the
5405   // class in which the entity is already declared, diagnose and ignore it.
5406   //
5407   // class X {
5408   //   void X::f();
5409   // };
5410   //
5411   // Note, it was once ill-formed to give redundant qualification in all
5412   // contexts, but that rule was removed by DR482.
5413   if (Cur->Equals(DC)) {
5414     if (Cur->isRecord()) {
5415       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5416                                       : diag::err_member_extra_qualification)
5417         << Name << FixItHint::CreateRemoval(SS.getRange());
5418       SS.clear();
5419     } else {
5420       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5421     }
5422     return false;
5423   }
5424 
5425   // Check whether the qualifying scope encloses the scope of the original
5426   // declaration. For a template-id, we perform the checks in
5427   // CheckTemplateSpecializationScope.
5428   if (!Cur->Encloses(DC) && !IsTemplateId) {
5429     if (Cur->isRecord())
5430       Diag(Loc, diag::err_member_qualification)
5431         << Name << SS.getRange();
5432     else if (isa<TranslationUnitDecl>(DC))
5433       Diag(Loc, diag::err_invalid_declarator_global_scope)
5434         << Name << SS.getRange();
5435     else if (isa<FunctionDecl>(Cur))
5436       Diag(Loc, diag::err_invalid_declarator_in_function)
5437         << Name << SS.getRange();
5438     else if (isa<BlockDecl>(Cur))
5439       Diag(Loc, diag::err_invalid_declarator_in_block)
5440         << Name << SS.getRange();
5441     else
5442       Diag(Loc, diag::err_invalid_declarator_scope)
5443       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5444 
5445     return true;
5446   }
5447 
5448   if (Cur->isRecord()) {
5449     // Cannot qualify members within a class.
5450     Diag(Loc, diag::err_member_qualification)
5451       << Name << SS.getRange();
5452     SS.clear();
5453 
5454     // C++ constructors and destructors with incorrect scopes can break
5455     // our AST invariants by having the wrong underlying types. If
5456     // that's the case, then drop this declaration entirely.
5457     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5458          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5459         !Context.hasSameType(Name.getCXXNameType(),
5460                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5461       return true;
5462 
5463     return false;
5464   }
5465 
5466   // C++11 [dcl.meaning]p1:
5467   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5468   //   not begin with a decltype-specifer"
5469   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5470   while (SpecLoc.getPrefix())
5471     SpecLoc = SpecLoc.getPrefix();
5472   if (dyn_cast_or_null<DecltypeType>(
5473         SpecLoc.getNestedNameSpecifier()->getAsType()))
5474     Diag(Loc, diag::err_decltype_in_declarator)
5475       << SpecLoc.getTypeLoc().getSourceRange();
5476 
5477   return false;
5478 }
5479 
5480 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5481                                   MultiTemplateParamsArg TemplateParamLists) {
5482   // TODO: consider using NameInfo for diagnostic.
5483   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5484   DeclarationName Name = NameInfo.getName();
5485 
5486   // All of these full declarators require an identifier.  If it doesn't have
5487   // one, the ParsedFreeStandingDeclSpec action should be used.
5488   if (D.isDecompositionDeclarator()) {
5489     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5490   } else if (!Name) {
5491     if (!D.isInvalidType())  // Reject this if we think it is valid.
5492       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5493           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5494     return nullptr;
5495   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5496     return nullptr;
5497 
5498   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5499   // we find one that is.
5500   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5501          (S->getFlags() & Scope::TemplateParamScope) != 0)
5502     S = S->getParent();
5503 
5504   DeclContext *DC = CurContext;
5505   if (D.getCXXScopeSpec().isInvalid())
5506     D.setInvalidType();
5507   else if (D.getCXXScopeSpec().isSet()) {
5508     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5509                                         UPPC_DeclarationQualifier))
5510       return nullptr;
5511 
5512     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5513     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5514     if (!DC || isa<EnumDecl>(DC)) {
5515       // If we could not compute the declaration context, it's because the
5516       // declaration context is dependent but does not refer to a class,
5517       // class template, or class template partial specialization. Complain
5518       // and return early, to avoid the coming semantic disaster.
5519       Diag(D.getIdentifierLoc(),
5520            diag::err_template_qualified_declarator_no_match)
5521         << D.getCXXScopeSpec().getScopeRep()
5522         << D.getCXXScopeSpec().getRange();
5523       return nullptr;
5524     }
5525     bool IsDependentContext = DC->isDependentContext();
5526 
5527     if (!IsDependentContext &&
5528         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5529       return nullptr;
5530 
5531     // If a class is incomplete, do not parse entities inside it.
5532     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5533       Diag(D.getIdentifierLoc(),
5534            diag::err_member_def_undefined_record)
5535         << Name << DC << D.getCXXScopeSpec().getRange();
5536       return nullptr;
5537     }
5538     if (!D.getDeclSpec().isFriendSpecified()) {
5539       if (diagnoseQualifiedDeclaration(
5540               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5541               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5542         if (DC->isRecord())
5543           return nullptr;
5544 
5545         D.setInvalidType();
5546       }
5547     }
5548 
5549     // Check whether we need to rebuild the type of the given
5550     // declaration in the current instantiation.
5551     if (EnteringContext && IsDependentContext &&
5552         TemplateParamLists.size() != 0) {
5553       ContextRAII SavedContext(*this, DC);
5554       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5555         D.setInvalidType();
5556     }
5557   }
5558 
5559   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5560   QualType R = TInfo->getType();
5561 
5562   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5563                                       UPPC_DeclarationType))
5564     D.setInvalidType();
5565 
5566   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5567                         forRedeclarationInCurContext());
5568 
5569   // See if this is a redefinition of a variable in the same scope.
5570   if (!D.getCXXScopeSpec().isSet()) {
5571     bool IsLinkageLookup = false;
5572     bool CreateBuiltins = false;
5573 
5574     // If the declaration we're planning to build will be a function
5575     // or object with linkage, then look for another declaration with
5576     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5577     //
5578     // If the declaration we're planning to build will be declared with
5579     // external linkage in the translation unit, create any builtin with
5580     // the same name.
5581     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5582       /* Do nothing*/;
5583     else if (CurContext->isFunctionOrMethod() &&
5584              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5585               R->isFunctionType())) {
5586       IsLinkageLookup = true;
5587       CreateBuiltins =
5588           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5589     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5590                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5591       CreateBuiltins = true;
5592 
5593     if (IsLinkageLookup) {
5594       Previous.clear(LookupRedeclarationWithLinkage);
5595       Previous.setRedeclarationKind(ForExternalRedeclaration);
5596     }
5597 
5598     LookupName(Previous, S, CreateBuiltins);
5599   } else { // Something like "int foo::x;"
5600     LookupQualifiedName(Previous, DC);
5601 
5602     // C++ [dcl.meaning]p1:
5603     //   When the declarator-id is qualified, the declaration shall refer to a
5604     //  previously declared member of the class or namespace to which the
5605     //  qualifier refers (or, in the case of a namespace, of an element of the
5606     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5607     //  thereof; [...]
5608     //
5609     // Note that we already checked the context above, and that we do not have
5610     // enough information to make sure that Previous contains the declaration
5611     // we want to match. For example, given:
5612     //
5613     //   class X {
5614     //     void f();
5615     //     void f(float);
5616     //   };
5617     //
5618     //   void X::f(int) { } // ill-formed
5619     //
5620     // In this case, Previous will point to the overload set
5621     // containing the two f's declared in X, but neither of them
5622     // matches.
5623 
5624     // C++ [dcl.meaning]p1:
5625     //   [...] the member shall not merely have been introduced by a
5626     //   using-declaration in the scope of the class or namespace nominated by
5627     //   the nested-name-specifier of the declarator-id.
5628     RemoveUsingDecls(Previous);
5629   }
5630 
5631   if (Previous.isSingleResult() &&
5632       Previous.getFoundDecl()->isTemplateParameter()) {
5633     // Maybe we will complain about the shadowed template parameter.
5634     if (!D.isInvalidType())
5635       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5636                                       Previous.getFoundDecl());
5637 
5638     // Just pretend that we didn't see the previous declaration.
5639     Previous.clear();
5640   }
5641 
5642   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5643     // Forget that the previous declaration is the injected-class-name.
5644     Previous.clear();
5645 
5646   // In C++, the previous declaration we find might be a tag type
5647   // (class or enum). In this case, the new declaration will hide the
5648   // tag type. Note that this applies to functions, function templates, and
5649   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5650   if (Previous.isSingleTagDecl() &&
5651       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5652       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5653     Previous.clear();
5654 
5655   // Check that there are no default arguments other than in the parameters
5656   // of a function declaration (C++ only).
5657   if (getLangOpts().CPlusPlus)
5658     CheckExtraCXXDefaultArguments(D);
5659 
5660   NamedDecl *New;
5661 
5662   bool AddToScope = true;
5663   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5664     if (TemplateParamLists.size()) {
5665       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5666       return nullptr;
5667     }
5668 
5669     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5670   } else if (R->isFunctionType()) {
5671     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5672                                   TemplateParamLists,
5673                                   AddToScope);
5674   } else {
5675     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5676                                   AddToScope);
5677   }
5678 
5679   if (!New)
5680     return nullptr;
5681 
5682   // If this has an identifier and is not a function template specialization,
5683   // add it to the scope stack.
5684   if (New->getDeclName() && AddToScope)
5685     PushOnScopeChains(New, S);
5686 
5687   if (isInOpenMPDeclareTargetContext())
5688     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5689 
5690   return New;
5691 }
5692 
5693 /// Helper method to turn variable array types into constant array
5694 /// types in certain situations which would otherwise be errors (for
5695 /// GCC compatibility).
5696 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5697                                                     ASTContext &Context,
5698                                                     bool &SizeIsNegative,
5699                                                     llvm::APSInt &Oversized) {
5700   // This method tries to turn a variable array into a constant
5701   // array even when the size isn't an ICE.  This is necessary
5702   // for compatibility with code that depends on gcc's buggy
5703   // constant expression folding, like struct {char x[(int)(char*)2];}
5704   SizeIsNegative = false;
5705   Oversized = 0;
5706 
5707   if (T->isDependentType())
5708     return QualType();
5709 
5710   QualifierCollector Qs;
5711   const Type *Ty = Qs.strip(T);
5712 
5713   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5714     QualType Pointee = PTy->getPointeeType();
5715     QualType FixedType =
5716         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5717                                             Oversized);
5718     if (FixedType.isNull()) return FixedType;
5719     FixedType = Context.getPointerType(FixedType);
5720     return Qs.apply(Context, FixedType);
5721   }
5722   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5723     QualType Inner = PTy->getInnerType();
5724     QualType FixedType =
5725         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5726                                             Oversized);
5727     if (FixedType.isNull()) return FixedType;
5728     FixedType = Context.getParenType(FixedType);
5729     return Qs.apply(Context, FixedType);
5730   }
5731 
5732   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5733   if (!VLATy)
5734     return QualType();
5735   // FIXME: We should probably handle this case
5736   if (VLATy->getElementType()->isVariablyModifiedType())
5737     return QualType();
5738 
5739   Expr::EvalResult Result;
5740   if (!VLATy->getSizeExpr() ||
5741       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5742     return QualType();
5743 
5744   llvm::APSInt Res = Result.Val.getInt();
5745 
5746   // Check whether the array size is negative.
5747   if (Res.isSigned() && Res.isNegative()) {
5748     SizeIsNegative = true;
5749     return QualType();
5750   }
5751 
5752   // Check whether the array is too large to be addressed.
5753   unsigned ActiveSizeBits
5754     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5755                                               Res);
5756   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5757     Oversized = Res;
5758     return QualType();
5759   }
5760 
5761   return Context.getConstantArrayType(VLATy->getElementType(),
5762                                       Res, ArrayType::Normal, 0);
5763 }
5764 
5765 static void
5766 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5767   SrcTL = SrcTL.getUnqualifiedLoc();
5768   DstTL = DstTL.getUnqualifiedLoc();
5769   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5770     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5771     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5772                                       DstPTL.getPointeeLoc());
5773     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5774     return;
5775   }
5776   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5777     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5778     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5779                                       DstPTL.getInnerLoc());
5780     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5781     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5782     return;
5783   }
5784   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5785   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5786   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5787   TypeLoc DstElemTL = DstATL.getElementLoc();
5788   DstElemTL.initializeFullCopy(SrcElemTL);
5789   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5790   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5791   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5792 }
5793 
5794 /// Helper method to turn variable array types into constant array
5795 /// types in certain situations which would otherwise be errors (for
5796 /// GCC compatibility).
5797 static TypeSourceInfo*
5798 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5799                                               ASTContext &Context,
5800                                               bool &SizeIsNegative,
5801                                               llvm::APSInt &Oversized) {
5802   QualType FixedTy
5803     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5804                                           SizeIsNegative, Oversized);
5805   if (FixedTy.isNull())
5806     return nullptr;
5807   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5808   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5809                                     FixedTInfo->getTypeLoc());
5810   return FixedTInfo;
5811 }
5812 
5813 /// Register the given locally-scoped extern "C" declaration so
5814 /// that it can be found later for redeclarations. We include any extern "C"
5815 /// declaration that is not visible in the translation unit here, not just
5816 /// function-scope declarations.
5817 void
5818 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5819   if (!getLangOpts().CPlusPlus &&
5820       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5821     // Don't need to track declarations in the TU in C.
5822     return;
5823 
5824   // Note that we have a locally-scoped external with this name.
5825   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5826 }
5827 
5828 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5829   // FIXME: We can have multiple results via __attribute__((overloadable)).
5830   auto Result = Context.getExternCContextDecl()->lookup(Name);
5831   return Result.empty() ? nullptr : *Result.begin();
5832 }
5833 
5834 /// Diagnose function specifiers on a declaration of an identifier that
5835 /// does not identify a function.
5836 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5837   // FIXME: We should probably indicate the identifier in question to avoid
5838   // confusion for constructs like "virtual int a(), b;"
5839   if (DS.isVirtualSpecified())
5840     Diag(DS.getVirtualSpecLoc(),
5841          diag::err_virtual_non_function);
5842 
5843   if (DS.hasExplicitSpecifier())
5844     Diag(DS.getExplicitSpecLoc(),
5845          diag::err_explicit_non_function);
5846 
5847   if (DS.isNoreturnSpecified())
5848     Diag(DS.getNoreturnSpecLoc(),
5849          diag::err_noreturn_non_function);
5850 }
5851 
5852 NamedDecl*
5853 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5854                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5855   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5856   if (D.getCXXScopeSpec().isSet()) {
5857     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5858       << D.getCXXScopeSpec().getRange();
5859     D.setInvalidType();
5860     // Pretend we didn't see the scope specifier.
5861     DC = CurContext;
5862     Previous.clear();
5863   }
5864 
5865   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5866 
5867   if (D.getDeclSpec().isInlineSpecified())
5868     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5869         << getLangOpts().CPlusPlus17;
5870   if (D.getDeclSpec().hasConstexprSpecifier())
5871     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5872         << 1 << D.getDeclSpec().getConstexprSpecifier();
5873 
5874   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5875     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5876       Diag(D.getName().StartLocation,
5877            diag::err_deduction_guide_invalid_specifier)
5878           << "typedef";
5879     else
5880       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5881           << D.getName().getSourceRange();
5882     return nullptr;
5883   }
5884 
5885   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5886   if (!NewTD) return nullptr;
5887 
5888   // Handle attributes prior to checking for duplicates in MergeVarDecl
5889   ProcessDeclAttributes(S, NewTD, D);
5890 
5891   CheckTypedefForVariablyModifiedType(S, NewTD);
5892 
5893   bool Redeclaration = D.isRedeclaration();
5894   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5895   D.setRedeclaration(Redeclaration);
5896   return ND;
5897 }
5898 
5899 void
5900 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5901   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5902   // then it shall have block scope.
5903   // Note that variably modified types must be fixed before merging the decl so
5904   // that redeclarations will match.
5905   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5906   QualType T = TInfo->getType();
5907   if (T->isVariablyModifiedType()) {
5908     setFunctionHasBranchProtectedScope();
5909 
5910     if (S->getFnParent() == nullptr) {
5911       bool SizeIsNegative;
5912       llvm::APSInt Oversized;
5913       TypeSourceInfo *FixedTInfo =
5914         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5915                                                       SizeIsNegative,
5916                                                       Oversized);
5917       if (FixedTInfo) {
5918         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5919         NewTD->setTypeSourceInfo(FixedTInfo);
5920       } else {
5921         if (SizeIsNegative)
5922           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5923         else if (T->isVariableArrayType())
5924           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5925         else if (Oversized.getBoolValue())
5926           Diag(NewTD->getLocation(), diag::err_array_too_large)
5927             << Oversized.toString(10);
5928         else
5929           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5930         NewTD->setInvalidDecl();
5931       }
5932     }
5933   }
5934 }
5935 
5936 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5937 /// declares a typedef-name, either using the 'typedef' type specifier or via
5938 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5939 NamedDecl*
5940 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5941                            LookupResult &Previous, bool &Redeclaration) {
5942 
5943   // Find the shadowed declaration before filtering for scope.
5944   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5945 
5946   // Merge the decl with the existing one if appropriate. If the decl is
5947   // in an outer scope, it isn't the same thing.
5948   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5949                        /*AllowInlineNamespace*/false);
5950   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5951   if (!Previous.empty()) {
5952     Redeclaration = true;
5953     MergeTypedefNameDecl(S, NewTD, Previous);
5954   } else {
5955     inferGslPointerAttribute(NewTD);
5956   }
5957 
5958   if (ShadowedDecl && !Redeclaration)
5959     CheckShadow(NewTD, ShadowedDecl, Previous);
5960 
5961   // If this is the C FILE type, notify the AST context.
5962   if (IdentifierInfo *II = NewTD->getIdentifier())
5963     if (!NewTD->isInvalidDecl() &&
5964         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5965       if (II->isStr("FILE"))
5966         Context.setFILEDecl(NewTD);
5967       else if (II->isStr("jmp_buf"))
5968         Context.setjmp_bufDecl(NewTD);
5969       else if (II->isStr("sigjmp_buf"))
5970         Context.setsigjmp_bufDecl(NewTD);
5971       else if (II->isStr("ucontext_t"))
5972         Context.setucontext_tDecl(NewTD);
5973     }
5974 
5975   return NewTD;
5976 }
5977 
5978 /// Determines whether the given declaration is an out-of-scope
5979 /// previous declaration.
5980 ///
5981 /// This routine should be invoked when name lookup has found a
5982 /// previous declaration (PrevDecl) that is not in the scope where a
5983 /// new declaration by the same name is being introduced. If the new
5984 /// declaration occurs in a local scope, previous declarations with
5985 /// linkage may still be considered previous declarations (C99
5986 /// 6.2.2p4-5, C++ [basic.link]p6).
5987 ///
5988 /// \param PrevDecl the previous declaration found by name
5989 /// lookup
5990 ///
5991 /// \param DC the context in which the new declaration is being
5992 /// declared.
5993 ///
5994 /// \returns true if PrevDecl is an out-of-scope previous declaration
5995 /// for a new delcaration with the same name.
5996 static bool
5997 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5998                                 ASTContext &Context) {
5999   if (!PrevDecl)
6000     return false;
6001 
6002   if (!PrevDecl->hasLinkage())
6003     return false;
6004 
6005   if (Context.getLangOpts().CPlusPlus) {
6006     // C++ [basic.link]p6:
6007     //   If there is a visible declaration of an entity with linkage
6008     //   having the same name and type, ignoring entities declared
6009     //   outside the innermost enclosing namespace scope, the block
6010     //   scope declaration declares that same entity and receives the
6011     //   linkage of the previous declaration.
6012     DeclContext *OuterContext = DC->getRedeclContext();
6013     if (!OuterContext->isFunctionOrMethod())
6014       // This rule only applies to block-scope declarations.
6015       return false;
6016 
6017     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6018     if (PrevOuterContext->isRecord())
6019       // We found a member function: ignore it.
6020       return false;
6021 
6022     // Find the innermost enclosing namespace for the new and
6023     // previous declarations.
6024     OuterContext = OuterContext->getEnclosingNamespaceContext();
6025     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6026 
6027     // The previous declaration is in a different namespace, so it
6028     // isn't the same function.
6029     if (!OuterContext->Equals(PrevOuterContext))
6030       return false;
6031   }
6032 
6033   return true;
6034 }
6035 
6036 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6037   CXXScopeSpec &SS = D.getCXXScopeSpec();
6038   if (!SS.isSet()) return;
6039   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6040 }
6041 
6042 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6043   QualType type = decl->getType();
6044   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6045   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6046     // Various kinds of declaration aren't allowed to be __autoreleasing.
6047     unsigned kind = -1U;
6048     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6049       if (var->hasAttr<BlocksAttr>())
6050         kind = 0; // __block
6051       else if (!var->hasLocalStorage())
6052         kind = 1; // global
6053     } else if (isa<ObjCIvarDecl>(decl)) {
6054       kind = 3; // ivar
6055     } else if (isa<FieldDecl>(decl)) {
6056       kind = 2; // field
6057     }
6058 
6059     if (kind != -1U) {
6060       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6061         << kind;
6062     }
6063   } else if (lifetime == Qualifiers::OCL_None) {
6064     // Try to infer lifetime.
6065     if (!type->isObjCLifetimeType())
6066       return false;
6067 
6068     lifetime = type->getObjCARCImplicitLifetime();
6069     type = Context.getLifetimeQualifiedType(type, lifetime);
6070     decl->setType(type);
6071   }
6072 
6073   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6074     // Thread-local variables cannot have lifetime.
6075     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6076         var->getTLSKind()) {
6077       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6078         << var->getType();
6079       return true;
6080     }
6081   }
6082 
6083   return false;
6084 }
6085 
6086 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6087   // Ensure that an auto decl is deduced otherwise the checks below might cache
6088   // the wrong linkage.
6089   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6090 
6091   // 'weak' only applies to declarations with external linkage.
6092   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6093     if (!ND.isExternallyVisible()) {
6094       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6095       ND.dropAttr<WeakAttr>();
6096     }
6097   }
6098   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6099     if (ND.isExternallyVisible()) {
6100       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6101       ND.dropAttr<WeakRefAttr>();
6102       ND.dropAttr<AliasAttr>();
6103     }
6104   }
6105 
6106   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6107     if (VD->hasInit()) {
6108       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6109         assert(VD->isThisDeclarationADefinition() &&
6110                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6111         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6112         VD->dropAttr<AliasAttr>();
6113       }
6114     }
6115   }
6116 
6117   // 'selectany' only applies to externally visible variable declarations.
6118   // It does not apply to functions.
6119   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6120     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6121       S.Diag(Attr->getLocation(),
6122              diag::err_attribute_selectany_non_extern_data);
6123       ND.dropAttr<SelectAnyAttr>();
6124     }
6125   }
6126 
6127   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6128     auto *VD = dyn_cast<VarDecl>(&ND);
6129     bool IsAnonymousNS = false;
6130     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6131     if (VD) {
6132       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6133       while (NS && !IsAnonymousNS) {
6134         IsAnonymousNS = NS->isAnonymousNamespace();
6135         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6136       }
6137     }
6138     // dll attributes require external linkage. Static locals may have external
6139     // linkage but still cannot be explicitly imported or exported.
6140     // In Microsoft mode, a variable defined in anonymous namespace must have
6141     // external linkage in order to be exported.
6142     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6143     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6144         (!AnonNSInMicrosoftMode &&
6145          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6146       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6147         << &ND << Attr;
6148       ND.setInvalidDecl();
6149     }
6150   }
6151 
6152   // Virtual functions cannot be marked as 'notail'.
6153   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6154     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6155       if (MD->isVirtual()) {
6156         S.Diag(ND.getLocation(),
6157                diag::err_invalid_attribute_on_virtual_function)
6158             << Attr;
6159         ND.dropAttr<NotTailCalledAttr>();
6160       }
6161 
6162   // Check the attributes on the function type, if any.
6163   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6164     // Don't declare this variable in the second operand of the for-statement;
6165     // GCC miscompiles that by ending its lifetime before evaluating the
6166     // third operand. See gcc.gnu.org/PR86769.
6167     AttributedTypeLoc ATL;
6168     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6169          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6170          TL = ATL.getModifiedLoc()) {
6171       // The [[lifetimebound]] attribute can be applied to the implicit object
6172       // parameter of a non-static member function (other than a ctor or dtor)
6173       // by applying it to the function type.
6174       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6175         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6176         if (!MD || MD->isStatic()) {
6177           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6178               << !MD << A->getRange();
6179         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6180           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6181               << isa<CXXDestructorDecl>(MD) << A->getRange();
6182         }
6183       }
6184     }
6185   }
6186 }
6187 
6188 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6189                                            NamedDecl *NewDecl,
6190                                            bool IsSpecialization,
6191                                            bool IsDefinition) {
6192   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6193     return;
6194 
6195   bool IsTemplate = false;
6196   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6197     OldDecl = OldTD->getTemplatedDecl();
6198     IsTemplate = true;
6199     if (!IsSpecialization)
6200       IsDefinition = false;
6201   }
6202   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6203     NewDecl = NewTD->getTemplatedDecl();
6204     IsTemplate = true;
6205   }
6206 
6207   if (!OldDecl || !NewDecl)
6208     return;
6209 
6210   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6211   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6212   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6213   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6214 
6215   // dllimport and dllexport are inheritable attributes so we have to exclude
6216   // inherited attribute instances.
6217   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6218                     (NewExportAttr && !NewExportAttr->isInherited());
6219 
6220   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6221   // the only exception being explicit specializations.
6222   // Implicitly generated declarations are also excluded for now because there
6223   // is no other way to switch these to use dllimport or dllexport.
6224   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6225 
6226   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6227     // Allow with a warning for free functions and global variables.
6228     bool JustWarn = false;
6229     if (!OldDecl->isCXXClassMember()) {
6230       auto *VD = dyn_cast<VarDecl>(OldDecl);
6231       if (VD && !VD->getDescribedVarTemplate())
6232         JustWarn = true;
6233       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6234       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6235         JustWarn = true;
6236     }
6237 
6238     // We cannot change a declaration that's been used because IR has already
6239     // been emitted. Dllimported functions will still work though (modulo
6240     // address equality) as they can use the thunk.
6241     if (OldDecl->isUsed())
6242       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6243         JustWarn = false;
6244 
6245     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6246                                : diag::err_attribute_dll_redeclaration;
6247     S.Diag(NewDecl->getLocation(), DiagID)
6248         << NewDecl
6249         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6250     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6251     if (!JustWarn) {
6252       NewDecl->setInvalidDecl();
6253       return;
6254     }
6255   }
6256 
6257   // A redeclaration is not allowed to drop a dllimport attribute, the only
6258   // exceptions being inline function definitions (except for function
6259   // templates), local extern declarations, qualified friend declarations or
6260   // special MSVC extension: in the last case, the declaration is treated as if
6261   // it were marked dllexport.
6262   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6263   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6264   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6265     // Ignore static data because out-of-line definitions are diagnosed
6266     // separately.
6267     IsStaticDataMember = VD->isStaticDataMember();
6268     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6269                    VarDecl::DeclarationOnly;
6270   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6271     IsInline = FD->isInlined();
6272     IsQualifiedFriend = FD->getQualifier() &&
6273                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6274   }
6275 
6276   if (OldImportAttr && !HasNewAttr &&
6277       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6278       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6279     if (IsMicrosoft && IsDefinition) {
6280       S.Diag(NewDecl->getLocation(),
6281              diag::warn_redeclaration_without_import_attribute)
6282           << NewDecl;
6283       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6284       NewDecl->dropAttr<DLLImportAttr>();
6285       NewDecl->addAttr(
6286           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6287     } else {
6288       S.Diag(NewDecl->getLocation(),
6289              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6290           << NewDecl << OldImportAttr;
6291       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6292       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6293       OldDecl->dropAttr<DLLImportAttr>();
6294       NewDecl->dropAttr<DLLImportAttr>();
6295     }
6296   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6297     // In MinGW, seeing a function declared inline drops the dllimport
6298     // attribute.
6299     OldDecl->dropAttr<DLLImportAttr>();
6300     NewDecl->dropAttr<DLLImportAttr>();
6301     S.Diag(NewDecl->getLocation(),
6302            diag::warn_dllimport_dropped_from_inline_function)
6303         << NewDecl << OldImportAttr;
6304   }
6305 
6306   // A specialization of a class template member function is processed here
6307   // since it's a redeclaration. If the parent class is dllexport, the
6308   // specialization inherits that attribute. This doesn't happen automatically
6309   // since the parent class isn't instantiated until later.
6310   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6311     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6312         !NewImportAttr && !NewExportAttr) {
6313       if (const DLLExportAttr *ParentExportAttr =
6314               MD->getParent()->getAttr<DLLExportAttr>()) {
6315         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6316         NewAttr->setInherited(true);
6317         NewDecl->addAttr(NewAttr);
6318       }
6319     }
6320   }
6321 }
6322 
6323 /// Given that we are within the definition of the given function,
6324 /// will that definition behave like C99's 'inline', where the
6325 /// definition is discarded except for optimization purposes?
6326 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6327   // Try to avoid calling GetGVALinkageForFunction.
6328 
6329   // All cases of this require the 'inline' keyword.
6330   if (!FD->isInlined()) return false;
6331 
6332   // This is only possible in C++ with the gnu_inline attribute.
6333   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6334     return false;
6335 
6336   // Okay, go ahead and call the relatively-more-expensive function.
6337   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6338 }
6339 
6340 /// Determine whether a variable is extern "C" prior to attaching
6341 /// an initializer. We can't just call isExternC() here, because that
6342 /// will also compute and cache whether the declaration is externally
6343 /// visible, which might change when we attach the initializer.
6344 ///
6345 /// This can only be used if the declaration is known to not be a
6346 /// redeclaration of an internal linkage declaration.
6347 ///
6348 /// For instance:
6349 ///
6350 ///   auto x = []{};
6351 ///
6352 /// Attaching the initializer here makes this declaration not externally
6353 /// visible, because its type has internal linkage.
6354 ///
6355 /// FIXME: This is a hack.
6356 template<typename T>
6357 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6358   if (S.getLangOpts().CPlusPlus) {
6359     // In C++, the overloadable attribute negates the effects of extern "C".
6360     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6361       return false;
6362 
6363     // So do CUDA's host/device attributes.
6364     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6365                                  D->template hasAttr<CUDAHostAttr>()))
6366       return false;
6367   }
6368   return D->isExternC();
6369 }
6370 
6371 static bool shouldConsiderLinkage(const VarDecl *VD) {
6372   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6373   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6374       isa<OMPDeclareMapperDecl>(DC))
6375     return VD->hasExternalStorage();
6376   if (DC->isFileContext())
6377     return true;
6378   if (DC->isRecord())
6379     return false;
6380   llvm_unreachable("Unexpected context");
6381 }
6382 
6383 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6384   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6385   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6386       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6387     return true;
6388   if (DC->isRecord())
6389     return false;
6390   llvm_unreachable("Unexpected context");
6391 }
6392 
6393 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6394                           ParsedAttr::Kind Kind) {
6395   // Check decl attributes on the DeclSpec.
6396   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6397     return true;
6398 
6399   // Walk the declarator structure, checking decl attributes that were in a type
6400   // position to the decl itself.
6401   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6402     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6403       return true;
6404   }
6405 
6406   // Finally, check attributes on the decl itself.
6407   return PD.getAttributes().hasAttribute(Kind);
6408 }
6409 
6410 /// Adjust the \c DeclContext for a function or variable that might be a
6411 /// function-local external declaration.
6412 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6413   if (!DC->isFunctionOrMethod())
6414     return false;
6415 
6416   // If this is a local extern function or variable declared within a function
6417   // template, don't add it into the enclosing namespace scope until it is
6418   // instantiated; it might have a dependent type right now.
6419   if (DC->isDependentContext())
6420     return true;
6421 
6422   // C++11 [basic.link]p7:
6423   //   When a block scope declaration of an entity with linkage is not found to
6424   //   refer to some other declaration, then that entity is a member of the
6425   //   innermost enclosing namespace.
6426   //
6427   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6428   // semantically-enclosing namespace, not a lexically-enclosing one.
6429   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6430     DC = DC->getParent();
6431   return true;
6432 }
6433 
6434 /// Returns true if given declaration has external C language linkage.
6435 static bool isDeclExternC(const Decl *D) {
6436   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6437     return FD->isExternC();
6438   if (const auto *VD = dyn_cast<VarDecl>(D))
6439     return VD->isExternC();
6440 
6441   llvm_unreachable("Unknown type of decl!");
6442 }
6443 
6444 NamedDecl *Sema::ActOnVariableDeclarator(
6445     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6446     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6447     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6448   QualType R = TInfo->getType();
6449   DeclarationName Name = GetNameForDeclarator(D).getName();
6450 
6451   IdentifierInfo *II = Name.getAsIdentifierInfo();
6452 
6453   if (D.isDecompositionDeclarator()) {
6454     // Take the name of the first declarator as our name for diagnostic
6455     // purposes.
6456     auto &Decomp = D.getDecompositionDeclarator();
6457     if (!Decomp.bindings().empty()) {
6458       II = Decomp.bindings()[0].Name;
6459       Name = II;
6460     }
6461   } else if (!II) {
6462     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6463     return nullptr;
6464   }
6465 
6466   if (getLangOpts().OpenCL) {
6467     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6468     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6469     // argument.
6470     if (R->isImageType() || R->isPipeType()) {
6471       Diag(D.getIdentifierLoc(),
6472            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6473           << R;
6474       D.setInvalidType();
6475       return nullptr;
6476     }
6477 
6478     // OpenCL v1.2 s6.9.r:
6479     // The event type cannot be used to declare a program scope variable.
6480     // OpenCL v2.0 s6.9.q:
6481     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6482     if (NULL == S->getParent()) {
6483       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6484         Diag(D.getIdentifierLoc(),
6485              diag::err_invalid_type_for_program_scope_var) << R;
6486         D.setInvalidType();
6487         return nullptr;
6488       }
6489     }
6490 
6491     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6492     QualType NR = R;
6493     while (NR->isPointerType()) {
6494       if (NR->isFunctionPointerType()) {
6495         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6496         D.setInvalidType();
6497         break;
6498       }
6499       NR = NR->getPointeeType();
6500     }
6501 
6502     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6503       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6504       // half array type (unless the cl_khr_fp16 extension is enabled).
6505       if (Context.getBaseElementType(R)->isHalfType()) {
6506         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6507         D.setInvalidType();
6508       }
6509     }
6510 
6511     if (R->isSamplerT()) {
6512       // OpenCL v1.2 s6.9.b p4:
6513       // The sampler type cannot be used with the __local and __global address
6514       // space qualifiers.
6515       if (R.getAddressSpace() == LangAS::opencl_local ||
6516           R.getAddressSpace() == LangAS::opencl_global) {
6517         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6518       }
6519 
6520       // OpenCL v1.2 s6.12.14.1:
6521       // A global sampler must be declared with either the constant address
6522       // space qualifier or with the const qualifier.
6523       if (DC->isTranslationUnit() &&
6524           !(R.getAddressSpace() == LangAS::opencl_constant ||
6525           R.isConstQualified())) {
6526         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6527         D.setInvalidType();
6528       }
6529     }
6530 
6531     // OpenCL v1.2 s6.9.r:
6532     // The event type cannot be used with the __local, __constant and __global
6533     // address space qualifiers.
6534     if (R->isEventT()) {
6535       if (R.getAddressSpace() != LangAS::opencl_private) {
6536         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6537         D.setInvalidType();
6538       }
6539     }
6540 
6541     // C++ for OpenCL does not allow the thread_local storage qualifier.
6542     // OpenCL C does not support thread_local either, and
6543     // also reject all other thread storage class specifiers.
6544     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6545     if (TSC != TSCS_unspecified) {
6546       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6547       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6548            diag::err_opencl_unknown_type_specifier)
6549           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6550           << DeclSpec::getSpecifierName(TSC) << 1;
6551       D.setInvalidType();
6552       return nullptr;
6553     }
6554   }
6555 
6556   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6557   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6558 
6559   // dllimport globals without explicit storage class are treated as extern. We
6560   // have to change the storage class this early to get the right DeclContext.
6561   if (SC == SC_None && !DC->isRecord() &&
6562       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6563       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6564     SC = SC_Extern;
6565 
6566   DeclContext *OriginalDC = DC;
6567   bool IsLocalExternDecl = SC == SC_Extern &&
6568                            adjustContextForLocalExternDecl(DC);
6569 
6570   if (SCSpec == DeclSpec::SCS_mutable) {
6571     // mutable can only appear on non-static class members, so it's always
6572     // an error here
6573     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6574     D.setInvalidType();
6575     SC = SC_None;
6576   }
6577 
6578   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6579       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6580                               D.getDeclSpec().getStorageClassSpecLoc())) {
6581     // In C++11, the 'register' storage class specifier is deprecated.
6582     // Suppress the warning in system macros, it's used in macros in some
6583     // popular C system headers, such as in glibc's htonl() macro.
6584     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6585          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6586                                    : diag::warn_deprecated_register)
6587       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6588   }
6589 
6590   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6591 
6592   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6593     // C99 6.9p2: The storage-class specifiers auto and register shall not
6594     // appear in the declaration specifiers in an external declaration.
6595     // Global Register+Asm is a GNU extension we support.
6596     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6597       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6598       D.setInvalidType();
6599     }
6600   }
6601 
6602   bool IsMemberSpecialization = false;
6603   bool IsVariableTemplateSpecialization = false;
6604   bool IsPartialSpecialization = false;
6605   bool IsVariableTemplate = false;
6606   VarDecl *NewVD = nullptr;
6607   VarTemplateDecl *NewTemplate = nullptr;
6608   TemplateParameterList *TemplateParams = nullptr;
6609   if (!getLangOpts().CPlusPlus) {
6610     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6611                             II, R, TInfo, SC);
6612 
6613     if (R->getContainedDeducedType())
6614       ParsingInitForAutoVars.insert(NewVD);
6615 
6616     if (D.isInvalidType())
6617       NewVD->setInvalidDecl();
6618 
6619     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6620         NewVD->hasLocalStorage())
6621       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6622                             NTCUC_AutoVar, NTCUK_Destruct);
6623   } else {
6624     bool Invalid = false;
6625 
6626     if (DC->isRecord() && !CurContext->isRecord()) {
6627       // This is an out-of-line definition of a static data member.
6628       switch (SC) {
6629       case SC_None:
6630         break;
6631       case SC_Static:
6632         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6633              diag::err_static_out_of_line)
6634           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6635         break;
6636       case SC_Auto:
6637       case SC_Register:
6638       case SC_Extern:
6639         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6640         // to names of variables declared in a block or to function parameters.
6641         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6642         // of class members
6643 
6644         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6645              diag::err_storage_class_for_static_member)
6646           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6647         break;
6648       case SC_PrivateExtern:
6649         llvm_unreachable("C storage class in c++!");
6650       }
6651     }
6652 
6653     if (SC == SC_Static && CurContext->isRecord()) {
6654       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6655         if (RD->isLocalClass())
6656           Diag(D.getIdentifierLoc(),
6657                diag::err_static_data_member_not_allowed_in_local_class)
6658             << Name << RD->getDeclName();
6659 
6660         // C++98 [class.union]p1: If a union contains a static data member,
6661         // the program is ill-formed. C++11 drops this restriction.
6662         if (RD->isUnion())
6663           Diag(D.getIdentifierLoc(),
6664                getLangOpts().CPlusPlus11
6665                  ? diag::warn_cxx98_compat_static_data_member_in_union
6666                  : diag::ext_static_data_member_in_union) << Name;
6667         // We conservatively disallow static data members in anonymous structs.
6668         else if (!RD->getDeclName())
6669           Diag(D.getIdentifierLoc(),
6670                diag::err_static_data_member_not_allowed_in_anon_struct)
6671             << Name << RD->isUnion();
6672       }
6673     }
6674 
6675     // Match up the template parameter lists with the scope specifier, then
6676     // determine whether we have a template or a template specialization.
6677     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6678         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6679         D.getCXXScopeSpec(),
6680         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6681             ? D.getName().TemplateId
6682             : nullptr,
6683         TemplateParamLists,
6684         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6685 
6686     if (TemplateParams) {
6687       if (!TemplateParams->size() &&
6688           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6689         // There is an extraneous 'template<>' for this variable. Complain
6690         // about it, but allow the declaration of the variable.
6691         Diag(TemplateParams->getTemplateLoc(),
6692              diag::err_template_variable_noparams)
6693           << II
6694           << SourceRange(TemplateParams->getTemplateLoc(),
6695                          TemplateParams->getRAngleLoc());
6696         TemplateParams = nullptr;
6697       } else {
6698         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6699           // This is an explicit specialization or a partial specialization.
6700           // FIXME: Check that we can declare a specialization here.
6701           IsVariableTemplateSpecialization = true;
6702           IsPartialSpecialization = TemplateParams->size() > 0;
6703         } else { // if (TemplateParams->size() > 0)
6704           // This is a template declaration.
6705           IsVariableTemplate = true;
6706 
6707           // Check that we can declare a template here.
6708           if (CheckTemplateDeclScope(S, TemplateParams))
6709             return nullptr;
6710 
6711           // Only C++1y supports variable templates (N3651).
6712           Diag(D.getIdentifierLoc(),
6713                getLangOpts().CPlusPlus14
6714                    ? diag::warn_cxx11_compat_variable_template
6715                    : diag::ext_variable_template);
6716         }
6717       }
6718     } else {
6719       assert((Invalid ||
6720               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6721              "should have a 'template<>' for this decl");
6722     }
6723 
6724     if (IsVariableTemplateSpecialization) {
6725       SourceLocation TemplateKWLoc =
6726           TemplateParamLists.size() > 0
6727               ? TemplateParamLists[0]->getTemplateLoc()
6728               : SourceLocation();
6729       DeclResult Res = ActOnVarTemplateSpecialization(
6730           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6731           IsPartialSpecialization);
6732       if (Res.isInvalid())
6733         return nullptr;
6734       NewVD = cast<VarDecl>(Res.get());
6735       AddToScope = false;
6736     } else if (D.isDecompositionDeclarator()) {
6737       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6738                                         D.getIdentifierLoc(), R, TInfo, SC,
6739                                         Bindings);
6740     } else
6741       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6742                               D.getIdentifierLoc(), II, R, TInfo, SC);
6743 
6744     // If this is supposed to be a variable template, create it as such.
6745     if (IsVariableTemplate) {
6746       NewTemplate =
6747           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6748                                   TemplateParams, NewVD);
6749       NewVD->setDescribedVarTemplate(NewTemplate);
6750     }
6751 
6752     // If this decl has an auto type in need of deduction, make a note of the
6753     // Decl so we can diagnose uses of it in its own initializer.
6754     if (R->getContainedDeducedType())
6755       ParsingInitForAutoVars.insert(NewVD);
6756 
6757     if (D.isInvalidType() || Invalid) {
6758       NewVD->setInvalidDecl();
6759       if (NewTemplate)
6760         NewTemplate->setInvalidDecl();
6761     }
6762 
6763     SetNestedNameSpecifier(*this, NewVD, D);
6764 
6765     // If we have any template parameter lists that don't directly belong to
6766     // the variable (matching the scope specifier), store them.
6767     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6768     if (TemplateParamLists.size() > VDTemplateParamLists)
6769       NewVD->setTemplateParameterListsInfo(
6770           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6771   }
6772 
6773   if (D.getDeclSpec().isInlineSpecified()) {
6774     if (!getLangOpts().CPlusPlus) {
6775       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6776           << 0;
6777     } else if (CurContext->isFunctionOrMethod()) {
6778       // 'inline' is not allowed on block scope variable declaration.
6779       Diag(D.getDeclSpec().getInlineSpecLoc(),
6780            diag::err_inline_declaration_block_scope) << Name
6781         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6782     } else {
6783       Diag(D.getDeclSpec().getInlineSpecLoc(),
6784            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6785                                      : diag::ext_inline_variable);
6786       NewVD->setInlineSpecified();
6787     }
6788   }
6789 
6790   // Set the lexical context. If the declarator has a C++ scope specifier, the
6791   // lexical context will be different from the semantic context.
6792   NewVD->setLexicalDeclContext(CurContext);
6793   if (NewTemplate)
6794     NewTemplate->setLexicalDeclContext(CurContext);
6795 
6796   if (IsLocalExternDecl) {
6797     if (D.isDecompositionDeclarator())
6798       for (auto *B : Bindings)
6799         B->setLocalExternDecl();
6800     else
6801       NewVD->setLocalExternDecl();
6802   }
6803 
6804   bool EmitTLSUnsupportedError = false;
6805   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6806     // C++11 [dcl.stc]p4:
6807     //   When thread_local is applied to a variable of block scope the
6808     //   storage-class-specifier static is implied if it does not appear
6809     //   explicitly.
6810     // Core issue: 'static' is not implied if the variable is declared
6811     //   'extern'.
6812     if (NewVD->hasLocalStorage() &&
6813         (SCSpec != DeclSpec::SCS_unspecified ||
6814          TSCS != DeclSpec::TSCS_thread_local ||
6815          !DC->isFunctionOrMethod()))
6816       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6817            diag::err_thread_non_global)
6818         << DeclSpec::getSpecifierName(TSCS);
6819     else if (!Context.getTargetInfo().isTLSSupported()) {
6820       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6821         // Postpone error emission until we've collected attributes required to
6822         // figure out whether it's a host or device variable and whether the
6823         // error should be ignored.
6824         EmitTLSUnsupportedError = true;
6825         // We still need to mark the variable as TLS so it shows up in AST with
6826         // proper storage class for other tools to use even if we're not going
6827         // to emit any code for it.
6828         NewVD->setTSCSpec(TSCS);
6829       } else
6830         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6831              diag::err_thread_unsupported);
6832     } else
6833       NewVD->setTSCSpec(TSCS);
6834   }
6835 
6836   switch (D.getDeclSpec().getConstexprSpecifier()) {
6837   case CSK_unspecified:
6838     break;
6839 
6840   case CSK_consteval:
6841     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6842         diag::err_constexpr_wrong_decl_kind)
6843       << D.getDeclSpec().getConstexprSpecifier();
6844     LLVM_FALLTHROUGH;
6845 
6846   case CSK_constexpr:
6847     NewVD->setConstexpr(true);
6848     // C++1z [dcl.spec.constexpr]p1:
6849     //   A static data member declared with the constexpr specifier is
6850     //   implicitly an inline variable.
6851     if (NewVD->isStaticDataMember() &&
6852         (getLangOpts().CPlusPlus17 ||
6853          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6854       NewVD->setImplicitlyInline();
6855     break;
6856 
6857   case CSK_constinit:
6858     if (!NewVD->hasGlobalStorage())
6859       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6860            diag::err_constinit_local_variable);
6861     else
6862       NewVD->addAttr(ConstInitAttr::Create(
6863           Context, D.getDeclSpec().getConstexprSpecLoc(),
6864           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6865     break;
6866   }
6867 
6868   // C99 6.7.4p3
6869   //   An inline definition of a function with external linkage shall
6870   //   not contain a definition of a modifiable object with static or
6871   //   thread storage duration...
6872   // We only apply this when the function is required to be defined
6873   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6874   // that a local variable with thread storage duration still has to
6875   // be marked 'static'.  Also note that it's possible to get these
6876   // semantics in C++ using __attribute__((gnu_inline)).
6877   if (SC == SC_Static && S->getFnParent() != nullptr &&
6878       !NewVD->getType().isConstQualified()) {
6879     FunctionDecl *CurFD = getCurFunctionDecl();
6880     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6881       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6882            diag::warn_static_local_in_extern_inline);
6883       MaybeSuggestAddingStaticToDecl(CurFD);
6884     }
6885   }
6886 
6887   if (D.getDeclSpec().isModulePrivateSpecified()) {
6888     if (IsVariableTemplateSpecialization)
6889       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6890           << (IsPartialSpecialization ? 1 : 0)
6891           << FixItHint::CreateRemoval(
6892                  D.getDeclSpec().getModulePrivateSpecLoc());
6893     else if (IsMemberSpecialization)
6894       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6895         << 2
6896         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6897     else if (NewVD->hasLocalStorage())
6898       Diag(NewVD->getLocation(), diag::err_module_private_local)
6899         << 0 << NewVD->getDeclName()
6900         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6901         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6902     else {
6903       NewVD->setModulePrivate();
6904       if (NewTemplate)
6905         NewTemplate->setModulePrivate();
6906       for (auto *B : Bindings)
6907         B->setModulePrivate();
6908     }
6909   }
6910 
6911   // Handle attributes prior to checking for duplicates in MergeVarDecl
6912   ProcessDeclAttributes(S, NewVD, D);
6913 
6914   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6915     if (EmitTLSUnsupportedError &&
6916         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6917          (getLangOpts().OpenMPIsDevice &&
6918           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
6919       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6920            diag::err_thread_unsupported);
6921     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6922     // storage [duration]."
6923     if (SC == SC_None && S->getFnParent() != nullptr &&
6924         (NewVD->hasAttr<CUDASharedAttr>() ||
6925          NewVD->hasAttr<CUDAConstantAttr>())) {
6926       NewVD->setStorageClass(SC_Static);
6927     }
6928   }
6929 
6930   // Ensure that dllimport globals without explicit storage class are treated as
6931   // extern. The storage class is set above using parsed attributes. Now we can
6932   // check the VarDecl itself.
6933   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6934          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6935          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6936 
6937   // In auto-retain/release, infer strong retension for variables of
6938   // retainable type.
6939   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6940     NewVD->setInvalidDecl();
6941 
6942   // Handle GNU asm-label extension (encoded as an attribute).
6943   if (Expr *E = (Expr*)D.getAsmLabel()) {
6944     // The parser guarantees this is a string.
6945     StringLiteral *SE = cast<StringLiteral>(E);
6946     StringRef Label = SE->getString();
6947     if (S->getFnParent() != nullptr) {
6948       switch (SC) {
6949       case SC_None:
6950       case SC_Auto:
6951         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6952         break;
6953       case SC_Register:
6954         // Local Named register
6955         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6956             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6957           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6958         break;
6959       case SC_Static:
6960       case SC_Extern:
6961       case SC_PrivateExtern:
6962         break;
6963       }
6964     } else if (SC == SC_Register) {
6965       // Global Named register
6966       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6967         const auto &TI = Context.getTargetInfo();
6968         bool HasSizeMismatch;
6969 
6970         if (!TI.isValidGCCRegisterName(Label))
6971           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6972         else if (!TI.validateGlobalRegisterVariable(Label,
6973                                                     Context.getTypeSize(R),
6974                                                     HasSizeMismatch))
6975           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6976         else if (HasSizeMismatch)
6977           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6978       }
6979 
6980       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6981         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6982         NewVD->setInvalidDecl(true);
6983       }
6984     }
6985 
6986     NewVD->addAttr(::new (Context)
6987                        AsmLabelAttr(Context, SE->getStrTokenLoc(0), Label));
6988   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6989     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6990       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6991     if (I != ExtnameUndeclaredIdentifiers.end()) {
6992       if (isDeclExternC(NewVD)) {
6993         NewVD->addAttr(I->second);
6994         ExtnameUndeclaredIdentifiers.erase(I);
6995       } else
6996         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6997             << /*Variable*/1 << NewVD;
6998     }
6999   }
7000 
7001   // Find the shadowed declaration before filtering for scope.
7002   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7003                                 ? getShadowedDeclaration(NewVD, Previous)
7004                                 : nullptr;
7005 
7006   // Don't consider existing declarations that are in a different
7007   // scope and are out-of-semantic-context declarations (if the new
7008   // declaration has linkage).
7009   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7010                        D.getCXXScopeSpec().isNotEmpty() ||
7011                        IsMemberSpecialization ||
7012                        IsVariableTemplateSpecialization);
7013 
7014   // Check whether the previous declaration is in the same block scope. This
7015   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7016   if (getLangOpts().CPlusPlus &&
7017       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7018     NewVD->setPreviousDeclInSameBlockScope(
7019         Previous.isSingleResult() && !Previous.isShadowed() &&
7020         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7021 
7022   if (!getLangOpts().CPlusPlus) {
7023     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7024   } else {
7025     // If this is an explicit specialization of a static data member, check it.
7026     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7027         CheckMemberSpecialization(NewVD, Previous))
7028       NewVD->setInvalidDecl();
7029 
7030     // Merge the decl with the existing one if appropriate.
7031     if (!Previous.empty()) {
7032       if (Previous.isSingleResult() &&
7033           isa<FieldDecl>(Previous.getFoundDecl()) &&
7034           D.getCXXScopeSpec().isSet()) {
7035         // The user tried to define a non-static data member
7036         // out-of-line (C++ [dcl.meaning]p1).
7037         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7038           << D.getCXXScopeSpec().getRange();
7039         Previous.clear();
7040         NewVD->setInvalidDecl();
7041       }
7042     } else if (D.getCXXScopeSpec().isSet()) {
7043       // No previous declaration in the qualifying scope.
7044       Diag(D.getIdentifierLoc(), diag::err_no_member)
7045         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7046         << D.getCXXScopeSpec().getRange();
7047       NewVD->setInvalidDecl();
7048     }
7049 
7050     if (!IsVariableTemplateSpecialization)
7051       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7052 
7053     if (NewTemplate) {
7054       VarTemplateDecl *PrevVarTemplate =
7055           NewVD->getPreviousDecl()
7056               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7057               : nullptr;
7058 
7059       // Check the template parameter list of this declaration, possibly
7060       // merging in the template parameter list from the previous variable
7061       // template declaration.
7062       if (CheckTemplateParameterList(
7063               TemplateParams,
7064               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7065                               : nullptr,
7066               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7067                DC->isDependentContext())
7068                   ? TPC_ClassTemplateMember
7069                   : TPC_VarTemplate))
7070         NewVD->setInvalidDecl();
7071 
7072       // If we are providing an explicit specialization of a static variable
7073       // template, make a note of that.
7074       if (PrevVarTemplate &&
7075           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7076         PrevVarTemplate->setMemberSpecialization();
7077     }
7078   }
7079 
7080   // Diagnose shadowed variables iff this isn't a redeclaration.
7081   if (ShadowedDecl && !D.isRedeclaration())
7082     CheckShadow(NewVD, ShadowedDecl, Previous);
7083 
7084   ProcessPragmaWeak(S, NewVD);
7085 
7086   // If this is the first declaration of an extern C variable, update
7087   // the map of such variables.
7088   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7089       isIncompleteDeclExternC(*this, NewVD))
7090     RegisterLocallyScopedExternCDecl(NewVD, S);
7091 
7092   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7093     Decl *ManglingContextDecl;
7094     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
7095             NewVD->getDeclContext(), ManglingContextDecl)) {
7096       Context.setManglingNumber(
7097           NewVD, MCtx->getManglingNumber(
7098                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7099       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7100     }
7101   }
7102 
7103   // Special handling of variable named 'main'.
7104   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7105       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7106       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7107 
7108     // C++ [basic.start.main]p3
7109     // A program that declares a variable main at global scope is ill-formed.
7110     if (getLangOpts().CPlusPlus)
7111       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7112 
7113     // In C, and external-linkage variable named main results in undefined
7114     // behavior.
7115     else if (NewVD->hasExternalFormalLinkage())
7116       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7117   }
7118 
7119   if (D.isRedeclaration() && !Previous.empty()) {
7120     NamedDecl *Prev = Previous.getRepresentativeDecl();
7121     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7122                                    D.isFunctionDefinition());
7123   }
7124 
7125   if (NewTemplate) {
7126     if (NewVD->isInvalidDecl())
7127       NewTemplate->setInvalidDecl();
7128     ActOnDocumentableDecl(NewTemplate);
7129     return NewTemplate;
7130   }
7131 
7132   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7133     CompleteMemberSpecialization(NewVD, Previous);
7134 
7135   return NewVD;
7136 }
7137 
7138 /// Enum describing the %select options in diag::warn_decl_shadow.
7139 enum ShadowedDeclKind {
7140   SDK_Local,
7141   SDK_Global,
7142   SDK_StaticMember,
7143   SDK_Field,
7144   SDK_Typedef,
7145   SDK_Using
7146 };
7147 
7148 /// Determine what kind of declaration we're shadowing.
7149 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7150                                                 const DeclContext *OldDC) {
7151   if (isa<TypeAliasDecl>(ShadowedDecl))
7152     return SDK_Using;
7153   else if (isa<TypedefDecl>(ShadowedDecl))
7154     return SDK_Typedef;
7155   else if (isa<RecordDecl>(OldDC))
7156     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7157 
7158   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7159 }
7160 
7161 /// Return the location of the capture if the given lambda captures the given
7162 /// variable \p VD, or an invalid source location otherwise.
7163 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7164                                          const VarDecl *VD) {
7165   for (const Capture &Capture : LSI->Captures) {
7166     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7167       return Capture.getLocation();
7168   }
7169   return SourceLocation();
7170 }
7171 
7172 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7173                                      const LookupResult &R) {
7174   // Only diagnose if we're shadowing an unambiguous field or variable.
7175   if (R.getResultKind() != LookupResult::Found)
7176     return false;
7177 
7178   // Return false if warning is ignored.
7179   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7180 }
7181 
7182 /// Return the declaration shadowed by the given variable \p D, or null
7183 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7184 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7185                                         const LookupResult &R) {
7186   if (!shouldWarnIfShadowedDecl(Diags, R))
7187     return nullptr;
7188 
7189   // Don't diagnose declarations at file scope.
7190   if (D->hasGlobalStorage())
7191     return nullptr;
7192 
7193   NamedDecl *ShadowedDecl = R.getFoundDecl();
7194   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7195              ? ShadowedDecl
7196              : nullptr;
7197 }
7198 
7199 /// Return the declaration shadowed by the given typedef \p D, or null
7200 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7201 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7202                                         const LookupResult &R) {
7203   // Don't warn if typedef declaration is part of a class
7204   if (D->getDeclContext()->isRecord())
7205     return nullptr;
7206 
7207   if (!shouldWarnIfShadowedDecl(Diags, R))
7208     return nullptr;
7209 
7210   NamedDecl *ShadowedDecl = R.getFoundDecl();
7211   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7212 }
7213 
7214 /// Diagnose variable or built-in function shadowing.  Implements
7215 /// -Wshadow.
7216 ///
7217 /// This method is called whenever a VarDecl is added to a "useful"
7218 /// scope.
7219 ///
7220 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7221 /// \param R the lookup of the name
7222 ///
7223 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7224                        const LookupResult &R) {
7225   DeclContext *NewDC = D->getDeclContext();
7226 
7227   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7228     // Fields are not shadowed by variables in C++ static methods.
7229     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7230       if (MD->isStatic())
7231         return;
7232 
7233     // Fields shadowed by constructor parameters are a special case. Usually
7234     // the constructor initializes the field with the parameter.
7235     if (isa<CXXConstructorDecl>(NewDC))
7236       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7237         // Remember that this was shadowed so we can either warn about its
7238         // modification or its existence depending on warning settings.
7239         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7240         return;
7241       }
7242   }
7243 
7244   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7245     if (shadowedVar->isExternC()) {
7246       // For shadowing external vars, make sure that we point to the global
7247       // declaration, not a locally scoped extern declaration.
7248       for (auto I : shadowedVar->redecls())
7249         if (I->isFileVarDecl()) {
7250           ShadowedDecl = I;
7251           break;
7252         }
7253     }
7254 
7255   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7256 
7257   unsigned WarningDiag = diag::warn_decl_shadow;
7258   SourceLocation CaptureLoc;
7259   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7260       isa<CXXMethodDecl>(NewDC)) {
7261     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7262       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7263         if (RD->getLambdaCaptureDefault() == LCD_None) {
7264           // Try to avoid warnings for lambdas with an explicit capture list.
7265           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7266           // Warn only when the lambda captures the shadowed decl explicitly.
7267           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7268           if (CaptureLoc.isInvalid())
7269             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7270         } else {
7271           // Remember that this was shadowed so we can avoid the warning if the
7272           // shadowed decl isn't captured and the warning settings allow it.
7273           cast<LambdaScopeInfo>(getCurFunction())
7274               ->ShadowingDecls.push_back(
7275                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7276           return;
7277         }
7278       }
7279 
7280       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7281         // A variable can't shadow a local variable in an enclosing scope, if
7282         // they are separated by a non-capturing declaration context.
7283         for (DeclContext *ParentDC = NewDC;
7284              ParentDC && !ParentDC->Equals(OldDC);
7285              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7286           // Only block literals, captured statements, and lambda expressions
7287           // can capture; other scopes don't.
7288           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7289               !isLambdaCallOperator(ParentDC)) {
7290             return;
7291           }
7292         }
7293       }
7294     }
7295   }
7296 
7297   // Only warn about certain kinds of shadowing for class members.
7298   if (NewDC && NewDC->isRecord()) {
7299     // In particular, don't warn about shadowing non-class members.
7300     if (!OldDC->isRecord())
7301       return;
7302 
7303     // TODO: should we warn about static data members shadowing
7304     // static data members from base classes?
7305 
7306     // TODO: don't diagnose for inaccessible shadowed members.
7307     // This is hard to do perfectly because we might friend the
7308     // shadowing context, but that's just a false negative.
7309   }
7310 
7311 
7312   DeclarationName Name = R.getLookupName();
7313 
7314   // Emit warning and note.
7315   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7316     return;
7317   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7318   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7319   if (!CaptureLoc.isInvalid())
7320     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7321         << Name << /*explicitly*/ 1;
7322   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7323 }
7324 
7325 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7326 /// when these variables are captured by the lambda.
7327 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7328   for (const auto &Shadow : LSI->ShadowingDecls) {
7329     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7330     // Try to avoid the warning when the shadowed decl isn't captured.
7331     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7332     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7333     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7334                                        ? diag::warn_decl_shadow_uncaptured_local
7335                                        : diag::warn_decl_shadow)
7336         << Shadow.VD->getDeclName()
7337         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7338     if (!CaptureLoc.isInvalid())
7339       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7340           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7341     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7342   }
7343 }
7344 
7345 /// Check -Wshadow without the advantage of a previous lookup.
7346 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7347   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7348     return;
7349 
7350   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7351                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7352   LookupName(R, S);
7353   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7354     CheckShadow(D, ShadowedDecl, R);
7355 }
7356 
7357 /// Check if 'E', which is an expression that is about to be modified, refers
7358 /// to a constructor parameter that shadows a field.
7359 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7360   // Quickly ignore expressions that can't be shadowing ctor parameters.
7361   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7362     return;
7363   E = E->IgnoreParenImpCasts();
7364   auto *DRE = dyn_cast<DeclRefExpr>(E);
7365   if (!DRE)
7366     return;
7367   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7368   auto I = ShadowingDecls.find(D);
7369   if (I == ShadowingDecls.end())
7370     return;
7371   const NamedDecl *ShadowedDecl = I->second;
7372   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7373   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7374   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7375   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7376 
7377   // Avoid issuing multiple warnings about the same decl.
7378   ShadowingDecls.erase(I);
7379 }
7380 
7381 /// Check for conflict between this global or extern "C" declaration and
7382 /// previous global or extern "C" declarations. This is only used in C++.
7383 template<typename T>
7384 static bool checkGlobalOrExternCConflict(
7385     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7386   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7387   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7388 
7389   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7390     // The common case: this global doesn't conflict with any extern "C"
7391     // declaration.
7392     return false;
7393   }
7394 
7395   if (Prev) {
7396     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7397       // Both the old and new declarations have C language linkage. This is a
7398       // redeclaration.
7399       Previous.clear();
7400       Previous.addDecl(Prev);
7401       return true;
7402     }
7403 
7404     // This is a global, non-extern "C" declaration, and there is a previous
7405     // non-global extern "C" declaration. Diagnose if this is a variable
7406     // declaration.
7407     if (!isa<VarDecl>(ND))
7408       return false;
7409   } else {
7410     // The declaration is extern "C". Check for any declaration in the
7411     // translation unit which might conflict.
7412     if (IsGlobal) {
7413       // We have already performed the lookup into the translation unit.
7414       IsGlobal = false;
7415       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7416            I != E; ++I) {
7417         if (isa<VarDecl>(*I)) {
7418           Prev = *I;
7419           break;
7420         }
7421       }
7422     } else {
7423       DeclContext::lookup_result R =
7424           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7425       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7426            I != E; ++I) {
7427         if (isa<VarDecl>(*I)) {
7428           Prev = *I;
7429           break;
7430         }
7431         // FIXME: If we have any other entity with this name in global scope,
7432         // the declaration is ill-formed, but that is a defect: it breaks the
7433         // 'stat' hack, for instance. Only variables can have mangled name
7434         // clashes with extern "C" declarations, so only they deserve a
7435         // diagnostic.
7436       }
7437     }
7438 
7439     if (!Prev)
7440       return false;
7441   }
7442 
7443   // Use the first declaration's location to ensure we point at something which
7444   // is lexically inside an extern "C" linkage-spec.
7445   assert(Prev && "should have found a previous declaration to diagnose");
7446   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7447     Prev = FD->getFirstDecl();
7448   else
7449     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7450 
7451   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7452     << IsGlobal << ND;
7453   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7454     << IsGlobal;
7455   return false;
7456 }
7457 
7458 /// Apply special rules for handling extern "C" declarations. Returns \c true
7459 /// if we have found that this is a redeclaration of some prior entity.
7460 ///
7461 /// Per C++ [dcl.link]p6:
7462 ///   Two declarations [for a function or variable] with C language linkage
7463 ///   with the same name that appear in different scopes refer to the same
7464 ///   [entity]. An entity with C language linkage shall not be declared with
7465 ///   the same name as an entity in global scope.
7466 template<typename T>
7467 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7468                                                   LookupResult &Previous) {
7469   if (!S.getLangOpts().CPlusPlus) {
7470     // In C, when declaring a global variable, look for a corresponding 'extern'
7471     // variable declared in function scope. We don't need this in C++, because
7472     // we find local extern decls in the surrounding file-scope DeclContext.
7473     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7474       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7475         Previous.clear();
7476         Previous.addDecl(Prev);
7477         return true;
7478       }
7479     }
7480     return false;
7481   }
7482 
7483   // A declaration in the translation unit can conflict with an extern "C"
7484   // declaration.
7485   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7486     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7487 
7488   // An extern "C" declaration can conflict with a declaration in the
7489   // translation unit or can be a redeclaration of an extern "C" declaration
7490   // in another scope.
7491   if (isIncompleteDeclExternC(S,ND))
7492     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7493 
7494   // Neither global nor extern "C": nothing to do.
7495   return false;
7496 }
7497 
7498 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7499   // If the decl is already known invalid, don't check it.
7500   if (NewVD->isInvalidDecl())
7501     return;
7502 
7503   QualType T = NewVD->getType();
7504 
7505   // Defer checking an 'auto' type until its initializer is attached.
7506   if (T->isUndeducedType())
7507     return;
7508 
7509   if (NewVD->hasAttrs())
7510     CheckAlignasUnderalignment(NewVD);
7511 
7512   if (T->isObjCObjectType()) {
7513     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7514       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7515     T = Context.getObjCObjectPointerType(T);
7516     NewVD->setType(T);
7517   }
7518 
7519   // Emit an error if an address space was applied to decl with local storage.
7520   // This includes arrays of objects with address space qualifiers, but not
7521   // automatic variables that point to other address spaces.
7522   // ISO/IEC TR 18037 S5.1.2
7523   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7524       T.getAddressSpace() != LangAS::Default) {
7525     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7526     NewVD->setInvalidDecl();
7527     return;
7528   }
7529 
7530   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7531   // scope.
7532   if (getLangOpts().OpenCLVersion == 120 &&
7533       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7534       NewVD->isStaticLocal()) {
7535     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7536     NewVD->setInvalidDecl();
7537     return;
7538   }
7539 
7540   if (getLangOpts().OpenCL) {
7541     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7542     if (NewVD->hasAttr<BlocksAttr>()) {
7543       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7544       return;
7545     }
7546 
7547     if (T->isBlockPointerType()) {
7548       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7549       // can't use 'extern' storage class.
7550       if (!T.isConstQualified()) {
7551         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7552             << 0 /*const*/;
7553         NewVD->setInvalidDecl();
7554         return;
7555       }
7556       if (NewVD->hasExternalStorage()) {
7557         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7558         NewVD->setInvalidDecl();
7559         return;
7560       }
7561     }
7562     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7563     // __constant address space.
7564     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7565     // variables inside a function can also be declared in the global
7566     // address space.
7567     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7568     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7569     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7570         NewVD->hasExternalStorage()) {
7571       if (!T->isSamplerT() &&
7572           !(T.getAddressSpace() == LangAS::opencl_constant ||
7573             (T.getAddressSpace() == LangAS::opencl_global &&
7574              (getLangOpts().OpenCLVersion == 200 ||
7575               getLangOpts().OpenCLCPlusPlus)))) {
7576         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7577         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7578           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7579               << Scope << "global or constant";
7580         else
7581           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7582               << Scope << "constant";
7583         NewVD->setInvalidDecl();
7584         return;
7585       }
7586     } else {
7587       if (T.getAddressSpace() == LangAS::opencl_global) {
7588         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7589             << 1 /*is any function*/ << "global";
7590         NewVD->setInvalidDecl();
7591         return;
7592       }
7593       if (T.getAddressSpace() == LangAS::opencl_constant ||
7594           T.getAddressSpace() == LangAS::opencl_local) {
7595         FunctionDecl *FD = getCurFunctionDecl();
7596         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7597         // in functions.
7598         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7599           if (T.getAddressSpace() == LangAS::opencl_constant)
7600             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7601                 << 0 /*non-kernel only*/ << "constant";
7602           else
7603             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7604                 << 0 /*non-kernel only*/ << "local";
7605           NewVD->setInvalidDecl();
7606           return;
7607         }
7608         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7609         // in the outermost scope of a kernel function.
7610         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7611           if (!getCurScope()->isFunctionScope()) {
7612             if (T.getAddressSpace() == LangAS::opencl_constant)
7613               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7614                   << "constant";
7615             else
7616               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7617                   << "local";
7618             NewVD->setInvalidDecl();
7619             return;
7620           }
7621         }
7622       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7623                  // If we are parsing a template we didn't deduce an addr
7624                  // space yet.
7625                  T.getAddressSpace() != LangAS::Default) {
7626         // Do not allow other address spaces on automatic variable.
7627         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7628         NewVD->setInvalidDecl();
7629         return;
7630       }
7631     }
7632   }
7633 
7634   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7635       && !NewVD->hasAttr<BlocksAttr>()) {
7636     if (getLangOpts().getGC() != LangOptions::NonGC)
7637       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7638     else {
7639       assert(!getLangOpts().ObjCAutoRefCount);
7640       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7641     }
7642   }
7643 
7644   bool isVM = T->isVariablyModifiedType();
7645   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7646       NewVD->hasAttr<BlocksAttr>())
7647     setFunctionHasBranchProtectedScope();
7648 
7649   if ((isVM && NewVD->hasLinkage()) ||
7650       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7651     bool SizeIsNegative;
7652     llvm::APSInt Oversized;
7653     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7654         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7655     QualType FixedT;
7656     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7657       FixedT = FixedTInfo->getType();
7658     else if (FixedTInfo) {
7659       // Type and type-as-written are canonically different. We need to fix up
7660       // both types separately.
7661       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7662                                                    Oversized);
7663     }
7664     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7665       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7666       // FIXME: This won't give the correct result for
7667       // int a[10][n];
7668       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7669 
7670       if (NewVD->isFileVarDecl())
7671         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7672         << SizeRange;
7673       else if (NewVD->isStaticLocal())
7674         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7675         << SizeRange;
7676       else
7677         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7678         << SizeRange;
7679       NewVD->setInvalidDecl();
7680       return;
7681     }
7682 
7683     if (!FixedTInfo) {
7684       if (NewVD->isFileVarDecl())
7685         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7686       else
7687         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7688       NewVD->setInvalidDecl();
7689       return;
7690     }
7691 
7692     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7693     NewVD->setType(FixedT);
7694     NewVD->setTypeSourceInfo(FixedTInfo);
7695   }
7696 
7697   if (T->isVoidType()) {
7698     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7699     //                    of objects and functions.
7700     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7701       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7702         << T;
7703       NewVD->setInvalidDecl();
7704       return;
7705     }
7706   }
7707 
7708   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7709     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7710     NewVD->setInvalidDecl();
7711     return;
7712   }
7713 
7714   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7715     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7716     NewVD->setInvalidDecl();
7717     return;
7718   }
7719 
7720   if (NewVD->isConstexpr() && !T->isDependentType() &&
7721       RequireLiteralType(NewVD->getLocation(), T,
7722                          diag::err_constexpr_var_non_literal)) {
7723     NewVD->setInvalidDecl();
7724     return;
7725   }
7726 }
7727 
7728 /// Perform semantic checking on a newly-created variable
7729 /// declaration.
7730 ///
7731 /// This routine performs all of the type-checking required for a
7732 /// variable declaration once it has been built. It is used both to
7733 /// check variables after they have been parsed and their declarators
7734 /// have been translated into a declaration, and to check variables
7735 /// that have been instantiated from a template.
7736 ///
7737 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7738 ///
7739 /// Returns true if the variable declaration is a redeclaration.
7740 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7741   CheckVariableDeclarationType(NewVD);
7742 
7743   // If the decl is already known invalid, don't check it.
7744   if (NewVD->isInvalidDecl())
7745     return false;
7746 
7747   // If we did not find anything by this name, look for a non-visible
7748   // extern "C" declaration with the same name.
7749   if (Previous.empty() &&
7750       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7751     Previous.setShadowed();
7752 
7753   if (!Previous.empty()) {
7754     MergeVarDecl(NewVD, Previous);
7755     return true;
7756   }
7757   return false;
7758 }
7759 
7760 namespace {
7761 struct FindOverriddenMethod {
7762   Sema *S;
7763   CXXMethodDecl *Method;
7764 
7765   /// Member lookup function that determines whether a given C++
7766   /// method overrides a method in a base class, to be used with
7767   /// CXXRecordDecl::lookupInBases().
7768   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7769     RecordDecl *BaseRecord =
7770         Specifier->getType()->getAs<RecordType>()->getDecl();
7771 
7772     DeclarationName Name = Method->getDeclName();
7773 
7774     // FIXME: Do we care about other names here too?
7775     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7776       // We really want to find the base class destructor here.
7777       QualType T = S->Context.getTypeDeclType(BaseRecord);
7778       CanQualType CT = S->Context.getCanonicalType(T);
7779 
7780       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7781     }
7782 
7783     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7784          Path.Decls = Path.Decls.slice(1)) {
7785       NamedDecl *D = Path.Decls.front();
7786       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7787         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7788           return true;
7789       }
7790     }
7791 
7792     return false;
7793   }
7794 };
7795 
7796 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7797 } // end anonymous namespace
7798 
7799 /// Report an error regarding overriding, along with any relevant
7800 /// overridden methods.
7801 ///
7802 /// \param DiagID the primary error to report.
7803 /// \param MD the overriding method.
7804 /// \param OEK which overrides to include as notes.
7805 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7806                             OverrideErrorKind OEK = OEK_All) {
7807   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7808   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7809     // This check (& the OEK parameter) could be replaced by a predicate, but
7810     // without lambdas that would be overkill. This is still nicer than writing
7811     // out the diag loop 3 times.
7812     if ((OEK == OEK_All) ||
7813         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7814         (OEK == OEK_Deleted && O->isDeleted()))
7815       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7816   }
7817 }
7818 
7819 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7820 /// and if so, check that it's a valid override and remember it.
7821 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7822   // Look for methods in base classes that this method might override.
7823   CXXBasePaths Paths;
7824   FindOverriddenMethod FOM;
7825   FOM.Method = MD;
7826   FOM.S = this;
7827   bool hasDeletedOverridenMethods = false;
7828   bool hasNonDeletedOverridenMethods = false;
7829   bool AddedAny = false;
7830   if (DC->lookupInBases(FOM, Paths)) {
7831     for (auto *I : Paths.found_decls()) {
7832       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7833         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7834         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7835             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7836             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7837             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7838           hasDeletedOverridenMethods |= OldMD->isDeleted();
7839           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7840           AddedAny = true;
7841         }
7842       }
7843     }
7844   }
7845 
7846   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7847     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7848   }
7849   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7850     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7851   }
7852 
7853   return AddedAny;
7854 }
7855 
7856 namespace {
7857   // Struct for holding all of the extra arguments needed by
7858   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7859   struct ActOnFDArgs {
7860     Scope *S;
7861     Declarator &D;
7862     MultiTemplateParamsArg TemplateParamLists;
7863     bool AddToScope;
7864   };
7865 } // end anonymous namespace
7866 
7867 namespace {
7868 
7869 // Callback to only accept typo corrections that have a non-zero edit distance.
7870 // Also only accept corrections that have the same parent decl.
7871 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7872  public:
7873   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7874                             CXXRecordDecl *Parent)
7875       : Context(Context), OriginalFD(TypoFD),
7876         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7877 
7878   bool ValidateCandidate(const TypoCorrection &candidate) override {
7879     if (candidate.getEditDistance() == 0)
7880       return false;
7881 
7882     SmallVector<unsigned, 1> MismatchedParams;
7883     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7884                                           CDeclEnd = candidate.end();
7885          CDecl != CDeclEnd; ++CDecl) {
7886       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7887 
7888       if (FD && !FD->hasBody() &&
7889           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7890         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7891           CXXRecordDecl *Parent = MD->getParent();
7892           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7893             return true;
7894         } else if (!ExpectedParent) {
7895           return true;
7896         }
7897       }
7898     }
7899 
7900     return false;
7901   }
7902 
7903   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7904     return std::make_unique<DifferentNameValidatorCCC>(*this);
7905   }
7906 
7907  private:
7908   ASTContext &Context;
7909   FunctionDecl *OriginalFD;
7910   CXXRecordDecl *ExpectedParent;
7911 };
7912 
7913 } // end anonymous namespace
7914 
7915 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7916   TypoCorrectedFunctionDefinitions.insert(F);
7917 }
7918 
7919 /// Generate diagnostics for an invalid function redeclaration.
7920 ///
7921 /// This routine handles generating the diagnostic messages for an invalid
7922 /// function redeclaration, including finding possible similar declarations
7923 /// or performing typo correction if there are no previous declarations with
7924 /// the same name.
7925 ///
7926 /// Returns a NamedDecl iff typo correction was performed and substituting in
7927 /// the new declaration name does not cause new errors.
7928 static NamedDecl *DiagnoseInvalidRedeclaration(
7929     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7930     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7931   DeclarationName Name = NewFD->getDeclName();
7932   DeclContext *NewDC = NewFD->getDeclContext();
7933   SmallVector<unsigned, 1> MismatchedParams;
7934   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7935   TypoCorrection Correction;
7936   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7937   unsigned DiagMsg =
7938     IsLocalFriend ? diag::err_no_matching_local_friend :
7939     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7940     diag::err_member_decl_does_not_match;
7941   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7942                     IsLocalFriend ? Sema::LookupLocalFriendName
7943                                   : Sema::LookupOrdinaryName,
7944                     Sema::ForVisibleRedeclaration);
7945 
7946   NewFD->setInvalidDecl();
7947   if (IsLocalFriend)
7948     SemaRef.LookupName(Prev, S);
7949   else
7950     SemaRef.LookupQualifiedName(Prev, NewDC);
7951   assert(!Prev.isAmbiguous() &&
7952          "Cannot have an ambiguity in previous-declaration lookup");
7953   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7954   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7955                                 MD ? MD->getParent() : nullptr);
7956   if (!Prev.empty()) {
7957     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7958          Func != FuncEnd; ++Func) {
7959       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7960       if (FD &&
7961           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7962         // Add 1 to the index so that 0 can mean the mismatch didn't
7963         // involve a parameter
7964         unsigned ParamNum =
7965             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7966         NearMatches.push_back(std::make_pair(FD, ParamNum));
7967       }
7968     }
7969   // If the qualified name lookup yielded nothing, try typo correction
7970   } else if ((Correction = SemaRef.CorrectTypo(
7971                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7972                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7973                   IsLocalFriend ? nullptr : NewDC))) {
7974     // Set up everything for the call to ActOnFunctionDeclarator
7975     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7976                               ExtraArgs.D.getIdentifierLoc());
7977     Previous.clear();
7978     Previous.setLookupName(Correction.getCorrection());
7979     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7980                                     CDeclEnd = Correction.end();
7981          CDecl != CDeclEnd; ++CDecl) {
7982       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7983       if (FD && !FD->hasBody() &&
7984           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7985         Previous.addDecl(FD);
7986       }
7987     }
7988     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7989 
7990     NamedDecl *Result;
7991     // Retry building the function declaration with the new previous
7992     // declarations, and with errors suppressed.
7993     {
7994       // Trap errors.
7995       Sema::SFINAETrap Trap(SemaRef);
7996 
7997       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7998       // pieces need to verify the typo-corrected C++ declaration and hopefully
7999       // eliminate the need for the parameter pack ExtraArgs.
8000       Result = SemaRef.ActOnFunctionDeclarator(
8001           ExtraArgs.S, ExtraArgs.D,
8002           Correction.getCorrectionDecl()->getDeclContext(),
8003           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8004           ExtraArgs.AddToScope);
8005 
8006       if (Trap.hasErrorOccurred())
8007         Result = nullptr;
8008     }
8009 
8010     if (Result) {
8011       // Determine which correction we picked.
8012       Decl *Canonical = Result->getCanonicalDecl();
8013       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8014            I != E; ++I)
8015         if ((*I)->getCanonicalDecl() == Canonical)
8016           Correction.setCorrectionDecl(*I);
8017 
8018       // Let Sema know about the correction.
8019       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8020       SemaRef.diagnoseTypo(
8021           Correction,
8022           SemaRef.PDiag(IsLocalFriend
8023                           ? diag::err_no_matching_local_friend_suggest
8024                           : diag::err_member_decl_does_not_match_suggest)
8025             << Name << NewDC << IsDefinition);
8026       return Result;
8027     }
8028 
8029     // Pretend the typo correction never occurred
8030     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8031                               ExtraArgs.D.getIdentifierLoc());
8032     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8033     Previous.clear();
8034     Previous.setLookupName(Name);
8035   }
8036 
8037   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8038       << Name << NewDC << IsDefinition << NewFD->getLocation();
8039 
8040   bool NewFDisConst = false;
8041   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8042     NewFDisConst = NewMD->isConst();
8043 
8044   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8045        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8046        NearMatch != NearMatchEnd; ++NearMatch) {
8047     FunctionDecl *FD = NearMatch->first;
8048     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8049     bool FDisConst = MD && MD->isConst();
8050     bool IsMember = MD || !IsLocalFriend;
8051 
8052     // FIXME: These notes are poorly worded for the local friend case.
8053     if (unsigned Idx = NearMatch->second) {
8054       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8055       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8056       if (Loc.isInvalid()) Loc = FD->getLocation();
8057       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8058                                  : diag::note_local_decl_close_param_match)
8059         << Idx << FDParam->getType()
8060         << NewFD->getParamDecl(Idx - 1)->getType();
8061     } else if (FDisConst != NewFDisConst) {
8062       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8063           << NewFDisConst << FD->getSourceRange().getEnd();
8064     } else
8065       SemaRef.Diag(FD->getLocation(),
8066                    IsMember ? diag::note_member_def_close_match
8067                             : diag::note_local_decl_close_match);
8068   }
8069   return nullptr;
8070 }
8071 
8072 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8073   switch (D.getDeclSpec().getStorageClassSpec()) {
8074   default: llvm_unreachable("Unknown storage class!");
8075   case DeclSpec::SCS_auto:
8076   case DeclSpec::SCS_register:
8077   case DeclSpec::SCS_mutable:
8078     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8079                  diag::err_typecheck_sclass_func);
8080     D.getMutableDeclSpec().ClearStorageClassSpecs();
8081     D.setInvalidType();
8082     break;
8083   case DeclSpec::SCS_unspecified: break;
8084   case DeclSpec::SCS_extern:
8085     if (D.getDeclSpec().isExternInLinkageSpec())
8086       return SC_None;
8087     return SC_Extern;
8088   case DeclSpec::SCS_static: {
8089     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8090       // C99 6.7.1p5:
8091       //   The declaration of an identifier for a function that has
8092       //   block scope shall have no explicit storage-class specifier
8093       //   other than extern
8094       // See also (C++ [dcl.stc]p4).
8095       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8096                    diag::err_static_block_func);
8097       break;
8098     } else
8099       return SC_Static;
8100   }
8101   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8102   }
8103 
8104   // No explicit storage class has already been returned
8105   return SC_None;
8106 }
8107 
8108 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8109                                            DeclContext *DC, QualType &R,
8110                                            TypeSourceInfo *TInfo,
8111                                            StorageClass SC,
8112                                            bool &IsVirtualOkay) {
8113   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8114   DeclarationName Name = NameInfo.getName();
8115 
8116   FunctionDecl *NewFD = nullptr;
8117   bool isInline = D.getDeclSpec().isInlineSpecified();
8118 
8119   if (!SemaRef.getLangOpts().CPlusPlus) {
8120     // Determine whether the function was written with a
8121     // prototype. This true when:
8122     //   - there is a prototype in the declarator, or
8123     //   - the type R of the function is some kind of typedef or other non-
8124     //     attributed reference to a type name (which eventually refers to a
8125     //     function type).
8126     bool HasPrototype =
8127       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8128       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8129 
8130     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8131                                  R, TInfo, SC, isInline, HasPrototype,
8132                                  CSK_unspecified);
8133     if (D.isInvalidType())
8134       NewFD->setInvalidDecl();
8135 
8136     return NewFD;
8137   }
8138 
8139   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8140 
8141   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8142   if (ConstexprKind == CSK_constinit) {
8143     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8144                  diag::err_constexpr_wrong_decl_kind)
8145         << ConstexprKind;
8146     ConstexprKind = CSK_unspecified;
8147     D.getMutableDeclSpec().ClearConstexprSpec();
8148   }
8149 
8150   // Check that the return type is not an abstract class type.
8151   // For record types, this is done by the AbstractClassUsageDiagnoser once
8152   // the class has been completely parsed.
8153   if (!DC->isRecord() &&
8154       SemaRef.RequireNonAbstractType(
8155           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8156           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8157     D.setInvalidType();
8158 
8159   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8160     // This is a C++ constructor declaration.
8161     assert(DC->isRecord() &&
8162            "Constructors can only be declared in a member context");
8163 
8164     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8165     return CXXConstructorDecl::Create(
8166         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8167         TInfo, ExplicitSpecifier, isInline,
8168         /*isImplicitlyDeclared=*/false, ConstexprKind);
8169 
8170   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8171     // This is a C++ destructor declaration.
8172     if (DC->isRecord()) {
8173       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8174       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8175       CXXDestructorDecl *NewDD =
8176           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8177                                     NameInfo, R, TInfo, isInline,
8178                                     /*isImplicitlyDeclared=*/false);
8179 
8180       // If the destructor needs an implicit exception specification, set it
8181       // now. FIXME: It'd be nice to be able to create the right type to start
8182       // with, but the type needs to reference the destructor declaration.
8183       if (SemaRef.getLangOpts().CPlusPlus11)
8184         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8185 
8186       IsVirtualOkay = true;
8187       return NewDD;
8188 
8189     } else {
8190       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8191       D.setInvalidType();
8192 
8193       // Create a FunctionDecl to satisfy the function definition parsing
8194       // code path.
8195       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8196                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8197                                   isInline,
8198                                   /*hasPrototype=*/true, ConstexprKind);
8199     }
8200 
8201   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8202     if (!DC->isRecord()) {
8203       SemaRef.Diag(D.getIdentifierLoc(),
8204            diag::err_conv_function_not_member);
8205       return nullptr;
8206     }
8207 
8208     SemaRef.CheckConversionDeclarator(D, R, SC);
8209     IsVirtualOkay = true;
8210     return CXXConversionDecl::Create(
8211         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8212         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8213 
8214   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8215     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8216 
8217     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8218                                          ExplicitSpecifier, NameInfo, R, TInfo,
8219                                          D.getEndLoc());
8220   } else if (DC->isRecord()) {
8221     // If the name of the function is the same as the name of the record,
8222     // then this must be an invalid constructor that has a return type.
8223     // (The parser checks for a return type and makes the declarator a
8224     // constructor if it has no return type).
8225     if (Name.getAsIdentifierInfo() &&
8226         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8227       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8228         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8229         << SourceRange(D.getIdentifierLoc());
8230       return nullptr;
8231     }
8232 
8233     // This is a C++ method declaration.
8234     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8235         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8236         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8237     IsVirtualOkay = !Ret->isStatic();
8238     return Ret;
8239   } else {
8240     bool isFriend =
8241         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8242     if (!isFriend && SemaRef.CurContext->isRecord())
8243       return nullptr;
8244 
8245     // Determine whether the function was written with a
8246     // prototype. This true when:
8247     //   - we're in C++ (where every function has a prototype),
8248     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8249                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8250                                 ConstexprKind);
8251   }
8252 }
8253 
8254 enum OpenCLParamType {
8255   ValidKernelParam,
8256   PtrPtrKernelParam,
8257   PtrKernelParam,
8258   InvalidAddrSpacePtrKernelParam,
8259   InvalidKernelParam,
8260   RecordKernelParam
8261 };
8262 
8263 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8264   // Size dependent types are just typedefs to normal integer types
8265   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8266   // integers other than by their names.
8267   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8268 
8269   // Remove typedefs one by one until we reach a typedef
8270   // for a size dependent type.
8271   QualType DesugaredTy = Ty;
8272   do {
8273     ArrayRef<StringRef> Names(SizeTypeNames);
8274     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8275     if (Names.end() != Match)
8276       return true;
8277 
8278     Ty = DesugaredTy;
8279     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8280   } while (DesugaredTy != Ty);
8281 
8282   return false;
8283 }
8284 
8285 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8286   if (PT->isPointerType()) {
8287     QualType PointeeType = PT->getPointeeType();
8288     if (PointeeType->isPointerType())
8289       return PtrPtrKernelParam;
8290     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8291         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8292         PointeeType.getAddressSpace() == LangAS::Default)
8293       return InvalidAddrSpacePtrKernelParam;
8294     return PtrKernelParam;
8295   }
8296 
8297   // OpenCL v1.2 s6.9.k:
8298   // Arguments to kernel functions in a program cannot be declared with the
8299   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8300   // uintptr_t or a struct and/or union that contain fields declared to be one
8301   // of these built-in scalar types.
8302   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8303     return InvalidKernelParam;
8304 
8305   if (PT->isImageType())
8306     return PtrKernelParam;
8307 
8308   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8309     return InvalidKernelParam;
8310 
8311   // OpenCL extension spec v1.2 s9.5:
8312   // This extension adds support for half scalar and vector types as built-in
8313   // types that can be used for arithmetic operations, conversions etc.
8314   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8315     return InvalidKernelParam;
8316 
8317   if (PT->isRecordType())
8318     return RecordKernelParam;
8319 
8320   // Look into an array argument to check if it has a forbidden type.
8321   if (PT->isArrayType()) {
8322     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8323     // Call ourself to check an underlying type of an array. Since the
8324     // getPointeeOrArrayElementType returns an innermost type which is not an
8325     // array, this recursive call only happens once.
8326     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8327   }
8328 
8329   return ValidKernelParam;
8330 }
8331 
8332 static void checkIsValidOpenCLKernelParameter(
8333   Sema &S,
8334   Declarator &D,
8335   ParmVarDecl *Param,
8336   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8337   QualType PT = Param->getType();
8338 
8339   // Cache the valid types we encounter to avoid rechecking structs that are
8340   // used again
8341   if (ValidTypes.count(PT.getTypePtr()))
8342     return;
8343 
8344   switch (getOpenCLKernelParameterType(S, PT)) {
8345   case PtrPtrKernelParam:
8346     // OpenCL v1.2 s6.9.a:
8347     // A kernel function argument cannot be declared as a
8348     // pointer to a pointer type.
8349     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8350     D.setInvalidType();
8351     return;
8352 
8353   case InvalidAddrSpacePtrKernelParam:
8354     // OpenCL v1.0 s6.5:
8355     // __kernel function arguments declared to be a pointer of a type can point
8356     // to one of the following address spaces only : __global, __local or
8357     // __constant.
8358     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8359     D.setInvalidType();
8360     return;
8361 
8362     // OpenCL v1.2 s6.9.k:
8363     // Arguments to kernel functions in a program cannot be declared with the
8364     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8365     // uintptr_t or a struct and/or union that contain fields declared to be
8366     // one of these built-in scalar types.
8367 
8368   case InvalidKernelParam:
8369     // OpenCL v1.2 s6.8 n:
8370     // A kernel function argument cannot be declared
8371     // of event_t type.
8372     // Do not diagnose half type since it is diagnosed as invalid argument
8373     // type for any function elsewhere.
8374     if (!PT->isHalfType()) {
8375       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8376 
8377       // Explain what typedefs are involved.
8378       const TypedefType *Typedef = nullptr;
8379       while ((Typedef = PT->getAs<TypedefType>())) {
8380         SourceLocation Loc = Typedef->getDecl()->getLocation();
8381         // SourceLocation may be invalid for a built-in type.
8382         if (Loc.isValid())
8383           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8384         PT = Typedef->desugar();
8385       }
8386     }
8387 
8388     D.setInvalidType();
8389     return;
8390 
8391   case PtrKernelParam:
8392   case ValidKernelParam:
8393     ValidTypes.insert(PT.getTypePtr());
8394     return;
8395 
8396   case RecordKernelParam:
8397     break;
8398   }
8399 
8400   // Track nested structs we will inspect
8401   SmallVector<const Decl *, 4> VisitStack;
8402 
8403   // Track where we are in the nested structs. Items will migrate from
8404   // VisitStack to HistoryStack as we do the DFS for bad field.
8405   SmallVector<const FieldDecl *, 4> HistoryStack;
8406   HistoryStack.push_back(nullptr);
8407 
8408   // At this point we already handled everything except of a RecordType or
8409   // an ArrayType of a RecordType.
8410   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8411   const RecordType *RecTy =
8412       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8413   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8414 
8415   VisitStack.push_back(RecTy->getDecl());
8416   assert(VisitStack.back() && "First decl null?");
8417 
8418   do {
8419     const Decl *Next = VisitStack.pop_back_val();
8420     if (!Next) {
8421       assert(!HistoryStack.empty());
8422       // Found a marker, we have gone up a level
8423       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8424         ValidTypes.insert(Hist->getType().getTypePtr());
8425 
8426       continue;
8427     }
8428 
8429     // Adds everything except the original parameter declaration (which is not a
8430     // field itself) to the history stack.
8431     const RecordDecl *RD;
8432     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8433       HistoryStack.push_back(Field);
8434 
8435       QualType FieldTy = Field->getType();
8436       // Other field types (known to be valid or invalid) are handled while we
8437       // walk around RecordDecl::fields().
8438       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8439              "Unexpected type.");
8440       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8441 
8442       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8443     } else {
8444       RD = cast<RecordDecl>(Next);
8445     }
8446 
8447     // Add a null marker so we know when we've gone back up a level
8448     VisitStack.push_back(nullptr);
8449 
8450     for (const auto *FD : RD->fields()) {
8451       QualType QT = FD->getType();
8452 
8453       if (ValidTypes.count(QT.getTypePtr()))
8454         continue;
8455 
8456       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8457       if (ParamType == ValidKernelParam)
8458         continue;
8459 
8460       if (ParamType == RecordKernelParam) {
8461         VisitStack.push_back(FD);
8462         continue;
8463       }
8464 
8465       // OpenCL v1.2 s6.9.p:
8466       // Arguments to kernel functions that are declared to be a struct or union
8467       // do not allow OpenCL objects to be passed as elements of the struct or
8468       // union.
8469       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8470           ParamType == InvalidAddrSpacePtrKernelParam) {
8471         S.Diag(Param->getLocation(),
8472                diag::err_record_with_pointers_kernel_param)
8473           << PT->isUnionType()
8474           << PT;
8475       } else {
8476         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8477       }
8478 
8479       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8480           << OrigRecDecl->getDeclName();
8481 
8482       // We have an error, now let's go back up through history and show where
8483       // the offending field came from
8484       for (ArrayRef<const FieldDecl *>::const_iterator
8485                I = HistoryStack.begin() + 1,
8486                E = HistoryStack.end();
8487            I != E; ++I) {
8488         const FieldDecl *OuterField = *I;
8489         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8490           << OuterField->getType();
8491       }
8492 
8493       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8494         << QT->isPointerType()
8495         << QT;
8496       D.setInvalidType();
8497       return;
8498     }
8499   } while (!VisitStack.empty());
8500 }
8501 
8502 /// Find the DeclContext in which a tag is implicitly declared if we see an
8503 /// elaborated type specifier in the specified context, and lookup finds
8504 /// nothing.
8505 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8506   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8507     DC = DC->getParent();
8508   return DC;
8509 }
8510 
8511 /// Find the Scope in which a tag is implicitly declared if we see an
8512 /// elaborated type specifier in the specified context, and lookup finds
8513 /// nothing.
8514 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8515   while (S->isClassScope() ||
8516          (LangOpts.CPlusPlus &&
8517           S->isFunctionPrototypeScope()) ||
8518          ((S->getFlags() & Scope::DeclScope) == 0) ||
8519          (S->getEntity() && S->getEntity()->isTransparentContext()))
8520     S = S->getParent();
8521   return S;
8522 }
8523 
8524 NamedDecl*
8525 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8526                               TypeSourceInfo *TInfo, LookupResult &Previous,
8527                               MultiTemplateParamsArg TemplateParamLists,
8528                               bool &AddToScope) {
8529   QualType R = TInfo->getType();
8530 
8531   assert(R->isFunctionType());
8532 
8533   // TODO: consider using NameInfo for diagnostic.
8534   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8535   DeclarationName Name = NameInfo.getName();
8536   StorageClass SC = getFunctionStorageClass(*this, D);
8537 
8538   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8539     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8540          diag::err_invalid_thread)
8541       << DeclSpec::getSpecifierName(TSCS);
8542 
8543   if (D.isFirstDeclarationOfMember())
8544     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8545                            D.getIdentifierLoc());
8546 
8547   bool isFriend = false;
8548   FunctionTemplateDecl *FunctionTemplate = nullptr;
8549   bool isMemberSpecialization = false;
8550   bool isFunctionTemplateSpecialization = false;
8551 
8552   bool isDependentClassScopeExplicitSpecialization = false;
8553   bool HasExplicitTemplateArgs = false;
8554   TemplateArgumentListInfo TemplateArgs;
8555 
8556   bool isVirtualOkay = false;
8557 
8558   DeclContext *OriginalDC = DC;
8559   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8560 
8561   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8562                                               isVirtualOkay);
8563   if (!NewFD) return nullptr;
8564 
8565   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8566     NewFD->setTopLevelDeclInObjCContainer();
8567 
8568   // Set the lexical context. If this is a function-scope declaration, or has a
8569   // C++ scope specifier, or is the object of a friend declaration, the lexical
8570   // context will be different from the semantic context.
8571   NewFD->setLexicalDeclContext(CurContext);
8572 
8573   if (IsLocalExternDecl)
8574     NewFD->setLocalExternDecl();
8575 
8576   if (getLangOpts().CPlusPlus) {
8577     bool isInline = D.getDeclSpec().isInlineSpecified();
8578     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8579     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8580     isFriend = D.getDeclSpec().isFriendSpecified();
8581     if (isFriend && !isInline && D.isFunctionDefinition()) {
8582       // C++ [class.friend]p5
8583       //   A function can be defined in a friend declaration of a
8584       //   class . . . . Such a function is implicitly inline.
8585       NewFD->setImplicitlyInline();
8586     }
8587 
8588     // If this is a method defined in an __interface, and is not a constructor
8589     // or an overloaded operator, then set the pure flag (isVirtual will already
8590     // return true).
8591     if (const CXXRecordDecl *Parent =
8592           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8593       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8594         NewFD->setPure(true);
8595 
8596       // C++ [class.union]p2
8597       //   A union can have member functions, but not virtual functions.
8598       if (isVirtual && Parent->isUnion())
8599         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8600     }
8601 
8602     SetNestedNameSpecifier(*this, NewFD, D);
8603     isMemberSpecialization = false;
8604     isFunctionTemplateSpecialization = false;
8605     if (D.isInvalidType())
8606       NewFD->setInvalidDecl();
8607 
8608     // Match up the template parameter lists with the scope specifier, then
8609     // determine whether we have a template or a template specialization.
8610     bool Invalid = false;
8611     if (TemplateParameterList *TemplateParams =
8612             MatchTemplateParametersToScopeSpecifier(
8613                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8614                 D.getCXXScopeSpec(),
8615                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8616                     ? D.getName().TemplateId
8617                     : nullptr,
8618                 TemplateParamLists, isFriend, isMemberSpecialization,
8619                 Invalid)) {
8620       if (TemplateParams->size() > 0) {
8621         // This is a function template
8622 
8623         // Check that we can declare a template here.
8624         if (CheckTemplateDeclScope(S, TemplateParams))
8625           NewFD->setInvalidDecl();
8626 
8627         // A destructor cannot be a template.
8628         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8629           Diag(NewFD->getLocation(), diag::err_destructor_template);
8630           NewFD->setInvalidDecl();
8631         }
8632 
8633         // If we're adding a template to a dependent context, we may need to
8634         // rebuilding some of the types used within the template parameter list,
8635         // now that we know what the current instantiation is.
8636         if (DC->isDependentContext()) {
8637           ContextRAII SavedContext(*this, DC);
8638           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8639             Invalid = true;
8640         }
8641 
8642         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8643                                                         NewFD->getLocation(),
8644                                                         Name, TemplateParams,
8645                                                         NewFD);
8646         FunctionTemplate->setLexicalDeclContext(CurContext);
8647         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8648 
8649         // For source fidelity, store the other template param lists.
8650         if (TemplateParamLists.size() > 1) {
8651           NewFD->setTemplateParameterListsInfo(Context,
8652                                                TemplateParamLists.drop_back(1));
8653         }
8654       } else {
8655         // This is a function template specialization.
8656         isFunctionTemplateSpecialization = true;
8657         // For source fidelity, store all the template param lists.
8658         if (TemplateParamLists.size() > 0)
8659           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8660 
8661         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8662         if (isFriend) {
8663           // We want to remove the "template<>", found here.
8664           SourceRange RemoveRange = TemplateParams->getSourceRange();
8665 
8666           // If we remove the template<> and the name is not a
8667           // template-id, we're actually silently creating a problem:
8668           // the friend declaration will refer to an untemplated decl,
8669           // and clearly the user wants a template specialization.  So
8670           // we need to insert '<>' after the name.
8671           SourceLocation InsertLoc;
8672           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8673             InsertLoc = D.getName().getSourceRange().getEnd();
8674             InsertLoc = getLocForEndOfToken(InsertLoc);
8675           }
8676 
8677           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8678             << Name << RemoveRange
8679             << FixItHint::CreateRemoval(RemoveRange)
8680             << FixItHint::CreateInsertion(InsertLoc, "<>");
8681         }
8682       }
8683     } else {
8684       // All template param lists were matched against the scope specifier:
8685       // this is NOT (an explicit specialization of) a template.
8686       if (TemplateParamLists.size() > 0)
8687         // For source fidelity, store all the template param lists.
8688         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8689     }
8690 
8691     if (Invalid) {
8692       NewFD->setInvalidDecl();
8693       if (FunctionTemplate)
8694         FunctionTemplate->setInvalidDecl();
8695     }
8696 
8697     // C++ [dcl.fct.spec]p5:
8698     //   The virtual specifier shall only be used in declarations of
8699     //   nonstatic class member functions that appear within a
8700     //   member-specification of a class declaration; see 10.3.
8701     //
8702     if (isVirtual && !NewFD->isInvalidDecl()) {
8703       if (!isVirtualOkay) {
8704         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8705              diag::err_virtual_non_function);
8706       } else if (!CurContext->isRecord()) {
8707         // 'virtual' was specified outside of the class.
8708         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8709              diag::err_virtual_out_of_class)
8710           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8711       } else if (NewFD->getDescribedFunctionTemplate()) {
8712         // C++ [temp.mem]p3:
8713         //  A member function template shall not be virtual.
8714         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8715              diag::err_virtual_member_function_template)
8716           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8717       } else {
8718         // Okay: Add virtual to the method.
8719         NewFD->setVirtualAsWritten(true);
8720       }
8721 
8722       if (getLangOpts().CPlusPlus14 &&
8723           NewFD->getReturnType()->isUndeducedType())
8724         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8725     }
8726 
8727     if (getLangOpts().CPlusPlus14 &&
8728         (NewFD->isDependentContext() ||
8729          (isFriend && CurContext->isDependentContext())) &&
8730         NewFD->getReturnType()->isUndeducedType()) {
8731       // If the function template is referenced directly (for instance, as a
8732       // member of the current instantiation), pretend it has a dependent type.
8733       // This is not really justified by the standard, but is the only sane
8734       // thing to do.
8735       // FIXME: For a friend function, we have not marked the function as being
8736       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8737       const FunctionProtoType *FPT =
8738           NewFD->getType()->castAs<FunctionProtoType>();
8739       QualType Result =
8740           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8741       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8742                                              FPT->getExtProtoInfo()));
8743     }
8744 
8745     // C++ [dcl.fct.spec]p3:
8746     //  The inline specifier shall not appear on a block scope function
8747     //  declaration.
8748     if (isInline && !NewFD->isInvalidDecl()) {
8749       if (CurContext->isFunctionOrMethod()) {
8750         // 'inline' is not allowed on block scope function declaration.
8751         Diag(D.getDeclSpec().getInlineSpecLoc(),
8752              diag::err_inline_declaration_block_scope) << Name
8753           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8754       }
8755     }
8756 
8757     // C++ [dcl.fct.spec]p6:
8758     //  The explicit specifier shall be used only in the declaration of a
8759     //  constructor or conversion function within its class definition;
8760     //  see 12.3.1 and 12.3.2.
8761     if (hasExplicit && !NewFD->isInvalidDecl() &&
8762         !isa<CXXDeductionGuideDecl>(NewFD)) {
8763       if (!CurContext->isRecord()) {
8764         // 'explicit' was specified outside of the class.
8765         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8766              diag::err_explicit_out_of_class)
8767             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8768       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8769                  !isa<CXXConversionDecl>(NewFD)) {
8770         // 'explicit' was specified on a function that wasn't a constructor
8771         // or conversion function.
8772         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8773              diag::err_explicit_non_ctor_or_conv_function)
8774             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8775       }
8776     }
8777 
8778     if (ConstexprSpecKind ConstexprKind =
8779             D.getDeclSpec().getConstexprSpecifier()) {
8780       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8781       // are implicitly inline.
8782       NewFD->setImplicitlyInline();
8783 
8784       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8785       // be either constructors or to return a literal type. Therefore,
8786       // destructors cannot be declared constexpr.
8787       if (isa<CXXDestructorDecl>(NewFD)) {
8788         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8789             << ConstexprKind;
8790       }
8791     }
8792 
8793     // If __module_private__ was specified, mark the function accordingly.
8794     if (D.getDeclSpec().isModulePrivateSpecified()) {
8795       if (isFunctionTemplateSpecialization) {
8796         SourceLocation ModulePrivateLoc
8797           = D.getDeclSpec().getModulePrivateSpecLoc();
8798         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8799           << 0
8800           << FixItHint::CreateRemoval(ModulePrivateLoc);
8801       } else {
8802         NewFD->setModulePrivate();
8803         if (FunctionTemplate)
8804           FunctionTemplate->setModulePrivate();
8805       }
8806     }
8807 
8808     if (isFriend) {
8809       if (FunctionTemplate) {
8810         FunctionTemplate->setObjectOfFriendDecl();
8811         FunctionTemplate->setAccess(AS_public);
8812       }
8813       NewFD->setObjectOfFriendDecl();
8814       NewFD->setAccess(AS_public);
8815     }
8816 
8817     // If a function is defined as defaulted or deleted, mark it as such now.
8818     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8819     // definition kind to FDK_Definition.
8820     switch (D.getFunctionDefinitionKind()) {
8821       case FDK_Declaration:
8822       case FDK_Definition:
8823         break;
8824 
8825       case FDK_Defaulted:
8826         NewFD->setDefaulted();
8827         break;
8828 
8829       case FDK_Deleted:
8830         NewFD->setDeletedAsWritten();
8831         break;
8832     }
8833 
8834     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8835         D.isFunctionDefinition()) {
8836       // C++ [class.mfct]p2:
8837       //   A member function may be defined (8.4) in its class definition, in
8838       //   which case it is an inline member function (7.1.2)
8839       NewFD->setImplicitlyInline();
8840     }
8841 
8842     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8843         !CurContext->isRecord()) {
8844       // C++ [class.static]p1:
8845       //   A data or function member of a class may be declared static
8846       //   in a class definition, in which case it is a static member of
8847       //   the class.
8848 
8849       // Complain about the 'static' specifier if it's on an out-of-line
8850       // member function definition.
8851 
8852       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8853       // member function template declaration and class member template
8854       // declaration (MSVC versions before 2015), warn about this.
8855       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8856            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8857              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8858            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8859            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8860         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8861     }
8862 
8863     // C++11 [except.spec]p15:
8864     //   A deallocation function with no exception-specification is treated
8865     //   as if it were specified with noexcept(true).
8866     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8867     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8868          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8869         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8870       NewFD->setType(Context.getFunctionType(
8871           FPT->getReturnType(), FPT->getParamTypes(),
8872           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8873   }
8874 
8875   // Filter out previous declarations that don't match the scope.
8876   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8877                        D.getCXXScopeSpec().isNotEmpty() ||
8878                        isMemberSpecialization ||
8879                        isFunctionTemplateSpecialization);
8880 
8881   // Handle GNU asm-label extension (encoded as an attribute).
8882   if (Expr *E = (Expr*) D.getAsmLabel()) {
8883     // The parser guarantees this is a string.
8884     StringLiteral *SE = cast<StringLiteral>(E);
8885     NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getStrTokenLoc(0),
8886                                                 SE->getString()));
8887   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8888     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8889       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8890     if (I != ExtnameUndeclaredIdentifiers.end()) {
8891       if (isDeclExternC(NewFD)) {
8892         NewFD->addAttr(I->second);
8893         ExtnameUndeclaredIdentifiers.erase(I);
8894       } else
8895         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8896             << /*Variable*/0 << NewFD;
8897     }
8898   }
8899 
8900   // Copy the parameter declarations from the declarator D to the function
8901   // declaration NewFD, if they are available.  First scavenge them into Params.
8902   SmallVector<ParmVarDecl*, 16> Params;
8903   unsigned FTIIdx;
8904   if (D.isFunctionDeclarator(FTIIdx)) {
8905     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8906 
8907     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8908     // function that takes no arguments, not a function that takes a
8909     // single void argument.
8910     // We let through "const void" here because Sema::GetTypeForDeclarator
8911     // already checks for that case.
8912     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8913       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8914         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8915         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8916         Param->setDeclContext(NewFD);
8917         Params.push_back(Param);
8918 
8919         if (Param->isInvalidDecl())
8920           NewFD->setInvalidDecl();
8921       }
8922     }
8923 
8924     if (!getLangOpts().CPlusPlus) {
8925       // In C, find all the tag declarations from the prototype and move them
8926       // into the function DeclContext. Remove them from the surrounding tag
8927       // injection context of the function, which is typically but not always
8928       // the TU.
8929       DeclContext *PrototypeTagContext =
8930           getTagInjectionContext(NewFD->getLexicalDeclContext());
8931       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8932         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8933 
8934         // We don't want to reparent enumerators. Look at their parent enum
8935         // instead.
8936         if (!TD) {
8937           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8938             TD = cast<EnumDecl>(ECD->getDeclContext());
8939         }
8940         if (!TD)
8941           continue;
8942         DeclContext *TagDC = TD->getLexicalDeclContext();
8943         if (!TagDC->containsDecl(TD))
8944           continue;
8945         TagDC->removeDecl(TD);
8946         TD->setDeclContext(NewFD);
8947         NewFD->addDecl(TD);
8948 
8949         // Preserve the lexical DeclContext if it is not the surrounding tag
8950         // injection context of the FD. In this example, the semantic context of
8951         // E will be f and the lexical context will be S, while both the
8952         // semantic and lexical contexts of S will be f:
8953         //   void f(struct S { enum E { a } f; } s);
8954         if (TagDC != PrototypeTagContext)
8955           TD->setLexicalDeclContext(TagDC);
8956       }
8957     }
8958   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8959     // When we're declaring a function with a typedef, typeof, etc as in the
8960     // following example, we'll need to synthesize (unnamed)
8961     // parameters for use in the declaration.
8962     //
8963     // @code
8964     // typedef void fn(int);
8965     // fn f;
8966     // @endcode
8967 
8968     // Synthesize a parameter for each argument type.
8969     for (const auto &AI : FT->param_types()) {
8970       ParmVarDecl *Param =
8971           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8972       Param->setScopeInfo(0, Params.size());
8973       Params.push_back(Param);
8974     }
8975   } else {
8976     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8977            "Should not need args for typedef of non-prototype fn");
8978   }
8979 
8980   // Finally, we know we have the right number of parameters, install them.
8981   NewFD->setParams(Params);
8982 
8983   if (D.getDeclSpec().isNoreturnSpecified())
8984     NewFD->addAttr(C11NoReturnAttr::Create(Context,
8985                                            D.getDeclSpec().getNoreturnSpecLoc(),
8986                                            AttributeCommonInfo::AS_Keyword));
8987 
8988   // Functions returning a variably modified type violate C99 6.7.5.2p2
8989   // because all functions have linkage.
8990   if (!NewFD->isInvalidDecl() &&
8991       NewFD->getReturnType()->isVariablyModifiedType()) {
8992     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8993     NewFD->setInvalidDecl();
8994   }
8995 
8996   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8997   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8998       !NewFD->hasAttr<SectionAttr>())
8999     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9000         Context, PragmaClangTextSection.SectionName,
9001         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9002 
9003   // Apply an implicit SectionAttr if #pragma code_seg is active.
9004   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9005       !NewFD->hasAttr<SectionAttr>()) {
9006     NewFD->addAttr(SectionAttr::CreateImplicit(
9007         Context, CodeSegStack.CurrentValue->getString(),
9008         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9009         SectionAttr::Declspec_allocate));
9010     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9011                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9012                          ASTContext::PSF_Read,
9013                      NewFD))
9014       NewFD->dropAttr<SectionAttr>();
9015   }
9016 
9017   // Apply an implicit CodeSegAttr from class declspec or
9018   // apply an implicit SectionAttr from #pragma code_seg if active.
9019   if (!NewFD->hasAttr<CodeSegAttr>()) {
9020     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9021                                                                  D.isFunctionDefinition())) {
9022       NewFD->addAttr(SAttr);
9023     }
9024   }
9025 
9026   // Handle attributes.
9027   ProcessDeclAttributes(S, NewFD, D);
9028 
9029   if (getLangOpts().OpenCL) {
9030     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9031     // type declaration will generate a compilation error.
9032     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9033     if (AddressSpace != LangAS::Default) {
9034       Diag(NewFD->getLocation(),
9035            diag::err_opencl_return_value_with_address_space);
9036       NewFD->setInvalidDecl();
9037     }
9038   }
9039 
9040   if (!getLangOpts().CPlusPlus) {
9041     // Perform semantic checking on the function declaration.
9042     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9043       CheckMain(NewFD, D.getDeclSpec());
9044 
9045     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9046       CheckMSVCRTEntryPoint(NewFD);
9047 
9048     if (!NewFD->isInvalidDecl())
9049       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9050                                                   isMemberSpecialization));
9051     else if (!Previous.empty())
9052       // Recover gracefully from an invalid redeclaration.
9053       D.setRedeclaration(true);
9054     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9055             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9056            "previous declaration set still overloaded");
9057 
9058     // Diagnose no-prototype function declarations with calling conventions that
9059     // don't support variadic calls. Only do this in C and do it after merging
9060     // possibly prototyped redeclarations.
9061     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9062     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9063       CallingConv CC = FT->getExtInfo().getCC();
9064       if (!supportsVariadicCall(CC)) {
9065         // Windows system headers sometimes accidentally use stdcall without
9066         // (void) parameters, so we relax this to a warning.
9067         int DiagID =
9068             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9069         Diag(NewFD->getLocation(), DiagID)
9070             << FunctionType::getNameForCallConv(CC);
9071       }
9072     }
9073 
9074    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9075        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9076      checkNonTrivialCUnion(NewFD->getReturnType(),
9077                            NewFD->getReturnTypeSourceRange().getBegin(),
9078                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9079   } else {
9080     // C++11 [replacement.functions]p3:
9081     //  The program's definitions shall not be specified as inline.
9082     //
9083     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9084     //
9085     // Suppress the diagnostic if the function is __attribute__((used)), since
9086     // that forces an external definition to be emitted.
9087     if (D.getDeclSpec().isInlineSpecified() &&
9088         NewFD->isReplaceableGlobalAllocationFunction() &&
9089         !NewFD->hasAttr<UsedAttr>())
9090       Diag(D.getDeclSpec().getInlineSpecLoc(),
9091            diag::ext_operator_new_delete_declared_inline)
9092         << NewFD->getDeclName();
9093 
9094     // If the declarator is a template-id, translate the parser's template
9095     // argument list into our AST format.
9096     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9097       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9098       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9099       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9100       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9101                                          TemplateId->NumArgs);
9102       translateTemplateArguments(TemplateArgsPtr,
9103                                  TemplateArgs);
9104 
9105       HasExplicitTemplateArgs = true;
9106 
9107       if (NewFD->isInvalidDecl()) {
9108         HasExplicitTemplateArgs = false;
9109       } else if (FunctionTemplate) {
9110         // Function template with explicit template arguments.
9111         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9112           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9113 
9114         HasExplicitTemplateArgs = false;
9115       } else {
9116         assert((isFunctionTemplateSpecialization ||
9117                 D.getDeclSpec().isFriendSpecified()) &&
9118                "should have a 'template<>' for this decl");
9119         // "friend void foo<>(int);" is an implicit specialization decl.
9120         isFunctionTemplateSpecialization = true;
9121       }
9122     } else if (isFriend && isFunctionTemplateSpecialization) {
9123       // This combination is only possible in a recovery case;  the user
9124       // wrote something like:
9125       //   template <> friend void foo(int);
9126       // which we're recovering from as if the user had written:
9127       //   friend void foo<>(int);
9128       // Go ahead and fake up a template id.
9129       HasExplicitTemplateArgs = true;
9130       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9131       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9132     }
9133 
9134     // We do not add HD attributes to specializations here because
9135     // they may have different constexpr-ness compared to their
9136     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9137     // may end up with different effective targets. Instead, a
9138     // specialization inherits its target attributes from its template
9139     // in the CheckFunctionTemplateSpecialization() call below.
9140     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9141       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9142 
9143     // If it's a friend (and only if it's a friend), it's possible
9144     // that either the specialized function type or the specialized
9145     // template is dependent, and therefore matching will fail.  In
9146     // this case, don't check the specialization yet.
9147     bool InstantiationDependent = false;
9148     if (isFunctionTemplateSpecialization && isFriend &&
9149         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9150          TemplateSpecializationType::anyDependentTemplateArguments(
9151             TemplateArgs,
9152             InstantiationDependent))) {
9153       assert(HasExplicitTemplateArgs &&
9154              "friend function specialization without template args");
9155       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9156                                                        Previous))
9157         NewFD->setInvalidDecl();
9158     } else if (isFunctionTemplateSpecialization) {
9159       if (CurContext->isDependentContext() && CurContext->isRecord()
9160           && !isFriend) {
9161         isDependentClassScopeExplicitSpecialization = true;
9162       } else if (!NewFD->isInvalidDecl() &&
9163                  CheckFunctionTemplateSpecialization(
9164                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9165                      Previous))
9166         NewFD->setInvalidDecl();
9167 
9168       // C++ [dcl.stc]p1:
9169       //   A storage-class-specifier shall not be specified in an explicit
9170       //   specialization (14.7.3)
9171       FunctionTemplateSpecializationInfo *Info =
9172           NewFD->getTemplateSpecializationInfo();
9173       if (Info && SC != SC_None) {
9174         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9175           Diag(NewFD->getLocation(),
9176                diag::err_explicit_specialization_inconsistent_storage_class)
9177             << SC
9178             << FixItHint::CreateRemoval(
9179                                       D.getDeclSpec().getStorageClassSpecLoc());
9180 
9181         else
9182           Diag(NewFD->getLocation(),
9183                diag::ext_explicit_specialization_storage_class)
9184             << FixItHint::CreateRemoval(
9185                                       D.getDeclSpec().getStorageClassSpecLoc());
9186       }
9187     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9188       if (CheckMemberSpecialization(NewFD, Previous))
9189           NewFD->setInvalidDecl();
9190     }
9191 
9192     // Perform semantic checking on the function declaration.
9193     if (!isDependentClassScopeExplicitSpecialization) {
9194       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9195         CheckMain(NewFD, D.getDeclSpec());
9196 
9197       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9198         CheckMSVCRTEntryPoint(NewFD);
9199 
9200       if (!NewFD->isInvalidDecl())
9201         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9202                                                     isMemberSpecialization));
9203       else if (!Previous.empty())
9204         // Recover gracefully from an invalid redeclaration.
9205         D.setRedeclaration(true);
9206     }
9207 
9208     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9209             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9210            "previous declaration set still overloaded");
9211 
9212     NamedDecl *PrincipalDecl = (FunctionTemplate
9213                                 ? cast<NamedDecl>(FunctionTemplate)
9214                                 : NewFD);
9215 
9216     if (isFriend && NewFD->getPreviousDecl()) {
9217       AccessSpecifier Access = AS_public;
9218       if (!NewFD->isInvalidDecl())
9219         Access = NewFD->getPreviousDecl()->getAccess();
9220 
9221       NewFD->setAccess(Access);
9222       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9223     }
9224 
9225     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9226         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9227       PrincipalDecl->setNonMemberOperator();
9228 
9229     // If we have a function template, check the template parameter
9230     // list. This will check and merge default template arguments.
9231     if (FunctionTemplate) {
9232       FunctionTemplateDecl *PrevTemplate =
9233                                      FunctionTemplate->getPreviousDecl();
9234       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9235                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9236                                     : nullptr,
9237                             D.getDeclSpec().isFriendSpecified()
9238                               ? (D.isFunctionDefinition()
9239                                    ? TPC_FriendFunctionTemplateDefinition
9240                                    : TPC_FriendFunctionTemplate)
9241                               : (D.getCXXScopeSpec().isSet() &&
9242                                  DC && DC->isRecord() &&
9243                                  DC->isDependentContext())
9244                                   ? TPC_ClassTemplateMember
9245                                   : TPC_FunctionTemplate);
9246     }
9247 
9248     if (NewFD->isInvalidDecl()) {
9249       // Ignore all the rest of this.
9250     } else if (!D.isRedeclaration()) {
9251       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9252                                        AddToScope };
9253       // Fake up an access specifier if it's supposed to be a class member.
9254       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9255         NewFD->setAccess(AS_public);
9256 
9257       // Qualified decls generally require a previous declaration.
9258       if (D.getCXXScopeSpec().isSet()) {
9259         // ...with the major exception of templated-scope or
9260         // dependent-scope friend declarations.
9261 
9262         // TODO: we currently also suppress this check in dependent
9263         // contexts because (1) the parameter depth will be off when
9264         // matching friend templates and (2) we might actually be
9265         // selecting a friend based on a dependent factor.  But there
9266         // are situations where these conditions don't apply and we
9267         // can actually do this check immediately.
9268         //
9269         // Unless the scope is dependent, it's always an error if qualified
9270         // redeclaration lookup found nothing at all. Diagnose that now;
9271         // nothing will diagnose that error later.
9272         if (isFriend &&
9273             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9274              (!Previous.empty() && CurContext->isDependentContext()))) {
9275           // ignore these
9276         } else {
9277           // The user tried to provide an out-of-line definition for a
9278           // function that is a member of a class or namespace, but there
9279           // was no such member function declared (C++ [class.mfct]p2,
9280           // C++ [namespace.memdef]p2). For example:
9281           //
9282           // class X {
9283           //   void f() const;
9284           // };
9285           //
9286           // void X::f() { } // ill-formed
9287           //
9288           // Complain about this problem, and attempt to suggest close
9289           // matches (e.g., those that differ only in cv-qualifiers and
9290           // whether the parameter types are references).
9291 
9292           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9293                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9294             AddToScope = ExtraArgs.AddToScope;
9295             return Result;
9296           }
9297         }
9298 
9299         // Unqualified local friend declarations are required to resolve
9300         // to something.
9301       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9302         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9303                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9304           AddToScope = ExtraArgs.AddToScope;
9305           return Result;
9306         }
9307       }
9308     } else if (!D.isFunctionDefinition() &&
9309                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9310                !isFriend && !isFunctionTemplateSpecialization &&
9311                !isMemberSpecialization) {
9312       // An out-of-line member function declaration must also be a
9313       // definition (C++ [class.mfct]p2).
9314       // Note that this is not the case for explicit specializations of
9315       // function templates or member functions of class templates, per
9316       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9317       // extension for compatibility with old SWIG code which likes to
9318       // generate them.
9319       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9320         << D.getCXXScopeSpec().getRange();
9321     }
9322   }
9323 
9324   ProcessPragmaWeak(S, NewFD);
9325   checkAttributesAfterMerging(*this, *NewFD);
9326 
9327   AddKnownFunctionAttributes(NewFD);
9328 
9329   if (NewFD->hasAttr<OverloadableAttr>() &&
9330       !NewFD->getType()->getAs<FunctionProtoType>()) {
9331     Diag(NewFD->getLocation(),
9332          diag::err_attribute_overloadable_no_prototype)
9333       << NewFD;
9334 
9335     // Turn this into a variadic function with no parameters.
9336     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9337     FunctionProtoType::ExtProtoInfo EPI(
9338         Context.getDefaultCallingConvention(true, false));
9339     EPI.Variadic = true;
9340     EPI.ExtInfo = FT->getExtInfo();
9341 
9342     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9343     NewFD->setType(R);
9344   }
9345 
9346   // If there's a #pragma GCC visibility in scope, and this isn't a class
9347   // member, set the visibility of this function.
9348   if (!DC->isRecord() && NewFD->isExternallyVisible())
9349     AddPushedVisibilityAttribute(NewFD);
9350 
9351   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9352   // marking the function.
9353   AddCFAuditedAttribute(NewFD);
9354 
9355   // If this is a function definition, check if we have to apply optnone due to
9356   // a pragma.
9357   if(D.isFunctionDefinition())
9358     AddRangeBasedOptnone(NewFD);
9359 
9360   // If this is the first declaration of an extern C variable, update
9361   // the map of such variables.
9362   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9363       isIncompleteDeclExternC(*this, NewFD))
9364     RegisterLocallyScopedExternCDecl(NewFD, S);
9365 
9366   // Set this FunctionDecl's range up to the right paren.
9367   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9368 
9369   if (D.isRedeclaration() && !Previous.empty()) {
9370     NamedDecl *Prev = Previous.getRepresentativeDecl();
9371     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9372                                    isMemberSpecialization ||
9373                                        isFunctionTemplateSpecialization,
9374                                    D.isFunctionDefinition());
9375   }
9376 
9377   if (getLangOpts().CUDA) {
9378     IdentifierInfo *II = NewFD->getIdentifier();
9379     if (II && II->isStr(getCudaConfigureFuncName()) &&
9380         !NewFD->isInvalidDecl() &&
9381         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9382       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9383         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9384             << getCudaConfigureFuncName();
9385       Context.setcudaConfigureCallDecl(NewFD);
9386     }
9387 
9388     // Variadic functions, other than a *declaration* of printf, are not allowed
9389     // in device-side CUDA code, unless someone passed
9390     // -fcuda-allow-variadic-functions.
9391     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9392         (NewFD->hasAttr<CUDADeviceAttr>() ||
9393          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9394         !(II && II->isStr("printf") && NewFD->isExternC() &&
9395           !D.isFunctionDefinition())) {
9396       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9397     }
9398   }
9399 
9400   MarkUnusedFileScopedDecl(NewFD);
9401 
9402 
9403 
9404   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9405     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9406     if ((getLangOpts().OpenCLVersion >= 120)
9407         && (SC == SC_Static)) {
9408       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9409       D.setInvalidType();
9410     }
9411 
9412     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9413     if (!NewFD->getReturnType()->isVoidType()) {
9414       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9415       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9416           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9417                                 : FixItHint());
9418       D.setInvalidType();
9419     }
9420 
9421     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9422     for (auto Param : NewFD->parameters())
9423       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9424 
9425     if (getLangOpts().OpenCLCPlusPlus) {
9426       if (DC->isRecord()) {
9427         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9428         D.setInvalidType();
9429       }
9430       if (FunctionTemplate) {
9431         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9432         D.setInvalidType();
9433       }
9434     }
9435   }
9436 
9437   if (getLangOpts().CPlusPlus) {
9438     if (FunctionTemplate) {
9439       if (NewFD->isInvalidDecl())
9440         FunctionTemplate->setInvalidDecl();
9441       return FunctionTemplate;
9442     }
9443 
9444     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9445       CompleteMemberSpecialization(NewFD, Previous);
9446   }
9447 
9448   for (const ParmVarDecl *Param : NewFD->parameters()) {
9449     QualType PT = Param->getType();
9450 
9451     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9452     // types.
9453     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9454       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9455         QualType ElemTy = PipeTy->getElementType();
9456           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9457             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9458             D.setInvalidType();
9459           }
9460       }
9461     }
9462   }
9463 
9464   // Here we have an function template explicit specialization at class scope.
9465   // The actual specialization will be postponed to template instatiation
9466   // time via the ClassScopeFunctionSpecializationDecl node.
9467   if (isDependentClassScopeExplicitSpecialization) {
9468     ClassScopeFunctionSpecializationDecl *NewSpec =
9469                          ClassScopeFunctionSpecializationDecl::Create(
9470                                 Context, CurContext, NewFD->getLocation(),
9471                                 cast<CXXMethodDecl>(NewFD),
9472                                 HasExplicitTemplateArgs, TemplateArgs);
9473     CurContext->addDecl(NewSpec);
9474     AddToScope = false;
9475   }
9476 
9477   // Diagnose availability attributes. Availability cannot be used on functions
9478   // that are run during load/unload.
9479   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9480     if (NewFD->hasAttr<ConstructorAttr>()) {
9481       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9482           << 1;
9483       NewFD->dropAttr<AvailabilityAttr>();
9484     }
9485     if (NewFD->hasAttr<DestructorAttr>()) {
9486       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9487           << 2;
9488       NewFD->dropAttr<AvailabilityAttr>();
9489     }
9490   }
9491 
9492   return NewFD;
9493 }
9494 
9495 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9496 /// when __declspec(code_seg) "is applied to a class, all member functions of
9497 /// the class and nested classes -- this includes compiler-generated special
9498 /// member functions -- are put in the specified segment."
9499 /// The actual behavior is a little more complicated. The Microsoft compiler
9500 /// won't check outer classes if there is an active value from #pragma code_seg.
9501 /// The CodeSeg is always applied from the direct parent but only from outer
9502 /// classes when the #pragma code_seg stack is empty. See:
9503 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9504 /// available since MS has removed the page.
9505 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9506   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9507   if (!Method)
9508     return nullptr;
9509   const CXXRecordDecl *Parent = Method->getParent();
9510   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9511     Attr *NewAttr = SAttr->clone(S.getASTContext());
9512     NewAttr->setImplicit(true);
9513     return NewAttr;
9514   }
9515 
9516   // The Microsoft compiler won't check outer classes for the CodeSeg
9517   // when the #pragma code_seg stack is active.
9518   if (S.CodeSegStack.CurrentValue)
9519    return nullptr;
9520 
9521   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9522     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9523       Attr *NewAttr = SAttr->clone(S.getASTContext());
9524       NewAttr->setImplicit(true);
9525       return NewAttr;
9526     }
9527   }
9528   return nullptr;
9529 }
9530 
9531 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9532 /// containing class. Otherwise it will return implicit SectionAttr if the
9533 /// function is a definition and there is an active value on CodeSegStack
9534 /// (from the current #pragma code-seg value).
9535 ///
9536 /// \param FD Function being declared.
9537 /// \param IsDefinition Whether it is a definition or just a declarartion.
9538 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9539 ///          nullptr if no attribute should be added.
9540 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9541                                                        bool IsDefinition) {
9542   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9543     return A;
9544   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9545       CodeSegStack.CurrentValue)
9546     return SectionAttr::CreateImplicit(
9547         getASTContext(), CodeSegStack.CurrentValue->getString(),
9548         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9549         SectionAttr::Declspec_allocate);
9550   return nullptr;
9551 }
9552 
9553 /// Determines if we can perform a correct type check for \p D as a
9554 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9555 /// best-effort check.
9556 ///
9557 /// \param NewD The new declaration.
9558 /// \param OldD The old declaration.
9559 /// \param NewT The portion of the type of the new declaration to check.
9560 /// \param OldT The portion of the type of the old declaration to check.
9561 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9562                                           QualType NewT, QualType OldT) {
9563   if (!NewD->getLexicalDeclContext()->isDependentContext())
9564     return true;
9565 
9566   // For dependently-typed local extern declarations and friends, we can't
9567   // perform a correct type check in general until instantiation:
9568   //
9569   //   int f();
9570   //   template<typename T> void g() { T f(); }
9571   //
9572   // (valid if g() is only instantiated with T = int).
9573   if (NewT->isDependentType() &&
9574       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9575     return false;
9576 
9577   // Similarly, if the previous declaration was a dependent local extern
9578   // declaration, we don't really know its type yet.
9579   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9580     return false;
9581 
9582   return true;
9583 }
9584 
9585 /// Checks if the new declaration declared in dependent context must be
9586 /// put in the same redeclaration chain as the specified declaration.
9587 ///
9588 /// \param D Declaration that is checked.
9589 /// \param PrevDecl Previous declaration found with proper lookup method for the
9590 ///                 same declaration name.
9591 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9592 ///          belongs to.
9593 ///
9594 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9595   if (!D->getLexicalDeclContext()->isDependentContext())
9596     return true;
9597 
9598   // Don't chain dependent friend function definitions until instantiation, to
9599   // permit cases like
9600   //
9601   //   void func();
9602   //   template<typename T> class C1 { friend void func() {} };
9603   //   template<typename T> class C2 { friend void func() {} };
9604   //
9605   // ... which is valid if only one of C1 and C2 is ever instantiated.
9606   //
9607   // FIXME: This need only apply to function definitions. For now, we proxy
9608   // this by checking for a file-scope function. We do not want this to apply
9609   // to friend declarations nominating member functions, because that gets in
9610   // the way of access checks.
9611   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9612     return false;
9613 
9614   auto *VD = dyn_cast<ValueDecl>(D);
9615   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9616   return !VD || !PrevVD ||
9617          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9618                                         PrevVD->getType());
9619 }
9620 
9621 /// Check the target attribute of the function for MultiVersion
9622 /// validity.
9623 ///
9624 /// Returns true if there was an error, false otherwise.
9625 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9626   const auto *TA = FD->getAttr<TargetAttr>();
9627   assert(TA && "MultiVersion Candidate requires a target attribute");
9628   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9629   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9630   enum ErrType { Feature = 0, Architecture = 1 };
9631 
9632   if (!ParseInfo.Architecture.empty() &&
9633       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9634     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9635         << Architecture << ParseInfo.Architecture;
9636     return true;
9637   }
9638 
9639   for (const auto &Feat : ParseInfo.Features) {
9640     auto BareFeat = StringRef{Feat}.substr(1);
9641     if (Feat[0] == '-') {
9642       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9643           << Feature << ("no-" + BareFeat).str();
9644       return true;
9645     }
9646 
9647     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9648         !TargetInfo.isValidFeatureName(BareFeat)) {
9649       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9650           << Feature << BareFeat;
9651       return true;
9652     }
9653   }
9654   return false;
9655 }
9656 
9657 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9658                                          MultiVersionKind MVType) {
9659   for (const Attr *A : FD->attrs()) {
9660     switch (A->getKind()) {
9661     case attr::CPUDispatch:
9662     case attr::CPUSpecific:
9663       if (MVType != MultiVersionKind::CPUDispatch &&
9664           MVType != MultiVersionKind::CPUSpecific)
9665         return true;
9666       break;
9667     case attr::Target:
9668       if (MVType != MultiVersionKind::Target)
9669         return true;
9670       break;
9671     default:
9672       return true;
9673     }
9674   }
9675   return false;
9676 }
9677 
9678 bool Sema::areMultiversionVariantFunctionsCompatible(
9679     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9680     const PartialDiagnostic &NoProtoDiagID,
9681     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9682     const PartialDiagnosticAt &NoSupportDiagIDAt,
9683     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9684     bool ConstexprSupported) {
9685   enum DoesntSupport {
9686     FuncTemplates = 0,
9687     VirtFuncs = 1,
9688     DeducedReturn = 2,
9689     Constructors = 3,
9690     Destructors = 4,
9691     DeletedFuncs = 5,
9692     DefaultedFuncs = 6,
9693     ConstexprFuncs = 7,
9694     ConstevalFuncs = 8,
9695   };
9696   enum Different {
9697     CallingConv = 0,
9698     ReturnType = 1,
9699     ConstexprSpec = 2,
9700     InlineSpec = 3,
9701     StorageClass = 4,
9702     Linkage = 5,
9703   };
9704 
9705   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9706     Diag(OldFD->getLocation(), NoProtoDiagID);
9707     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9708     return true;
9709   }
9710 
9711   if (!NewFD->getType()->getAs<FunctionProtoType>())
9712     return Diag(NewFD->getLocation(), NoProtoDiagID);
9713 
9714   if (!TemplatesSupported &&
9715       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9716     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9717            << FuncTemplates;
9718 
9719   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9720     if (NewCXXFD->isVirtual())
9721       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9722              << VirtFuncs;
9723 
9724     if (isa<CXXConstructorDecl>(NewCXXFD))
9725       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9726              << Constructors;
9727 
9728     if (isa<CXXDestructorDecl>(NewCXXFD))
9729       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9730              << Destructors;
9731   }
9732 
9733   if (NewFD->isDeleted())
9734     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9735            << DeletedFuncs;
9736 
9737   if (NewFD->isDefaulted())
9738     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9739            << DefaultedFuncs;
9740 
9741   if (!ConstexprSupported && NewFD->isConstexpr())
9742     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9743            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9744 
9745   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9746   const auto *NewType = cast<FunctionType>(NewQType);
9747   QualType NewReturnType = NewType->getReturnType();
9748 
9749   if (NewReturnType->isUndeducedType())
9750     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9751            << DeducedReturn;
9752 
9753   // Ensure the return type is identical.
9754   if (OldFD) {
9755     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9756     const auto *OldType = cast<FunctionType>(OldQType);
9757     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9758     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9759 
9760     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9761       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9762 
9763     QualType OldReturnType = OldType->getReturnType();
9764 
9765     if (OldReturnType != NewReturnType)
9766       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9767 
9768     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9769       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9770 
9771     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9772       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9773 
9774     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9775       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9776 
9777     if (OldFD->isExternC() != NewFD->isExternC())
9778       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9779 
9780     if (CheckEquivalentExceptionSpec(
9781             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9782             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9783       return true;
9784   }
9785   return false;
9786 }
9787 
9788 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9789                                              const FunctionDecl *NewFD,
9790                                              bool CausesMV,
9791                                              MultiVersionKind MVType) {
9792   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9793     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9794     if (OldFD)
9795       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9796     return true;
9797   }
9798 
9799   bool IsCPUSpecificCPUDispatchMVType =
9800       MVType == MultiVersionKind::CPUDispatch ||
9801       MVType == MultiVersionKind::CPUSpecific;
9802 
9803   // For now, disallow all other attributes.  These should be opt-in, but
9804   // an analysis of all of them is a future FIXME.
9805   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9806     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9807         << IsCPUSpecificCPUDispatchMVType;
9808     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9809     return true;
9810   }
9811 
9812   if (HasNonMultiVersionAttributes(NewFD, MVType))
9813     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9814            << IsCPUSpecificCPUDispatchMVType;
9815 
9816   // Only allow transition to MultiVersion if it hasn't been used.
9817   if (OldFD && CausesMV && OldFD->isUsed(false))
9818     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9819 
9820   return S.areMultiversionVariantFunctionsCompatible(
9821       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9822       PartialDiagnosticAt(NewFD->getLocation(),
9823                           S.PDiag(diag::note_multiversioning_caused_here)),
9824       PartialDiagnosticAt(NewFD->getLocation(),
9825                           S.PDiag(diag::err_multiversion_doesnt_support)
9826                               << IsCPUSpecificCPUDispatchMVType),
9827       PartialDiagnosticAt(NewFD->getLocation(),
9828                           S.PDiag(diag::err_multiversion_diff)),
9829       /*TemplatesSupported=*/false,
9830       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType);
9831 }
9832 
9833 /// Check the validity of a multiversion function declaration that is the
9834 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9835 ///
9836 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9837 ///
9838 /// Returns true if there was an error, false otherwise.
9839 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9840                                            MultiVersionKind MVType,
9841                                            const TargetAttr *TA) {
9842   assert(MVType != MultiVersionKind::None &&
9843          "Function lacks multiversion attribute");
9844 
9845   // Target only causes MV if it is default, otherwise this is a normal
9846   // function.
9847   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9848     return false;
9849 
9850   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9851     FD->setInvalidDecl();
9852     return true;
9853   }
9854 
9855   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9856     FD->setInvalidDecl();
9857     return true;
9858   }
9859 
9860   FD->setIsMultiVersion();
9861   return false;
9862 }
9863 
9864 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9865   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9866     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9867       return true;
9868   }
9869 
9870   return false;
9871 }
9872 
9873 static bool CheckTargetCausesMultiVersioning(
9874     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9875     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9876     LookupResult &Previous) {
9877   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9878   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9879   // Sort order doesn't matter, it just needs to be consistent.
9880   llvm::sort(NewParsed.Features);
9881 
9882   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9883   // to change, this is a simple redeclaration.
9884   if (!NewTA->isDefaultVersion() &&
9885       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9886     return false;
9887 
9888   // Otherwise, this decl causes MultiVersioning.
9889   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9890     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9891     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9892     NewFD->setInvalidDecl();
9893     return true;
9894   }
9895 
9896   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9897                                        MultiVersionKind::Target)) {
9898     NewFD->setInvalidDecl();
9899     return true;
9900   }
9901 
9902   if (CheckMultiVersionValue(S, NewFD)) {
9903     NewFD->setInvalidDecl();
9904     return true;
9905   }
9906 
9907   // If this is 'default', permit the forward declaration.
9908   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9909     Redeclaration = true;
9910     OldDecl = OldFD;
9911     OldFD->setIsMultiVersion();
9912     NewFD->setIsMultiVersion();
9913     return false;
9914   }
9915 
9916   if (CheckMultiVersionValue(S, OldFD)) {
9917     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9918     NewFD->setInvalidDecl();
9919     return true;
9920   }
9921 
9922   TargetAttr::ParsedTargetAttr OldParsed =
9923       OldTA->parse(std::less<std::string>());
9924 
9925   if (OldParsed == NewParsed) {
9926     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9927     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9928     NewFD->setInvalidDecl();
9929     return true;
9930   }
9931 
9932   for (const auto *FD : OldFD->redecls()) {
9933     const auto *CurTA = FD->getAttr<TargetAttr>();
9934     // We allow forward declarations before ANY multiversioning attributes, but
9935     // nothing after the fact.
9936     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9937         (!CurTA || CurTA->isInherited())) {
9938       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9939           << 0;
9940       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9941       NewFD->setInvalidDecl();
9942       return true;
9943     }
9944   }
9945 
9946   OldFD->setIsMultiVersion();
9947   NewFD->setIsMultiVersion();
9948   Redeclaration = false;
9949   MergeTypeWithPrevious = false;
9950   OldDecl = nullptr;
9951   Previous.clear();
9952   return false;
9953 }
9954 
9955 /// Check the validity of a new function declaration being added to an existing
9956 /// multiversioned declaration collection.
9957 static bool CheckMultiVersionAdditionalDecl(
9958     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9959     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9960     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9961     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9962     LookupResult &Previous) {
9963 
9964   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9965   // Disallow mixing of multiversioning types.
9966   if ((OldMVType == MultiVersionKind::Target &&
9967        NewMVType != MultiVersionKind::Target) ||
9968       (NewMVType == MultiVersionKind::Target &&
9969        OldMVType != MultiVersionKind::Target)) {
9970     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9971     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9972     NewFD->setInvalidDecl();
9973     return true;
9974   }
9975 
9976   TargetAttr::ParsedTargetAttr NewParsed;
9977   if (NewTA) {
9978     NewParsed = NewTA->parse();
9979     llvm::sort(NewParsed.Features);
9980   }
9981 
9982   bool UseMemberUsingDeclRules =
9983       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9984 
9985   // Next, check ALL non-overloads to see if this is a redeclaration of a
9986   // previous member of the MultiVersion set.
9987   for (NamedDecl *ND : Previous) {
9988     FunctionDecl *CurFD = ND->getAsFunction();
9989     if (!CurFD)
9990       continue;
9991     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9992       continue;
9993 
9994     if (NewMVType == MultiVersionKind::Target) {
9995       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9996       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9997         NewFD->setIsMultiVersion();
9998         Redeclaration = true;
9999         OldDecl = ND;
10000         return false;
10001       }
10002 
10003       TargetAttr::ParsedTargetAttr CurParsed =
10004           CurTA->parse(std::less<std::string>());
10005       if (CurParsed == NewParsed) {
10006         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10007         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10008         NewFD->setInvalidDecl();
10009         return true;
10010       }
10011     } else {
10012       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10013       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10014       // Handle CPUDispatch/CPUSpecific versions.
10015       // Only 1 CPUDispatch function is allowed, this will make it go through
10016       // the redeclaration errors.
10017       if (NewMVType == MultiVersionKind::CPUDispatch &&
10018           CurFD->hasAttr<CPUDispatchAttr>()) {
10019         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10020             std::equal(
10021                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10022                 NewCPUDisp->cpus_begin(),
10023                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10024                   return Cur->getName() == New->getName();
10025                 })) {
10026           NewFD->setIsMultiVersion();
10027           Redeclaration = true;
10028           OldDecl = ND;
10029           return false;
10030         }
10031 
10032         // If the declarations don't match, this is an error condition.
10033         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10034         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10035         NewFD->setInvalidDecl();
10036         return true;
10037       }
10038       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10039 
10040         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10041             std::equal(
10042                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10043                 NewCPUSpec->cpus_begin(),
10044                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10045                   return Cur->getName() == New->getName();
10046                 })) {
10047           NewFD->setIsMultiVersion();
10048           Redeclaration = true;
10049           OldDecl = ND;
10050           return false;
10051         }
10052 
10053         // Only 1 version of CPUSpecific is allowed for each CPU.
10054         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10055           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10056             if (CurII == NewII) {
10057               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10058                   << NewII;
10059               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10060               NewFD->setInvalidDecl();
10061               return true;
10062             }
10063           }
10064         }
10065       }
10066       // If the two decls aren't the same MVType, there is no possible error
10067       // condition.
10068     }
10069   }
10070 
10071   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10072   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10073   // handled in the attribute adding step.
10074   if (NewMVType == MultiVersionKind::Target &&
10075       CheckMultiVersionValue(S, NewFD)) {
10076     NewFD->setInvalidDecl();
10077     return true;
10078   }
10079 
10080   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10081                                        !OldFD->isMultiVersion(), NewMVType)) {
10082     NewFD->setInvalidDecl();
10083     return true;
10084   }
10085 
10086   // Permit forward declarations in the case where these two are compatible.
10087   if (!OldFD->isMultiVersion()) {
10088     OldFD->setIsMultiVersion();
10089     NewFD->setIsMultiVersion();
10090     Redeclaration = true;
10091     OldDecl = OldFD;
10092     return false;
10093   }
10094 
10095   NewFD->setIsMultiVersion();
10096   Redeclaration = false;
10097   MergeTypeWithPrevious = false;
10098   OldDecl = nullptr;
10099   Previous.clear();
10100   return false;
10101 }
10102 
10103 
10104 /// Check the validity of a mulitversion function declaration.
10105 /// Also sets the multiversion'ness' of the function itself.
10106 ///
10107 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10108 ///
10109 /// Returns true if there was an error, false otherwise.
10110 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10111                                       bool &Redeclaration, NamedDecl *&OldDecl,
10112                                       bool &MergeTypeWithPrevious,
10113                                       LookupResult &Previous) {
10114   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10115   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10116   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10117 
10118   // Mixing Multiversioning types is prohibited.
10119   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10120       (NewCPUDisp && NewCPUSpec)) {
10121     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10122     NewFD->setInvalidDecl();
10123     return true;
10124   }
10125 
10126   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10127 
10128   // Main isn't allowed to become a multiversion function, however it IS
10129   // permitted to have 'main' be marked with the 'target' optimization hint.
10130   if (NewFD->isMain()) {
10131     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10132         MVType == MultiVersionKind::CPUDispatch ||
10133         MVType == MultiVersionKind::CPUSpecific) {
10134       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10135       NewFD->setInvalidDecl();
10136       return true;
10137     }
10138     return false;
10139   }
10140 
10141   if (!OldDecl || !OldDecl->getAsFunction() ||
10142       OldDecl->getDeclContext()->getRedeclContext() !=
10143           NewFD->getDeclContext()->getRedeclContext()) {
10144     // If there's no previous declaration, AND this isn't attempting to cause
10145     // multiversioning, this isn't an error condition.
10146     if (MVType == MultiVersionKind::None)
10147       return false;
10148     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10149   }
10150 
10151   FunctionDecl *OldFD = OldDecl->getAsFunction();
10152 
10153   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10154     return false;
10155 
10156   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10157     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10158         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10159     NewFD->setInvalidDecl();
10160     return true;
10161   }
10162 
10163   // Handle the target potentially causes multiversioning case.
10164   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10165     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10166                                             Redeclaration, OldDecl,
10167                                             MergeTypeWithPrevious, Previous);
10168 
10169   // At this point, we have a multiversion function decl (in OldFD) AND an
10170   // appropriate attribute in the current function decl.  Resolve that these are
10171   // still compatible with previous declarations.
10172   return CheckMultiVersionAdditionalDecl(
10173       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10174       OldDecl, MergeTypeWithPrevious, Previous);
10175 }
10176 
10177 /// Perform semantic checking of a new function declaration.
10178 ///
10179 /// Performs semantic analysis of the new function declaration
10180 /// NewFD. This routine performs all semantic checking that does not
10181 /// require the actual declarator involved in the declaration, and is
10182 /// used both for the declaration of functions as they are parsed
10183 /// (called via ActOnDeclarator) and for the declaration of functions
10184 /// that have been instantiated via C++ template instantiation (called
10185 /// via InstantiateDecl).
10186 ///
10187 /// \param IsMemberSpecialization whether this new function declaration is
10188 /// a member specialization (that replaces any definition provided by the
10189 /// previous declaration).
10190 ///
10191 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10192 ///
10193 /// \returns true if the function declaration is a redeclaration.
10194 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10195                                     LookupResult &Previous,
10196                                     bool IsMemberSpecialization) {
10197   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10198          "Variably modified return types are not handled here");
10199 
10200   // Determine whether the type of this function should be merged with
10201   // a previous visible declaration. This never happens for functions in C++,
10202   // and always happens in C if the previous declaration was visible.
10203   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10204                                !Previous.isShadowed();
10205 
10206   bool Redeclaration = false;
10207   NamedDecl *OldDecl = nullptr;
10208   bool MayNeedOverloadableChecks = false;
10209 
10210   // Merge or overload the declaration with an existing declaration of
10211   // the same name, if appropriate.
10212   if (!Previous.empty()) {
10213     // Determine whether NewFD is an overload of PrevDecl or
10214     // a declaration that requires merging. If it's an overload,
10215     // there's no more work to do here; we'll just add the new
10216     // function to the scope.
10217     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10218       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10219       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10220         Redeclaration = true;
10221         OldDecl = Candidate;
10222       }
10223     } else {
10224       MayNeedOverloadableChecks = true;
10225       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10226                             /*NewIsUsingDecl*/ false)) {
10227       case Ovl_Match:
10228         Redeclaration = true;
10229         break;
10230 
10231       case Ovl_NonFunction:
10232         Redeclaration = true;
10233         break;
10234 
10235       case Ovl_Overload:
10236         Redeclaration = false;
10237         break;
10238       }
10239     }
10240   }
10241 
10242   // Check for a previous extern "C" declaration with this name.
10243   if (!Redeclaration &&
10244       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10245     if (!Previous.empty()) {
10246       // This is an extern "C" declaration with the same name as a previous
10247       // declaration, and thus redeclares that entity...
10248       Redeclaration = true;
10249       OldDecl = Previous.getFoundDecl();
10250       MergeTypeWithPrevious = false;
10251 
10252       // ... except in the presence of __attribute__((overloadable)).
10253       if (OldDecl->hasAttr<OverloadableAttr>() ||
10254           NewFD->hasAttr<OverloadableAttr>()) {
10255         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10256           MayNeedOverloadableChecks = true;
10257           Redeclaration = false;
10258           OldDecl = nullptr;
10259         }
10260       }
10261     }
10262   }
10263 
10264   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10265                                 MergeTypeWithPrevious, Previous))
10266     return Redeclaration;
10267 
10268   // C++11 [dcl.constexpr]p8:
10269   //   A constexpr specifier for a non-static member function that is not
10270   //   a constructor declares that member function to be const.
10271   //
10272   // This needs to be delayed until we know whether this is an out-of-line
10273   // definition of a static member function.
10274   //
10275   // This rule is not present in C++1y, so we produce a backwards
10276   // compatibility warning whenever it happens in C++11.
10277   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10278   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10279       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10280       !MD->getMethodQualifiers().hasConst()) {
10281     CXXMethodDecl *OldMD = nullptr;
10282     if (OldDecl)
10283       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10284     if (!OldMD || !OldMD->isStatic()) {
10285       const FunctionProtoType *FPT =
10286         MD->getType()->castAs<FunctionProtoType>();
10287       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10288       EPI.TypeQuals.addConst();
10289       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10290                                           FPT->getParamTypes(), EPI));
10291 
10292       // Warn that we did this, if we're not performing template instantiation.
10293       // In that case, we'll have warned already when the template was defined.
10294       if (!inTemplateInstantiation()) {
10295         SourceLocation AddConstLoc;
10296         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10297                 .IgnoreParens().getAs<FunctionTypeLoc>())
10298           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10299 
10300         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10301           << FixItHint::CreateInsertion(AddConstLoc, " const");
10302       }
10303     }
10304   }
10305 
10306   if (Redeclaration) {
10307     // NewFD and OldDecl represent declarations that need to be
10308     // merged.
10309     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10310       NewFD->setInvalidDecl();
10311       return Redeclaration;
10312     }
10313 
10314     Previous.clear();
10315     Previous.addDecl(OldDecl);
10316 
10317     if (FunctionTemplateDecl *OldTemplateDecl =
10318             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10319       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10320       FunctionTemplateDecl *NewTemplateDecl
10321         = NewFD->getDescribedFunctionTemplate();
10322       assert(NewTemplateDecl && "Template/non-template mismatch");
10323 
10324       // The call to MergeFunctionDecl above may have created some state in
10325       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10326       // can add it as a redeclaration.
10327       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10328 
10329       NewFD->setPreviousDeclaration(OldFD);
10330       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10331       if (NewFD->isCXXClassMember()) {
10332         NewFD->setAccess(OldTemplateDecl->getAccess());
10333         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10334       }
10335 
10336       // If this is an explicit specialization of a member that is a function
10337       // template, mark it as a member specialization.
10338       if (IsMemberSpecialization &&
10339           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10340         NewTemplateDecl->setMemberSpecialization();
10341         assert(OldTemplateDecl->isMemberSpecialization());
10342         // Explicit specializations of a member template do not inherit deleted
10343         // status from the parent member template that they are specializing.
10344         if (OldFD->isDeleted()) {
10345           // FIXME: This assert will not hold in the presence of modules.
10346           assert(OldFD->getCanonicalDecl() == OldFD);
10347           // FIXME: We need an update record for this AST mutation.
10348           OldFD->setDeletedAsWritten(false);
10349         }
10350       }
10351 
10352     } else {
10353       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10354         auto *OldFD = cast<FunctionDecl>(OldDecl);
10355         // This needs to happen first so that 'inline' propagates.
10356         NewFD->setPreviousDeclaration(OldFD);
10357         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10358         if (NewFD->isCXXClassMember())
10359           NewFD->setAccess(OldFD->getAccess());
10360       }
10361     }
10362   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10363              !NewFD->getAttr<OverloadableAttr>()) {
10364     assert((Previous.empty() ||
10365             llvm::any_of(Previous,
10366                          [](const NamedDecl *ND) {
10367                            return ND->hasAttr<OverloadableAttr>();
10368                          })) &&
10369            "Non-redecls shouldn't happen without overloadable present");
10370 
10371     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10372       const auto *FD = dyn_cast<FunctionDecl>(ND);
10373       return FD && !FD->hasAttr<OverloadableAttr>();
10374     });
10375 
10376     if (OtherUnmarkedIter != Previous.end()) {
10377       Diag(NewFD->getLocation(),
10378            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10379       Diag((*OtherUnmarkedIter)->getLocation(),
10380            diag::note_attribute_overloadable_prev_overload)
10381           << false;
10382 
10383       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10384     }
10385   }
10386 
10387   // Semantic checking for this function declaration (in isolation).
10388 
10389   if (getLangOpts().CPlusPlus) {
10390     // C++-specific checks.
10391     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10392       CheckConstructor(Constructor);
10393     } else if (CXXDestructorDecl *Destructor =
10394                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10395       CXXRecordDecl *Record = Destructor->getParent();
10396       QualType ClassType = Context.getTypeDeclType(Record);
10397 
10398       // FIXME: Shouldn't we be able to perform this check even when the class
10399       // type is dependent? Both gcc and edg can handle that.
10400       if (!ClassType->isDependentType()) {
10401         DeclarationName Name
10402           = Context.DeclarationNames.getCXXDestructorName(
10403                                         Context.getCanonicalType(ClassType));
10404         if (NewFD->getDeclName() != Name) {
10405           Diag(NewFD->getLocation(), diag::err_destructor_name);
10406           NewFD->setInvalidDecl();
10407           return Redeclaration;
10408         }
10409       }
10410     } else if (CXXConversionDecl *Conversion
10411                = dyn_cast<CXXConversionDecl>(NewFD)) {
10412       ActOnConversionDeclarator(Conversion);
10413     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10414       if (auto *TD = Guide->getDescribedFunctionTemplate())
10415         CheckDeductionGuideTemplate(TD);
10416 
10417       // A deduction guide is not on the list of entities that can be
10418       // explicitly specialized.
10419       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10420         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10421             << /*explicit specialization*/ 1;
10422     }
10423 
10424     // Find any virtual functions that this function overrides.
10425     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10426       if (!Method->isFunctionTemplateSpecialization() &&
10427           !Method->getDescribedFunctionTemplate() &&
10428           Method->isCanonicalDecl()) {
10429         if (AddOverriddenMethods(Method->getParent(), Method)) {
10430           // If the function was marked as "static", we have a problem.
10431           if (NewFD->getStorageClass() == SC_Static) {
10432             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10433           }
10434         }
10435       }
10436 
10437       if (Method->isStatic())
10438         checkThisInStaticMemberFunctionType(Method);
10439     }
10440 
10441     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10442     if (NewFD->isOverloadedOperator() &&
10443         CheckOverloadedOperatorDeclaration(NewFD)) {
10444       NewFD->setInvalidDecl();
10445       return Redeclaration;
10446     }
10447 
10448     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10449     if (NewFD->getLiteralIdentifier() &&
10450         CheckLiteralOperatorDeclaration(NewFD)) {
10451       NewFD->setInvalidDecl();
10452       return Redeclaration;
10453     }
10454 
10455     // In C++, check default arguments now that we have merged decls. Unless
10456     // the lexical context is the class, because in this case this is done
10457     // during delayed parsing anyway.
10458     if (!CurContext->isRecord())
10459       CheckCXXDefaultArguments(NewFD);
10460 
10461     // If this function declares a builtin function, check the type of this
10462     // declaration against the expected type for the builtin.
10463     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10464       ASTContext::GetBuiltinTypeError Error;
10465       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10466       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10467       // If the type of the builtin differs only in its exception
10468       // specification, that's OK.
10469       // FIXME: If the types do differ in this way, it would be better to
10470       // retain the 'noexcept' form of the type.
10471       if (!T.isNull() &&
10472           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10473                                                             NewFD->getType()))
10474         // The type of this function differs from the type of the builtin,
10475         // so forget about the builtin entirely.
10476         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10477     }
10478 
10479     // If this function is declared as being extern "C", then check to see if
10480     // the function returns a UDT (class, struct, or union type) that is not C
10481     // compatible, and if it does, warn the user.
10482     // But, issue any diagnostic on the first declaration only.
10483     if (Previous.empty() && NewFD->isExternC()) {
10484       QualType R = NewFD->getReturnType();
10485       if (R->isIncompleteType() && !R->isVoidType())
10486         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10487             << NewFD << R;
10488       else if (!R.isPODType(Context) && !R->isVoidType() &&
10489                !R->isObjCObjectPointerType())
10490         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10491     }
10492 
10493     // C++1z [dcl.fct]p6:
10494     //   [...] whether the function has a non-throwing exception-specification
10495     //   [is] part of the function type
10496     //
10497     // This results in an ABI break between C++14 and C++17 for functions whose
10498     // declared type includes an exception-specification in a parameter or
10499     // return type. (Exception specifications on the function itself are OK in
10500     // most cases, and exception specifications are not permitted in most other
10501     // contexts where they could make it into a mangling.)
10502     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10503       auto HasNoexcept = [&](QualType T) -> bool {
10504         // Strip off declarator chunks that could be between us and a function
10505         // type. We don't need to look far, exception specifications are very
10506         // restricted prior to C++17.
10507         if (auto *RT = T->getAs<ReferenceType>())
10508           T = RT->getPointeeType();
10509         else if (T->isAnyPointerType())
10510           T = T->getPointeeType();
10511         else if (auto *MPT = T->getAs<MemberPointerType>())
10512           T = MPT->getPointeeType();
10513         if (auto *FPT = T->getAs<FunctionProtoType>())
10514           if (FPT->isNothrow())
10515             return true;
10516         return false;
10517       };
10518 
10519       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10520       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10521       for (QualType T : FPT->param_types())
10522         AnyNoexcept |= HasNoexcept(T);
10523       if (AnyNoexcept)
10524         Diag(NewFD->getLocation(),
10525              diag::warn_cxx17_compat_exception_spec_in_signature)
10526             << NewFD;
10527     }
10528 
10529     if (!Redeclaration && LangOpts.CUDA)
10530       checkCUDATargetOverload(NewFD, Previous);
10531   }
10532   return Redeclaration;
10533 }
10534 
10535 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10536   // C++11 [basic.start.main]p3:
10537   //   A program that [...] declares main to be inline, static or
10538   //   constexpr is ill-formed.
10539   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10540   //   appear in a declaration of main.
10541   // static main is not an error under C99, but we should warn about it.
10542   // We accept _Noreturn main as an extension.
10543   if (FD->getStorageClass() == SC_Static)
10544     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10545          ? diag::err_static_main : diag::warn_static_main)
10546       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10547   if (FD->isInlineSpecified())
10548     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10549       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10550   if (DS.isNoreturnSpecified()) {
10551     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10552     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10553     Diag(NoreturnLoc, diag::ext_noreturn_main);
10554     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10555       << FixItHint::CreateRemoval(NoreturnRange);
10556   }
10557   if (FD->isConstexpr()) {
10558     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10559         << FD->isConsteval()
10560         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10561     FD->setConstexprKind(CSK_unspecified);
10562   }
10563 
10564   if (getLangOpts().OpenCL) {
10565     Diag(FD->getLocation(), diag::err_opencl_no_main)
10566         << FD->hasAttr<OpenCLKernelAttr>();
10567     FD->setInvalidDecl();
10568     return;
10569   }
10570 
10571   QualType T = FD->getType();
10572   assert(T->isFunctionType() && "function decl is not of function type");
10573   const FunctionType* FT = T->castAs<FunctionType>();
10574 
10575   // Set default calling convention for main()
10576   if (FT->getCallConv() != CC_C) {
10577     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10578     FD->setType(QualType(FT, 0));
10579     T = Context.getCanonicalType(FD->getType());
10580   }
10581 
10582   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10583     // In C with GNU extensions we allow main() to have non-integer return
10584     // type, but we should warn about the extension, and we disable the
10585     // implicit-return-zero rule.
10586 
10587     // GCC in C mode accepts qualified 'int'.
10588     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10589       FD->setHasImplicitReturnZero(true);
10590     else {
10591       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10592       SourceRange RTRange = FD->getReturnTypeSourceRange();
10593       if (RTRange.isValid())
10594         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10595             << FixItHint::CreateReplacement(RTRange, "int");
10596     }
10597   } else {
10598     // In C and C++, main magically returns 0 if you fall off the end;
10599     // set the flag which tells us that.
10600     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10601 
10602     // All the standards say that main() should return 'int'.
10603     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10604       FD->setHasImplicitReturnZero(true);
10605     else {
10606       // Otherwise, this is just a flat-out error.
10607       SourceRange RTRange = FD->getReturnTypeSourceRange();
10608       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10609           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10610                                 : FixItHint());
10611       FD->setInvalidDecl(true);
10612     }
10613   }
10614 
10615   // Treat protoless main() as nullary.
10616   if (isa<FunctionNoProtoType>(FT)) return;
10617 
10618   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10619   unsigned nparams = FTP->getNumParams();
10620   assert(FD->getNumParams() == nparams);
10621 
10622   bool HasExtraParameters = (nparams > 3);
10623 
10624   if (FTP->isVariadic()) {
10625     Diag(FD->getLocation(), diag::ext_variadic_main);
10626     // FIXME: if we had information about the location of the ellipsis, we
10627     // could add a FixIt hint to remove it as a parameter.
10628   }
10629 
10630   // Darwin passes an undocumented fourth argument of type char**.  If
10631   // other platforms start sprouting these, the logic below will start
10632   // getting shifty.
10633   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10634     HasExtraParameters = false;
10635 
10636   if (HasExtraParameters) {
10637     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10638     FD->setInvalidDecl(true);
10639     nparams = 3;
10640   }
10641 
10642   // FIXME: a lot of the following diagnostics would be improved
10643   // if we had some location information about types.
10644 
10645   QualType CharPP =
10646     Context.getPointerType(Context.getPointerType(Context.CharTy));
10647   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10648 
10649   for (unsigned i = 0; i < nparams; ++i) {
10650     QualType AT = FTP->getParamType(i);
10651 
10652     bool mismatch = true;
10653 
10654     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10655       mismatch = false;
10656     else if (Expected[i] == CharPP) {
10657       // As an extension, the following forms are okay:
10658       //   char const **
10659       //   char const * const *
10660       //   char * const *
10661 
10662       QualifierCollector qs;
10663       const PointerType* PT;
10664       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10665           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10666           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10667                               Context.CharTy)) {
10668         qs.removeConst();
10669         mismatch = !qs.empty();
10670       }
10671     }
10672 
10673     if (mismatch) {
10674       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10675       // TODO: suggest replacing given type with expected type
10676       FD->setInvalidDecl(true);
10677     }
10678   }
10679 
10680   if (nparams == 1 && !FD->isInvalidDecl()) {
10681     Diag(FD->getLocation(), diag::warn_main_one_arg);
10682   }
10683 
10684   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10685     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10686     FD->setInvalidDecl();
10687   }
10688 }
10689 
10690 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10691   QualType T = FD->getType();
10692   assert(T->isFunctionType() && "function decl is not of function type");
10693   const FunctionType *FT = T->castAs<FunctionType>();
10694 
10695   // Set an implicit return of 'zero' if the function can return some integral,
10696   // enumeration, pointer or nullptr type.
10697   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10698       FT->getReturnType()->isAnyPointerType() ||
10699       FT->getReturnType()->isNullPtrType())
10700     // DllMain is exempt because a return value of zero means it failed.
10701     if (FD->getName() != "DllMain")
10702       FD->setHasImplicitReturnZero(true);
10703 
10704   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10705     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10706     FD->setInvalidDecl();
10707   }
10708 }
10709 
10710 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10711   // FIXME: Need strict checking.  In C89, we need to check for
10712   // any assignment, increment, decrement, function-calls, or
10713   // commas outside of a sizeof.  In C99, it's the same list,
10714   // except that the aforementioned are allowed in unevaluated
10715   // expressions.  Everything else falls under the
10716   // "may accept other forms of constant expressions" exception.
10717   // (We never end up here for C++, so the constant expression
10718   // rules there don't matter.)
10719   const Expr *Culprit;
10720   if (Init->isConstantInitializer(Context, false, &Culprit))
10721     return false;
10722   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10723     << Culprit->getSourceRange();
10724   return true;
10725 }
10726 
10727 namespace {
10728   // Visits an initialization expression to see if OrigDecl is evaluated in
10729   // its own initialization and throws a warning if it does.
10730   class SelfReferenceChecker
10731       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10732     Sema &S;
10733     Decl *OrigDecl;
10734     bool isRecordType;
10735     bool isPODType;
10736     bool isReferenceType;
10737 
10738     bool isInitList;
10739     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10740 
10741   public:
10742     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10743 
10744     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10745                                                     S(S), OrigDecl(OrigDecl) {
10746       isPODType = false;
10747       isRecordType = false;
10748       isReferenceType = false;
10749       isInitList = false;
10750       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10751         isPODType = VD->getType().isPODType(S.Context);
10752         isRecordType = VD->getType()->isRecordType();
10753         isReferenceType = VD->getType()->isReferenceType();
10754       }
10755     }
10756 
10757     // For most expressions, just call the visitor.  For initializer lists,
10758     // track the index of the field being initialized since fields are
10759     // initialized in order allowing use of previously initialized fields.
10760     void CheckExpr(Expr *E) {
10761       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10762       if (!InitList) {
10763         Visit(E);
10764         return;
10765       }
10766 
10767       // Track and increment the index here.
10768       isInitList = true;
10769       InitFieldIndex.push_back(0);
10770       for (auto Child : InitList->children()) {
10771         CheckExpr(cast<Expr>(Child));
10772         ++InitFieldIndex.back();
10773       }
10774       InitFieldIndex.pop_back();
10775     }
10776 
10777     // Returns true if MemberExpr is checked and no further checking is needed.
10778     // Returns false if additional checking is required.
10779     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10780       llvm::SmallVector<FieldDecl*, 4> Fields;
10781       Expr *Base = E;
10782       bool ReferenceField = false;
10783 
10784       // Get the field members used.
10785       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10786         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10787         if (!FD)
10788           return false;
10789         Fields.push_back(FD);
10790         if (FD->getType()->isReferenceType())
10791           ReferenceField = true;
10792         Base = ME->getBase()->IgnoreParenImpCasts();
10793       }
10794 
10795       // Keep checking only if the base Decl is the same.
10796       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10797       if (!DRE || DRE->getDecl() != OrigDecl)
10798         return false;
10799 
10800       // A reference field can be bound to an unininitialized field.
10801       if (CheckReference && !ReferenceField)
10802         return true;
10803 
10804       // Convert FieldDecls to their index number.
10805       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10806       for (const FieldDecl *I : llvm::reverse(Fields))
10807         UsedFieldIndex.push_back(I->getFieldIndex());
10808 
10809       // See if a warning is needed by checking the first difference in index
10810       // numbers.  If field being used has index less than the field being
10811       // initialized, then the use is safe.
10812       for (auto UsedIter = UsedFieldIndex.begin(),
10813                 UsedEnd = UsedFieldIndex.end(),
10814                 OrigIter = InitFieldIndex.begin(),
10815                 OrigEnd = InitFieldIndex.end();
10816            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10817         if (*UsedIter < *OrigIter)
10818           return true;
10819         if (*UsedIter > *OrigIter)
10820           break;
10821       }
10822 
10823       // TODO: Add a different warning which will print the field names.
10824       HandleDeclRefExpr(DRE);
10825       return true;
10826     }
10827 
10828     // For most expressions, the cast is directly above the DeclRefExpr.
10829     // For conditional operators, the cast can be outside the conditional
10830     // operator if both expressions are DeclRefExpr's.
10831     void HandleValue(Expr *E) {
10832       E = E->IgnoreParens();
10833       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10834         HandleDeclRefExpr(DRE);
10835         return;
10836       }
10837 
10838       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10839         Visit(CO->getCond());
10840         HandleValue(CO->getTrueExpr());
10841         HandleValue(CO->getFalseExpr());
10842         return;
10843       }
10844 
10845       if (BinaryConditionalOperator *BCO =
10846               dyn_cast<BinaryConditionalOperator>(E)) {
10847         Visit(BCO->getCond());
10848         HandleValue(BCO->getFalseExpr());
10849         return;
10850       }
10851 
10852       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10853         HandleValue(OVE->getSourceExpr());
10854         return;
10855       }
10856 
10857       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10858         if (BO->getOpcode() == BO_Comma) {
10859           Visit(BO->getLHS());
10860           HandleValue(BO->getRHS());
10861           return;
10862         }
10863       }
10864 
10865       if (isa<MemberExpr>(E)) {
10866         if (isInitList) {
10867           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10868                                       false /*CheckReference*/))
10869             return;
10870         }
10871 
10872         Expr *Base = E->IgnoreParenImpCasts();
10873         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10874           // Check for static member variables and don't warn on them.
10875           if (!isa<FieldDecl>(ME->getMemberDecl()))
10876             return;
10877           Base = ME->getBase()->IgnoreParenImpCasts();
10878         }
10879         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10880           HandleDeclRefExpr(DRE);
10881         return;
10882       }
10883 
10884       Visit(E);
10885     }
10886 
10887     // Reference types not handled in HandleValue are handled here since all
10888     // uses of references are bad, not just r-value uses.
10889     void VisitDeclRefExpr(DeclRefExpr *E) {
10890       if (isReferenceType)
10891         HandleDeclRefExpr(E);
10892     }
10893 
10894     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10895       if (E->getCastKind() == CK_LValueToRValue) {
10896         HandleValue(E->getSubExpr());
10897         return;
10898       }
10899 
10900       Inherited::VisitImplicitCastExpr(E);
10901     }
10902 
10903     void VisitMemberExpr(MemberExpr *E) {
10904       if (isInitList) {
10905         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10906           return;
10907       }
10908 
10909       // Don't warn on arrays since they can be treated as pointers.
10910       if (E->getType()->canDecayToPointerType()) return;
10911 
10912       // Warn when a non-static method call is followed by non-static member
10913       // field accesses, which is followed by a DeclRefExpr.
10914       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10915       bool Warn = (MD && !MD->isStatic());
10916       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10917       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10918         if (!isa<FieldDecl>(ME->getMemberDecl()))
10919           Warn = false;
10920         Base = ME->getBase()->IgnoreParenImpCasts();
10921       }
10922 
10923       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10924         if (Warn)
10925           HandleDeclRefExpr(DRE);
10926         return;
10927       }
10928 
10929       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10930       // Visit that expression.
10931       Visit(Base);
10932     }
10933 
10934     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10935       Expr *Callee = E->getCallee();
10936 
10937       if (isa<UnresolvedLookupExpr>(Callee))
10938         return Inherited::VisitCXXOperatorCallExpr(E);
10939 
10940       Visit(Callee);
10941       for (auto Arg: E->arguments())
10942         HandleValue(Arg->IgnoreParenImpCasts());
10943     }
10944 
10945     void VisitUnaryOperator(UnaryOperator *E) {
10946       // For POD record types, addresses of its own members are well-defined.
10947       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10948           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10949         if (!isPODType)
10950           HandleValue(E->getSubExpr());
10951         return;
10952       }
10953 
10954       if (E->isIncrementDecrementOp()) {
10955         HandleValue(E->getSubExpr());
10956         return;
10957       }
10958 
10959       Inherited::VisitUnaryOperator(E);
10960     }
10961 
10962     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10963 
10964     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10965       if (E->getConstructor()->isCopyConstructor()) {
10966         Expr *ArgExpr = E->getArg(0);
10967         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10968           if (ILE->getNumInits() == 1)
10969             ArgExpr = ILE->getInit(0);
10970         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10971           if (ICE->getCastKind() == CK_NoOp)
10972             ArgExpr = ICE->getSubExpr();
10973         HandleValue(ArgExpr);
10974         return;
10975       }
10976       Inherited::VisitCXXConstructExpr(E);
10977     }
10978 
10979     void VisitCallExpr(CallExpr *E) {
10980       // Treat std::move as a use.
10981       if (E->isCallToStdMove()) {
10982         HandleValue(E->getArg(0));
10983         return;
10984       }
10985 
10986       Inherited::VisitCallExpr(E);
10987     }
10988 
10989     void VisitBinaryOperator(BinaryOperator *E) {
10990       if (E->isCompoundAssignmentOp()) {
10991         HandleValue(E->getLHS());
10992         Visit(E->getRHS());
10993         return;
10994       }
10995 
10996       Inherited::VisitBinaryOperator(E);
10997     }
10998 
10999     // A custom visitor for BinaryConditionalOperator is needed because the
11000     // regular visitor would check the condition and true expression separately
11001     // but both point to the same place giving duplicate diagnostics.
11002     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11003       Visit(E->getCond());
11004       Visit(E->getFalseExpr());
11005     }
11006 
11007     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11008       Decl* ReferenceDecl = DRE->getDecl();
11009       if (OrigDecl != ReferenceDecl) return;
11010       unsigned diag;
11011       if (isReferenceType) {
11012         diag = diag::warn_uninit_self_reference_in_reference_init;
11013       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11014         diag = diag::warn_static_self_reference_in_init;
11015       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11016                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11017                  DRE->getDecl()->getType()->isRecordType()) {
11018         diag = diag::warn_uninit_self_reference_in_init;
11019       } else {
11020         // Local variables will be handled by the CFG analysis.
11021         return;
11022       }
11023 
11024       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11025                             S.PDiag(diag)
11026                                 << DRE->getDecl() << OrigDecl->getLocation()
11027                                 << DRE->getSourceRange());
11028     }
11029   };
11030 
11031   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11032   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11033                                  bool DirectInit) {
11034     // Parameters arguments are occassionially constructed with itself,
11035     // for instance, in recursive functions.  Skip them.
11036     if (isa<ParmVarDecl>(OrigDecl))
11037       return;
11038 
11039     E = E->IgnoreParens();
11040 
11041     // Skip checking T a = a where T is not a record or reference type.
11042     // Doing so is a way to silence uninitialized warnings.
11043     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11044       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11045         if (ICE->getCastKind() == CK_LValueToRValue)
11046           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11047             if (DRE->getDecl() == OrigDecl)
11048               return;
11049 
11050     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11051   }
11052 } // end anonymous namespace
11053 
11054 namespace {
11055   // Simple wrapper to add the name of a variable or (if no variable is
11056   // available) a DeclarationName into a diagnostic.
11057   struct VarDeclOrName {
11058     VarDecl *VDecl;
11059     DeclarationName Name;
11060 
11061     friend const Sema::SemaDiagnosticBuilder &
11062     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11063       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11064     }
11065   };
11066 } // end anonymous namespace
11067 
11068 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11069                                             DeclarationName Name, QualType Type,
11070                                             TypeSourceInfo *TSI,
11071                                             SourceRange Range, bool DirectInit,
11072                                             Expr *Init) {
11073   bool IsInitCapture = !VDecl;
11074   assert((!VDecl || !VDecl->isInitCapture()) &&
11075          "init captures are expected to be deduced prior to initialization");
11076 
11077   VarDeclOrName VN{VDecl, Name};
11078 
11079   DeducedType *Deduced = Type->getContainedDeducedType();
11080   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11081 
11082   // C++11 [dcl.spec.auto]p3
11083   if (!Init) {
11084     assert(VDecl && "no init for init capture deduction?");
11085 
11086     // Except for class argument deduction, and then for an initializing
11087     // declaration only, i.e. no static at class scope or extern.
11088     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11089         VDecl->hasExternalStorage() ||
11090         VDecl->isStaticDataMember()) {
11091       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11092         << VDecl->getDeclName() << Type;
11093       return QualType();
11094     }
11095   }
11096 
11097   ArrayRef<Expr*> DeduceInits;
11098   if (Init)
11099     DeduceInits = Init;
11100 
11101   if (DirectInit) {
11102     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11103       DeduceInits = PL->exprs();
11104   }
11105 
11106   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11107     assert(VDecl && "non-auto type for init capture deduction?");
11108     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11109     InitializationKind Kind = InitializationKind::CreateForInit(
11110         VDecl->getLocation(), DirectInit, Init);
11111     // FIXME: Initialization should not be taking a mutable list of inits.
11112     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11113     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11114                                                        InitsCopy);
11115   }
11116 
11117   if (DirectInit) {
11118     if (auto *IL = dyn_cast<InitListExpr>(Init))
11119       DeduceInits = IL->inits();
11120   }
11121 
11122   // Deduction only works if we have exactly one source expression.
11123   if (DeduceInits.empty()) {
11124     // It isn't possible to write this directly, but it is possible to
11125     // end up in this situation with "auto x(some_pack...);"
11126     Diag(Init->getBeginLoc(), IsInitCapture
11127                                   ? diag::err_init_capture_no_expression
11128                                   : diag::err_auto_var_init_no_expression)
11129         << VN << Type << Range;
11130     return QualType();
11131   }
11132 
11133   if (DeduceInits.size() > 1) {
11134     Diag(DeduceInits[1]->getBeginLoc(),
11135          IsInitCapture ? diag::err_init_capture_multiple_expressions
11136                        : diag::err_auto_var_init_multiple_expressions)
11137         << VN << Type << Range;
11138     return QualType();
11139   }
11140 
11141   Expr *DeduceInit = DeduceInits[0];
11142   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11143     Diag(Init->getBeginLoc(), IsInitCapture
11144                                   ? diag::err_init_capture_paren_braces
11145                                   : diag::err_auto_var_init_paren_braces)
11146         << isa<InitListExpr>(Init) << VN << Type << Range;
11147     return QualType();
11148   }
11149 
11150   // Expressions default to 'id' when we're in a debugger.
11151   bool DefaultedAnyToId = false;
11152   if (getLangOpts().DebuggerCastResultToId &&
11153       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11154     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11155     if (Result.isInvalid()) {
11156       return QualType();
11157     }
11158     Init = Result.get();
11159     DefaultedAnyToId = true;
11160   }
11161 
11162   // C++ [dcl.decomp]p1:
11163   //   If the assignment-expression [...] has array type A and no ref-qualifier
11164   //   is present, e has type cv A
11165   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11166       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11167       DeduceInit->getType()->isConstantArrayType())
11168     return Context.getQualifiedType(DeduceInit->getType(),
11169                                     Type.getQualifiers());
11170 
11171   QualType DeducedType;
11172   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11173     if (!IsInitCapture)
11174       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11175     else if (isa<InitListExpr>(Init))
11176       Diag(Range.getBegin(),
11177            diag::err_init_capture_deduction_failure_from_init_list)
11178           << VN
11179           << (DeduceInit->getType().isNull() ? TSI->getType()
11180                                              : DeduceInit->getType())
11181           << DeduceInit->getSourceRange();
11182     else
11183       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11184           << VN << TSI->getType()
11185           << (DeduceInit->getType().isNull() ? TSI->getType()
11186                                              : DeduceInit->getType())
11187           << DeduceInit->getSourceRange();
11188   }
11189 
11190   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11191   // 'id' instead of a specific object type prevents most of our usual
11192   // checks.
11193   // We only want to warn outside of template instantiations, though:
11194   // inside a template, the 'id' could have come from a parameter.
11195   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11196       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11197     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11198     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11199   }
11200 
11201   return DeducedType;
11202 }
11203 
11204 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11205                                          Expr *Init) {
11206   QualType DeducedType = deduceVarTypeFromInitializer(
11207       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11208       VDecl->getSourceRange(), DirectInit, Init);
11209   if (DeducedType.isNull()) {
11210     VDecl->setInvalidDecl();
11211     return true;
11212   }
11213 
11214   VDecl->setType(DeducedType);
11215   assert(VDecl->isLinkageValid());
11216 
11217   // In ARC, infer lifetime.
11218   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11219     VDecl->setInvalidDecl();
11220 
11221   // If this is a redeclaration, check that the type we just deduced matches
11222   // the previously declared type.
11223   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11224     // We never need to merge the type, because we cannot form an incomplete
11225     // array of auto, nor deduce such a type.
11226     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11227   }
11228 
11229   // Check the deduced type is valid for a variable declaration.
11230   CheckVariableDeclarationType(VDecl);
11231   return VDecl->isInvalidDecl();
11232 }
11233 
11234 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11235                                               SourceLocation Loc) {
11236   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11237     Init = CE->getSubExpr();
11238 
11239   QualType InitType = Init->getType();
11240   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11241           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11242          "shouldn't be called if type doesn't have a non-trivial C struct");
11243   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11244     for (auto I : ILE->inits()) {
11245       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11246           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11247         continue;
11248       SourceLocation SL = I->getExprLoc();
11249       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11250     }
11251     return;
11252   }
11253 
11254   if (isa<ImplicitValueInitExpr>(Init)) {
11255     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11256       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11257                             NTCUK_Init);
11258   } else {
11259     // Assume all other explicit initializers involving copying some existing
11260     // object.
11261     // TODO: ignore any explicit initializers where we can guarantee
11262     // copy-elision.
11263     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11264       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11265   }
11266 }
11267 
11268 namespace {
11269 
11270 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11271   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11272   // in the source code or implicitly by the compiler if it is in a union
11273   // defined in a system header and has non-trivial ObjC ownership
11274   // qualifications. We don't want those fields to participate in determining
11275   // whether the containing union is non-trivial.
11276   return FD->hasAttr<UnavailableAttr>();
11277 }
11278 
11279 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11280     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11281                                     void> {
11282   using Super =
11283       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11284                                     void>;
11285 
11286   DiagNonTrivalCUnionDefaultInitializeVisitor(
11287       QualType OrigTy, SourceLocation OrigLoc,
11288       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11289       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11290 
11291   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11292                      const FieldDecl *FD, bool InNonTrivialUnion) {
11293     if (const auto *AT = S.Context.getAsArrayType(QT))
11294       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11295                                      InNonTrivialUnion);
11296     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11297   }
11298 
11299   void visitARCStrong(QualType QT, const FieldDecl *FD,
11300                       bool InNonTrivialUnion) {
11301     if (InNonTrivialUnion)
11302       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11303           << 1 << 0 << QT << FD->getName();
11304   }
11305 
11306   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11307     if (InNonTrivialUnion)
11308       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11309           << 1 << 0 << QT << FD->getName();
11310   }
11311 
11312   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11313     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11314     if (RD->isUnion()) {
11315       if (OrigLoc.isValid()) {
11316         bool IsUnion = false;
11317         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11318           IsUnion = OrigRD->isUnion();
11319         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11320             << 0 << OrigTy << IsUnion << UseContext;
11321         // Reset OrigLoc so that this diagnostic is emitted only once.
11322         OrigLoc = SourceLocation();
11323       }
11324       InNonTrivialUnion = true;
11325     }
11326 
11327     if (InNonTrivialUnion)
11328       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11329           << 0 << 0 << QT.getUnqualifiedType() << "";
11330 
11331     for (const FieldDecl *FD : RD->fields())
11332       if (!shouldIgnoreForRecordTriviality(FD))
11333         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11334   }
11335 
11336   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11337 
11338   // The non-trivial C union type or the struct/union type that contains a
11339   // non-trivial C union.
11340   QualType OrigTy;
11341   SourceLocation OrigLoc;
11342   Sema::NonTrivialCUnionContext UseContext;
11343   Sema &S;
11344 };
11345 
11346 struct DiagNonTrivalCUnionDestructedTypeVisitor
11347     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11348   using Super =
11349       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11350 
11351   DiagNonTrivalCUnionDestructedTypeVisitor(
11352       QualType OrigTy, SourceLocation OrigLoc,
11353       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11354       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11355 
11356   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11357                      const FieldDecl *FD, bool InNonTrivialUnion) {
11358     if (const auto *AT = S.Context.getAsArrayType(QT))
11359       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11360                                      InNonTrivialUnion);
11361     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11362   }
11363 
11364   void visitARCStrong(QualType QT, const FieldDecl *FD,
11365                       bool InNonTrivialUnion) {
11366     if (InNonTrivialUnion)
11367       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11368           << 1 << 1 << QT << FD->getName();
11369   }
11370 
11371   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11372     if (InNonTrivialUnion)
11373       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11374           << 1 << 1 << QT << FD->getName();
11375   }
11376 
11377   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11378     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11379     if (RD->isUnion()) {
11380       if (OrigLoc.isValid()) {
11381         bool IsUnion = false;
11382         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11383           IsUnion = OrigRD->isUnion();
11384         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11385             << 1 << OrigTy << IsUnion << UseContext;
11386         // Reset OrigLoc so that this diagnostic is emitted only once.
11387         OrigLoc = SourceLocation();
11388       }
11389       InNonTrivialUnion = true;
11390     }
11391 
11392     if (InNonTrivialUnion)
11393       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11394           << 0 << 1 << QT.getUnqualifiedType() << "";
11395 
11396     for (const FieldDecl *FD : RD->fields())
11397       if (!shouldIgnoreForRecordTriviality(FD))
11398         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11399   }
11400 
11401   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11402   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11403                           bool InNonTrivialUnion) {}
11404 
11405   // The non-trivial C union type or the struct/union type that contains a
11406   // non-trivial C union.
11407   QualType OrigTy;
11408   SourceLocation OrigLoc;
11409   Sema::NonTrivialCUnionContext UseContext;
11410   Sema &S;
11411 };
11412 
11413 struct DiagNonTrivalCUnionCopyVisitor
11414     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11415   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11416 
11417   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11418                                  Sema::NonTrivialCUnionContext UseContext,
11419                                  Sema &S)
11420       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11421 
11422   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11423                      const FieldDecl *FD, bool InNonTrivialUnion) {
11424     if (const auto *AT = S.Context.getAsArrayType(QT))
11425       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11426                                      InNonTrivialUnion);
11427     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11428   }
11429 
11430   void visitARCStrong(QualType QT, const FieldDecl *FD,
11431                       bool InNonTrivialUnion) {
11432     if (InNonTrivialUnion)
11433       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11434           << 1 << 2 << QT << FD->getName();
11435   }
11436 
11437   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11438     if (InNonTrivialUnion)
11439       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11440           << 1 << 2 << QT << FD->getName();
11441   }
11442 
11443   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11444     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11445     if (RD->isUnion()) {
11446       if (OrigLoc.isValid()) {
11447         bool IsUnion = false;
11448         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11449           IsUnion = OrigRD->isUnion();
11450         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11451             << 2 << OrigTy << IsUnion << UseContext;
11452         // Reset OrigLoc so that this diagnostic is emitted only once.
11453         OrigLoc = SourceLocation();
11454       }
11455       InNonTrivialUnion = true;
11456     }
11457 
11458     if (InNonTrivialUnion)
11459       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11460           << 0 << 2 << QT.getUnqualifiedType() << "";
11461 
11462     for (const FieldDecl *FD : RD->fields())
11463       if (!shouldIgnoreForRecordTriviality(FD))
11464         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11465   }
11466 
11467   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11468                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11469   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11470   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11471                             bool InNonTrivialUnion) {}
11472 
11473   // The non-trivial C union type or the struct/union type that contains a
11474   // non-trivial C union.
11475   QualType OrigTy;
11476   SourceLocation OrigLoc;
11477   Sema::NonTrivialCUnionContext UseContext;
11478   Sema &S;
11479 };
11480 
11481 } // namespace
11482 
11483 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11484                                  NonTrivialCUnionContext UseContext,
11485                                  unsigned NonTrivialKind) {
11486   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11487           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11488           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11489          "shouldn't be called if type doesn't have a non-trivial C union");
11490 
11491   if ((NonTrivialKind & NTCUK_Init) &&
11492       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11493     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11494         .visit(QT, nullptr, false);
11495   if ((NonTrivialKind & NTCUK_Destruct) &&
11496       QT.hasNonTrivialToPrimitiveDestructCUnion())
11497     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11498         .visit(QT, nullptr, false);
11499   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11500     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11501         .visit(QT, nullptr, false);
11502 }
11503 
11504 /// AddInitializerToDecl - Adds the initializer Init to the
11505 /// declaration dcl. If DirectInit is true, this is C++ direct
11506 /// initialization rather than copy initialization.
11507 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11508   // If there is no declaration, there was an error parsing it.  Just ignore
11509   // the initializer.
11510   if (!RealDecl || RealDecl->isInvalidDecl()) {
11511     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11512     return;
11513   }
11514 
11515   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11516     // Pure-specifiers are handled in ActOnPureSpecifier.
11517     Diag(Method->getLocation(), diag::err_member_function_initialization)
11518       << Method->getDeclName() << Init->getSourceRange();
11519     Method->setInvalidDecl();
11520     return;
11521   }
11522 
11523   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11524   if (!VDecl) {
11525     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11526     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11527     RealDecl->setInvalidDecl();
11528     return;
11529   }
11530 
11531   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11532   if (VDecl->getType()->isUndeducedType()) {
11533     // Attempt typo correction early so that the type of the init expression can
11534     // be deduced based on the chosen correction if the original init contains a
11535     // TypoExpr.
11536     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11537     if (!Res.isUsable()) {
11538       RealDecl->setInvalidDecl();
11539       return;
11540     }
11541     Init = Res.get();
11542 
11543     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11544       return;
11545   }
11546 
11547   // dllimport cannot be used on variable definitions.
11548   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11549     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11550     VDecl->setInvalidDecl();
11551     return;
11552   }
11553 
11554   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11555     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11556     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11557     VDecl->setInvalidDecl();
11558     return;
11559   }
11560 
11561   if (!VDecl->getType()->isDependentType()) {
11562     // A definition must end up with a complete type, which means it must be
11563     // complete with the restriction that an array type might be completed by
11564     // the initializer; note that later code assumes this restriction.
11565     QualType BaseDeclType = VDecl->getType();
11566     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11567       BaseDeclType = Array->getElementType();
11568     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11569                             diag::err_typecheck_decl_incomplete_type)) {
11570       RealDecl->setInvalidDecl();
11571       return;
11572     }
11573 
11574     // The variable can not have an abstract class type.
11575     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11576                                diag::err_abstract_type_in_decl,
11577                                AbstractVariableType))
11578       VDecl->setInvalidDecl();
11579   }
11580 
11581   // If adding the initializer will turn this declaration into a definition,
11582   // and we already have a definition for this variable, diagnose or otherwise
11583   // handle the situation.
11584   VarDecl *Def;
11585   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11586       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11587       !VDecl->isThisDeclarationADemotedDefinition() &&
11588       checkVarDeclRedefinition(Def, VDecl))
11589     return;
11590 
11591   if (getLangOpts().CPlusPlus) {
11592     // C++ [class.static.data]p4
11593     //   If a static data member is of const integral or const
11594     //   enumeration type, its declaration in the class definition can
11595     //   specify a constant-initializer which shall be an integral
11596     //   constant expression (5.19). In that case, the member can appear
11597     //   in integral constant expressions. The member shall still be
11598     //   defined in a namespace scope if it is used in the program and the
11599     //   namespace scope definition shall not contain an initializer.
11600     //
11601     // We already performed a redefinition check above, but for static
11602     // data members we also need to check whether there was an in-class
11603     // declaration with an initializer.
11604     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11605       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11606           << VDecl->getDeclName();
11607       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11608            diag::note_previous_initializer)
11609           << 0;
11610       return;
11611     }
11612 
11613     if (VDecl->hasLocalStorage())
11614       setFunctionHasBranchProtectedScope();
11615 
11616     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11617       VDecl->setInvalidDecl();
11618       return;
11619     }
11620   }
11621 
11622   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11623   // a kernel function cannot be initialized."
11624   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11625     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11626     VDecl->setInvalidDecl();
11627     return;
11628   }
11629 
11630   // Get the decls type and save a reference for later, since
11631   // CheckInitializerTypes may change it.
11632   QualType DclT = VDecl->getType(), SavT = DclT;
11633 
11634   // Expressions default to 'id' when we're in a debugger
11635   // and we are assigning it to a variable of Objective-C pointer type.
11636   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11637       Init->getType() == Context.UnknownAnyTy) {
11638     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11639     if (Result.isInvalid()) {
11640       VDecl->setInvalidDecl();
11641       return;
11642     }
11643     Init = Result.get();
11644   }
11645 
11646   // Perform the initialization.
11647   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11648   if (!VDecl->isInvalidDecl()) {
11649     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11650     InitializationKind Kind = InitializationKind::CreateForInit(
11651         VDecl->getLocation(), DirectInit, Init);
11652 
11653     MultiExprArg Args = Init;
11654     if (CXXDirectInit)
11655       Args = MultiExprArg(CXXDirectInit->getExprs(),
11656                           CXXDirectInit->getNumExprs());
11657 
11658     // Try to correct any TypoExprs in the initialization arguments.
11659     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11660       ExprResult Res = CorrectDelayedTyposInExpr(
11661           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11662             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11663             return Init.Failed() ? ExprError() : E;
11664           });
11665       if (Res.isInvalid()) {
11666         VDecl->setInvalidDecl();
11667       } else if (Res.get() != Args[Idx]) {
11668         Args[Idx] = Res.get();
11669       }
11670     }
11671     if (VDecl->isInvalidDecl())
11672       return;
11673 
11674     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11675                                    /*TopLevelOfInitList=*/false,
11676                                    /*TreatUnavailableAsInvalid=*/false);
11677     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11678     if (Result.isInvalid()) {
11679       VDecl->setInvalidDecl();
11680       return;
11681     }
11682 
11683     Init = Result.getAs<Expr>();
11684   }
11685 
11686   // Check for self-references within variable initializers.
11687   // Variables declared within a function/method body (except for references)
11688   // are handled by a dataflow analysis.
11689   // This is undefined behavior in C++, but valid in C.
11690   if (getLangOpts().CPlusPlus) {
11691     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11692         VDecl->getType()->isReferenceType()) {
11693       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11694     }
11695   }
11696 
11697   // If the type changed, it means we had an incomplete type that was
11698   // completed by the initializer. For example:
11699   //   int ary[] = { 1, 3, 5 };
11700   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11701   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11702     VDecl->setType(DclT);
11703 
11704   if (!VDecl->isInvalidDecl()) {
11705     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11706 
11707     if (VDecl->hasAttr<BlocksAttr>())
11708       checkRetainCycles(VDecl, Init);
11709 
11710     // It is safe to assign a weak reference into a strong variable.
11711     // Although this code can still have problems:
11712     //   id x = self.weakProp;
11713     //   id y = self.weakProp;
11714     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11715     // paths through the function. This should be revisited if
11716     // -Wrepeated-use-of-weak is made flow-sensitive.
11717     if (FunctionScopeInfo *FSI = getCurFunction())
11718       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11719            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11720           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11721                            Init->getBeginLoc()))
11722         FSI->markSafeWeakUse(Init);
11723   }
11724 
11725   // The initialization is usually a full-expression.
11726   //
11727   // FIXME: If this is a braced initialization of an aggregate, it is not
11728   // an expression, and each individual field initializer is a separate
11729   // full-expression. For instance, in:
11730   //
11731   //   struct Temp { ~Temp(); };
11732   //   struct S { S(Temp); };
11733   //   struct T { S a, b; } t = { Temp(), Temp() }
11734   //
11735   // we should destroy the first Temp before constructing the second.
11736   ExprResult Result =
11737       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11738                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11739   if (Result.isInvalid()) {
11740     VDecl->setInvalidDecl();
11741     return;
11742   }
11743   Init = Result.get();
11744 
11745   // Attach the initializer to the decl.
11746   VDecl->setInit(Init);
11747 
11748   if (VDecl->isLocalVarDecl()) {
11749     // Don't check the initializer if the declaration is malformed.
11750     if (VDecl->isInvalidDecl()) {
11751       // do nothing
11752 
11753     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11754     // This is true even in C++ for OpenCL.
11755     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11756       CheckForConstantInitializer(Init, DclT);
11757 
11758     // Otherwise, C++ does not restrict the initializer.
11759     } else if (getLangOpts().CPlusPlus) {
11760       // do nothing
11761 
11762     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11763     // static storage duration shall be constant expressions or string literals.
11764     } else if (VDecl->getStorageClass() == SC_Static) {
11765       CheckForConstantInitializer(Init, DclT);
11766 
11767     // C89 is stricter than C99 for aggregate initializers.
11768     // C89 6.5.7p3: All the expressions [...] in an initializer list
11769     // for an object that has aggregate or union type shall be
11770     // constant expressions.
11771     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11772                isa<InitListExpr>(Init)) {
11773       const Expr *Culprit;
11774       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11775         Diag(Culprit->getExprLoc(),
11776              diag::ext_aggregate_init_not_constant)
11777           << Culprit->getSourceRange();
11778       }
11779     }
11780 
11781     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11782       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11783         if (VDecl->hasLocalStorage())
11784           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11785   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11786              VDecl->getLexicalDeclContext()->isRecord()) {
11787     // This is an in-class initialization for a static data member, e.g.,
11788     //
11789     // struct S {
11790     //   static const int value = 17;
11791     // };
11792 
11793     // C++ [class.mem]p4:
11794     //   A member-declarator can contain a constant-initializer only
11795     //   if it declares a static member (9.4) of const integral or
11796     //   const enumeration type, see 9.4.2.
11797     //
11798     // C++11 [class.static.data]p3:
11799     //   If a non-volatile non-inline const static data member is of integral
11800     //   or enumeration type, its declaration in the class definition can
11801     //   specify a brace-or-equal-initializer in which every initializer-clause
11802     //   that is an assignment-expression is a constant expression. A static
11803     //   data member of literal type can be declared in the class definition
11804     //   with the constexpr specifier; if so, its declaration shall specify a
11805     //   brace-or-equal-initializer in which every initializer-clause that is
11806     //   an assignment-expression is a constant expression.
11807 
11808     // Do nothing on dependent types.
11809     if (DclT->isDependentType()) {
11810 
11811     // Allow any 'static constexpr' members, whether or not they are of literal
11812     // type. We separately check that every constexpr variable is of literal
11813     // type.
11814     } else if (VDecl->isConstexpr()) {
11815 
11816     // Require constness.
11817     } else if (!DclT.isConstQualified()) {
11818       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11819         << Init->getSourceRange();
11820       VDecl->setInvalidDecl();
11821 
11822     // We allow integer constant expressions in all cases.
11823     } else if (DclT->isIntegralOrEnumerationType()) {
11824       // Check whether the expression is a constant expression.
11825       SourceLocation Loc;
11826       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11827         // In C++11, a non-constexpr const static data member with an
11828         // in-class initializer cannot be volatile.
11829         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11830       else if (Init->isValueDependent())
11831         ; // Nothing to check.
11832       else if (Init->isIntegerConstantExpr(Context, &Loc))
11833         ; // Ok, it's an ICE!
11834       else if (Init->getType()->isScopedEnumeralType() &&
11835                Init->isCXX11ConstantExpr(Context))
11836         ; // Ok, it is a scoped-enum constant expression.
11837       else if (Init->isEvaluatable(Context)) {
11838         // If we can constant fold the initializer through heroics, accept it,
11839         // but report this as a use of an extension for -pedantic.
11840         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11841           << Init->getSourceRange();
11842       } else {
11843         // Otherwise, this is some crazy unknown case.  Report the issue at the
11844         // location provided by the isIntegerConstantExpr failed check.
11845         Diag(Loc, diag::err_in_class_initializer_non_constant)
11846           << Init->getSourceRange();
11847         VDecl->setInvalidDecl();
11848       }
11849 
11850     // We allow foldable floating-point constants as an extension.
11851     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11852       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11853       // it anyway and provide a fixit to add the 'constexpr'.
11854       if (getLangOpts().CPlusPlus11) {
11855         Diag(VDecl->getLocation(),
11856              diag::ext_in_class_initializer_float_type_cxx11)
11857             << DclT << Init->getSourceRange();
11858         Diag(VDecl->getBeginLoc(),
11859              diag::note_in_class_initializer_float_type_cxx11)
11860             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11861       } else {
11862         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11863           << DclT << Init->getSourceRange();
11864 
11865         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11866           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11867             << Init->getSourceRange();
11868           VDecl->setInvalidDecl();
11869         }
11870       }
11871 
11872     // Suggest adding 'constexpr' in C++11 for literal types.
11873     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11874       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11875           << DclT << Init->getSourceRange()
11876           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11877       VDecl->setConstexpr(true);
11878 
11879     } else {
11880       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11881         << DclT << Init->getSourceRange();
11882       VDecl->setInvalidDecl();
11883     }
11884   } else if (VDecl->isFileVarDecl()) {
11885     // In C, extern is typically used to avoid tentative definitions when
11886     // declaring variables in headers, but adding an intializer makes it a
11887     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11888     // In C++, extern is often used to give implictly static const variables
11889     // external linkage, so don't warn in that case. If selectany is present,
11890     // this might be header code intended for C and C++ inclusion, so apply the
11891     // C++ rules.
11892     if (VDecl->getStorageClass() == SC_Extern &&
11893         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11894          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11895         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11896         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11897       Diag(VDecl->getLocation(), diag::warn_extern_init);
11898 
11899     // In Microsoft C++ mode, a const variable defined in namespace scope has
11900     // external linkage by default if the variable is declared with
11901     // __declspec(dllexport).
11902     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11903         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11904         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11905       VDecl->setStorageClass(SC_Extern);
11906 
11907     // C99 6.7.8p4. All file scoped initializers need to be constant.
11908     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11909       CheckForConstantInitializer(Init, DclT);
11910   }
11911 
11912   QualType InitType = Init->getType();
11913   if (!InitType.isNull() &&
11914       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11915        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11916     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11917 
11918   // We will represent direct-initialization similarly to copy-initialization:
11919   //    int x(1);  -as-> int x = 1;
11920   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11921   //
11922   // Clients that want to distinguish between the two forms, can check for
11923   // direct initializer using VarDecl::getInitStyle().
11924   // A major benefit is that clients that don't particularly care about which
11925   // exactly form was it (like the CodeGen) can handle both cases without
11926   // special case code.
11927 
11928   // C++ 8.5p11:
11929   // The form of initialization (using parentheses or '=') is generally
11930   // insignificant, but does matter when the entity being initialized has a
11931   // class type.
11932   if (CXXDirectInit) {
11933     assert(DirectInit && "Call-style initializer must be direct init.");
11934     VDecl->setInitStyle(VarDecl::CallInit);
11935   } else if (DirectInit) {
11936     // This must be list-initialization. No other way is direct-initialization.
11937     VDecl->setInitStyle(VarDecl::ListInit);
11938   }
11939 
11940   CheckCompleteVariableDeclaration(VDecl);
11941 }
11942 
11943 /// ActOnInitializerError - Given that there was an error parsing an
11944 /// initializer for the given declaration, try to return to some form
11945 /// of sanity.
11946 void Sema::ActOnInitializerError(Decl *D) {
11947   // Our main concern here is re-establishing invariants like "a
11948   // variable's type is either dependent or complete".
11949   if (!D || D->isInvalidDecl()) return;
11950 
11951   VarDecl *VD = dyn_cast<VarDecl>(D);
11952   if (!VD) return;
11953 
11954   // Bindings are not usable if we can't make sense of the initializer.
11955   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11956     for (auto *BD : DD->bindings())
11957       BD->setInvalidDecl();
11958 
11959   // Auto types are meaningless if we can't make sense of the initializer.
11960   if (ParsingInitForAutoVars.count(D)) {
11961     D->setInvalidDecl();
11962     return;
11963   }
11964 
11965   QualType Ty = VD->getType();
11966   if (Ty->isDependentType()) return;
11967 
11968   // Require a complete type.
11969   if (RequireCompleteType(VD->getLocation(),
11970                           Context.getBaseElementType(Ty),
11971                           diag::err_typecheck_decl_incomplete_type)) {
11972     VD->setInvalidDecl();
11973     return;
11974   }
11975 
11976   // Require a non-abstract type.
11977   if (RequireNonAbstractType(VD->getLocation(), Ty,
11978                              diag::err_abstract_type_in_decl,
11979                              AbstractVariableType)) {
11980     VD->setInvalidDecl();
11981     return;
11982   }
11983 
11984   // Don't bother complaining about constructors or destructors,
11985   // though.
11986 }
11987 
11988 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11989   // If there is no declaration, there was an error parsing it. Just ignore it.
11990   if (!RealDecl)
11991     return;
11992 
11993   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11994     QualType Type = Var->getType();
11995 
11996     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11997     if (isa<DecompositionDecl>(RealDecl)) {
11998       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11999       Var->setInvalidDecl();
12000       return;
12001     }
12002 
12003     if (Type->isUndeducedType() &&
12004         DeduceVariableDeclarationType(Var, false, nullptr))
12005       return;
12006 
12007     // C++11 [class.static.data]p3: A static data member can be declared with
12008     // the constexpr specifier; if so, its declaration shall specify
12009     // a brace-or-equal-initializer.
12010     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12011     // the definition of a variable [...] or the declaration of a static data
12012     // member.
12013     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12014         !Var->isThisDeclarationADemotedDefinition()) {
12015       if (Var->isStaticDataMember()) {
12016         // C++1z removes the relevant rule; the in-class declaration is always
12017         // a definition there.
12018         if (!getLangOpts().CPlusPlus17 &&
12019             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12020           Diag(Var->getLocation(),
12021                diag::err_constexpr_static_mem_var_requires_init)
12022             << Var->getDeclName();
12023           Var->setInvalidDecl();
12024           return;
12025         }
12026       } else {
12027         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12028         Var->setInvalidDecl();
12029         return;
12030       }
12031     }
12032 
12033     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12034     // be initialized.
12035     if (!Var->isInvalidDecl() &&
12036         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12037         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12038       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12039       Var->setInvalidDecl();
12040       return;
12041     }
12042 
12043     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12044     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12045         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12046       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12047                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12048 
12049 
12050     switch (DefKind) {
12051     case VarDecl::Definition:
12052       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12053         break;
12054 
12055       // We have an out-of-line definition of a static data member
12056       // that has an in-class initializer, so we type-check this like
12057       // a declaration.
12058       //
12059       LLVM_FALLTHROUGH;
12060 
12061     case VarDecl::DeclarationOnly:
12062       // It's only a declaration.
12063 
12064       // Block scope. C99 6.7p7: If an identifier for an object is
12065       // declared with no linkage (C99 6.2.2p6), the type for the
12066       // object shall be complete.
12067       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12068           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12069           RequireCompleteType(Var->getLocation(), Type,
12070                               diag::err_typecheck_decl_incomplete_type))
12071         Var->setInvalidDecl();
12072 
12073       // Make sure that the type is not abstract.
12074       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12075           RequireNonAbstractType(Var->getLocation(), Type,
12076                                  diag::err_abstract_type_in_decl,
12077                                  AbstractVariableType))
12078         Var->setInvalidDecl();
12079       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12080           Var->getStorageClass() == SC_PrivateExtern) {
12081         Diag(Var->getLocation(), diag::warn_private_extern);
12082         Diag(Var->getLocation(), diag::note_private_extern);
12083       }
12084 
12085       return;
12086 
12087     case VarDecl::TentativeDefinition:
12088       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12089       // object that has file scope without an initializer, and without a
12090       // storage-class specifier or with the storage-class specifier "static",
12091       // constitutes a tentative definition. Note: A tentative definition with
12092       // external linkage is valid (C99 6.2.2p5).
12093       if (!Var->isInvalidDecl()) {
12094         if (const IncompleteArrayType *ArrayT
12095                                     = Context.getAsIncompleteArrayType(Type)) {
12096           if (RequireCompleteType(Var->getLocation(),
12097                                   ArrayT->getElementType(),
12098                                   diag::err_illegal_decl_array_incomplete_type))
12099             Var->setInvalidDecl();
12100         } else if (Var->getStorageClass() == SC_Static) {
12101           // C99 6.9.2p3: If the declaration of an identifier for an object is
12102           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12103           // declared type shall not be an incomplete type.
12104           // NOTE: code such as the following
12105           //     static struct s;
12106           //     struct s { int a; };
12107           // is accepted by gcc. Hence here we issue a warning instead of
12108           // an error and we do not invalidate the static declaration.
12109           // NOTE: to avoid multiple warnings, only check the first declaration.
12110           if (Var->isFirstDecl())
12111             RequireCompleteType(Var->getLocation(), Type,
12112                                 diag::ext_typecheck_decl_incomplete_type);
12113         }
12114       }
12115 
12116       // Record the tentative definition; we're done.
12117       if (!Var->isInvalidDecl())
12118         TentativeDefinitions.push_back(Var);
12119       return;
12120     }
12121 
12122     // Provide a specific diagnostic for uninitialized variable
12123     // definitions with incomplete array type.
12124     if (Type->isIncompleteArrayType()) {
12125       Diag(Var->getLocation(),
12126            diag::err_typecheck_incomplete_array_needs_initializer);
12127       Var->setInvalidDecl();
12128       return;
12129     }
12130 
12131     // Provide a specific diagnostic for uninitialized variable
12132     // definitions with reference type.
12133     if (Type->isReferenceType()) {
12134       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12135         << Var->getDeclName()
12136         << SourceRange(Var->getLocation(), Var->getLocation());
12137       Var->setInvalidDecl();
12138       return;
12139     }
12140 
12141     // Do not attempt to type-check the default initializer for a
12142     // variable with dependent type.
12143     if (Type->isDependentType())
12144       return;
12145 
12146     if (Var->isInvalidDecl())
12147       return;
12148 
12149     if (!Var->hasAttr<AliasAttr>()) {
12150       if (RequireCompleteType(Var->getLocation(),
12151                               Context.getBaseElementType(Type),
12152                               diag::err_typecheck_decl_incomplete_type)) {
12153         Var->setInvalidDecl();
12154         return;
12155       }
12156     } else {
12157       return;
12158     }
12159 
12160     // The variable can not have an abstract class type.
12161     if (RequireNonAbstractType(Var->getLocation(), Type,
12162                                diag::err_abstract_type_in_decl,
12163                                AbstractVariableType)) {
12164       Var->setInvalidDecl();
12165       return;
12166     }
12167 
12168     // Check for jumps past the implicit initializer.  C++0x
12169     // clarifies that this applies to a "variable with automatic
12170     // storage duration", not a "local variable".
12171     // C++11 [stmt.dcl]p3
12172     //   A program that jumps from a point where a variable with automatic
12173     //   storage duration is not in scope to a point where it is in scope is
12174     //   ill-formed unless the variable has scalar type, class type with a
12175     //   trivial default constructor and a trivial destructor, a cv-qualified
12176     //   version of one of these types, or an array of one of the preceding
12177     //   types and is declared without an initializer.
12178     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12179       if (const RecordType *Record
12180             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12181         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12182         // Mark the function (if we're in one) for further checking even if the
12183         // looser rules of C++11 do not require such checks, so that we can
12184         // diagnose incompatibilities with C++98.
12185         if (!CXXRecord->isPOD())
12186           setFunctionHasBranchProtectedScope();
12187       }
12188     }
12189     // In OpenCL, we can't initialize objects in the __local address space,
12190     // even implicitly, so don't synthesize an implicit initializer.
12191     if (getLangOpts().OpenCL &&
12192         Var->getType().getAddressSpace() == LangAS::opencl_local)
12193       return;
12194     // C++03 [dcl.init]p9:
12195     //   If no initializer is specified for an object, and the
12196     //   object is of (possibly cv-qualified) non-POD class type (or
12197     //   array thereof), the object shall be default-initialized; if
12198     //   the object is of const-qualified type, the underlying class
12199     //   type shall have a user-declared default
12200     //   constructor. Otherwise, if no initializer is specified for
12201     //   a non- static object, the object and its subobjects, if
12202     //   any, have an indeterminate initial value); if the object
12203     //   or any of its subobjects are of const-qualified type, the
12204     //   program is ill-formed.
12205     // C++0x [dcl.init]p11:
12206     //   If no initializer is specified for an object, the object is
12207     //   default-initialized; [...].
12208     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12209     InitializationKind Kind
12210       = InitializationKind::CreateDefault(Var->getLocation());
12211 
12212     InitializationSequence InitSeq(*this, Entity, Kind, None);
12213     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12214     if (Init.isInvalid())
12215       Var->setInvalidDecl();
12216     else if (Init.get()) {
12217       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12218       // This is important for template substitution.
12219       Var->setInitStyle(VarDecl::CallInit);
12220     }
12221 
12222     CheckCompleteVariableDeclaration(Var);
12223   }
12224 }
12225 
12226 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12227   // If there is no declaration, there was an error parsing it. Ignore it.
12228   if (!D)
12229     return;
12230 
12231   VarDecl *VD = dyn_cast<VarDecl>(D);
12232   if (!VD) {
12233     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12234     D->setInvalidDecl();
12235     return;
12236   }
12237 
12238   VD->setCXXForRangeDecl(true);
12239 
12240   // for-range-declaration cannot be given a storage class specifier.
12241   int Error = -1;
12242   switch (VD->getStorageClass()) {
12243   case SC_None:
12244     break;
12245   case SC_Extern:
12246     Error = 0;
12247     break;
12248   case SC_Static:
12249     Error = 1;
12250     break;
12251   case SC_PrivateExtern:
12252     Error = 2;
12253     break;
12254   case SC_Auto:
12255     Error = 3;
12256     break;
12257   case SC_Register:
12258     Error = 4;
12259     break;
12260   }
12261   if (Error != -1) {
12262     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12263       << VD->getDeclName() << Error;
12264     D->setInvalidDecl();
12265   }
12266 }
12267 
12268 StmtResult
12269 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12270                                  IdentifierInfo *Ident,
12271                                  ParsedAttributes &Attrs,
12272                                  SourceLocation AttrEnd) {
12273   // C++1y [stmt.iter]p1:
12274   //   A range-based for statement of the form
12275   //      for ( for-range-identifier : for-range-initializer ) statement
12276   //   is equivalent to
12277   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12278   DeclSpec DS(Attrs.getPool().getFactory());
12279 
12280   const char *PrevSpec;
12281   unsigned DiagID;
12282   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12283                      getPrintingPolicy());
12284 
12285   Declarator D(DS, DeclaratorContext::ForContext);
12286   D.SetIdentifier(Ident, IdentLoc);
12287   D.takeAttributes(Attrs, AttrEnd);
12288 
12289   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12290                 IdentLoc);
12291   Decl *Var = ActOnDeclarator(S, D);
12292   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12293   FinalizeDeclaration(Var);
12294   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12295                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12296 }
12297 
12298 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12299   if (var->isInvalidDecl()) return;
12300 
12301   if (getLangOpts().OpenCL) {
12302     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12303     // initialiser
12304     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12305         !var->hasInit()) {
12306       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12307           << 1 /*Init*/;
12308       var->setInvalidDecl();
12309       return;
12310     }
12311   }
12312 
12313   // In Objective-C, don't allow jumps past the implicit initialization of a
12314   // local retaining variable.
12315   if (getLangOpts().ObjC &&
12316       var->hasLocalStorage()) {
12317     switch (var->getType().getObjCLifetime()) {
12318     case Qualifiers::OCL_None:
12319     case Qualifiers::OCL_ExplicitNone:
12320     case Qualifiers::OCL_Autoreleasing:
12321       break;
12322 
12323     case Qualifiers::OCL_Weak:
12324     case Qualifiers::OCL_Strong:
12325       setFunctionHasBranchProtectedScope();
12326       break;
12327     }
12328   }
12329 
12330   if (var->hasLocalStorage() &&
12331       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12332     setFunctionHasBranchProtectedScope();
12333 
12334   // Warn about externally-visible variables being defined without a
12335   // prior declaration.  We only want to do this for global
12336   // declarations, but we also specifically need to avoid doing it for
12337   // class members because the linkage of an anonymous class can
12338   // change if it's later given a typedef name.
12339   if (var->isThisDeclarationADefinition() &&
12340       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12341       var->isExternallyVisible() && var->hasLinkage() &&
12342       !var->isInline() && !var->getDescribedVarTemplate() &&
12343       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12344       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12345                                   var->getLocation())) {
12346     // Find a previous declaration that's not a definition.
12347     VarDecl *prev = var->getPreviousDecl();
12348     while (prev && prev->isThisDeclarationADefinition())
12349       prev = prev->getPreviousDecl();
12350 
12351     if (!prev) {
12352       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12353       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12354           << /* variable */ 0;
12355     }
12356   }
12357 
12358   // Cache the result of checking for constant initialization.
12359   Optional<bool> CacheHasConstInit;
12360   const Expr *CacheCulprit = nullptr;
12361   auto checkConstInit = [&]() mutable {
12362     if (!CacheHasConstInit)
12363       CacheHasConstInit = var->getInit()->isConstantInitializer(
12364             Context, var->getType()->isReferenceType(), &CacheCulprit);
12365     return *CacheHasConstInit;
12366   };
12367 
12368   if (var->getTLSKind() == VarDecl::TLS_Static) {
12369     if (var->getType().isDestructedType()) {
12370       // GNU C++98 edits for __thread, [basic.start.term]p3:
12371       //   The type of an object with thread storage duration shall not
12372       //   have a non-trivial destructor.
12373       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12374       if (getLangOpts().CPlusPlus11)
12375         Diag(var->getLocation(), diag::note_use_thread_local);
12376     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12377       if (!checkConstInit()) {
12378         // GNU C++98 edits for __thread, [basic.start.init]p4:
12379         //   An object of thread storage duration shall not require dynamic
12380         //   initialization.
12381         // FIXME: Need strict checking here.
12382         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12383           << CacheCulprit->getSourceRange();
12384         if (getLangOpts().CPlusPlus11)
12385           Diag(var->getLocation(), diag::note_use_thread_local);
12386       }
12387     }
12388   }
12389 
12390   // Apply section attributes and pragmas to global variables.
12391   bool GlobalStorage = var->hasGlobalStorage();
12392   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12393       !inTemplateInstantiation()) {
12394     PragmaStack<StringLiteral *> *Stack = nullptr;
12395     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12396     if (var->getType().isConstQualified())
12397       Stack = &ConstSegStack;
12398     else if (!var->getInit()) {
12399       Stack = &BSSSegStack;
12400       SectionFlags |= ASTContext::PSF_Write;
12401     } else {
12402       Stack = &DataSegStack;
12403       SectionFlags |= ASTContext::PSF_Write;
12404     }
12405     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12406       var->addAttr(SectionAttr::CreateImplicit(
12407           Context, Stack->CurrentValue->getString(),
12408           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12409           SectionAttr::Declspec_allocate));
12410     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12411       if (UnifySection(SA->getName(), SectionFlags, var))
12412         var->dropAttr<SectionAttr>();
12413 
12414     // Apply the init_seg attribute if this has an initializer.  If the
12415     // initializer turns out to not be dynamic, we'll end up ignoring this
12416     // attribute.
12417     if (CurInitSeg && var->getInit())
12418       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12419                                                CurInitSegLoc,
12420                                                AttributeCommonInfo::AS_Pragma));
12421   }
12422 
12423   // All the following checks are C++ only.
12424   if (!getLangOpts().CPlusPlus) {
12425       // If this variable must be emitted, add it as an initializer for the
12426       // current module.
12427      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12428        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12429      return;
12430   }
12431 
12432   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12433     CheckCompleteDecompositionDeclaration(DD);
12434 
12435   QualType type = var->getType();
12436   if (type->isDependentType()) return;
12437 
12438   if (var->hasAttr<BlocksAttr>())
12439     getCurFunction()->addByrefBlockVar(var);
12440 
12441   Expr *Init = var->getInit();
12442   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12443   QualType baseType = Context.getBaseElementType(type);
12444 
12445   if (Init && !Init->isValueDependent()) {
12446     if (var->isConstexpr()) {
12447       SmallVector<PartialDiagnosticAt, 8> Notes;
12448       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12449         SourceLocation DiagLoc = var->getLocation();
12450         // If the note doesn't add any useful information other than a source
12451         // location, fold it into the primary diagnostic.
12452         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12453               diag::note_invalid_subexpr_in_const_expr) {
12454           DiagLoc = Notes[0].first;
12455           Notes.clear();
12456         }
12457         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12458           << var << Init->getSourceRange();
12459         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12460           Diag(Notes[I].first, Notes[I].second);
12461       }
12462     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12463       // Check whether the initializer of a const variable of integral or
12464       // enumeration type is an ICE now, since we can't tell whether it was
12465       // initialized by a constant expression if we check later.
12466       var->checkInitIsICE();
12467     }
12468 
12469     // Don't emit further diagnostics about constexpr globals since they
12470     // were just diagnosed.
12471     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12472       // FIXME: Need strict checking in C++03 here.
12473       bool DiagErr = getLangOpts().CPlusPlus11
12474           ? !var->checkInitIsICE() : !checkConstInit();
12475       if (DiagErr) {
12476         auto *Attr = var->getAttr<ConstInitAttr>();
12477         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12478           << Init->getSourceRange();
12479         Diag(Attr->getLocation(),
12480              diag::note_declared_required_constant_init_here)
12481             << Attr->getRange() << Attr->isConstinit();
12482         if (getLangOpts().CPlusPlus11) {
12483           APValue Value;
12484           SmallVector<PartialDiagnosticAt, 8> Notes;
12485           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12486           for (auto &it : Notes)
12487             Diag(it.first, it.second);
12488         } else {
12489           Diag(CacheCulprit->getExprLoc(),
12490                diag::note_invalid_subexpr_in_const_expr)
12491               << CacheCulprit->getSourceRange();
12492         }
12493       }
12494     }
12495     else if (!var->isConstexpr() && IsGlobal &&
12496              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12497                                     var->getLocation())) {
12498       // Warn about globals which don't have a constant initializer.  Don't
12499       // warn about globals with a non-trivial destructor because we already
12500       // warned about them.
12501       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12502       if (!(RD && !RD->hasTrivialDestructor())) {
12503         if (!checkConstInit())
12504           Diag(var->getLocation(), diag::warn_global_constructor)
12505             << Init->getSourceRange();
12506       }
12507     }
12508   }
12509 
12510   // Require the destructor.
12511   if (const RecordType *recordType = baseType->getAs<RecordType>())
12512     FinalizeVarWithDestructor(var, recordType);
12513 
12514   // If this variable must be emitted, add it as an initializer for the current
12515   // module.
12516   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12517     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12518 }
12519 
12520 /// Determines if a variable's alignment is dependent.
12521 static bool hasDependentAlignment(VarDecl *VD) {
12522   if (VD->getType()->isDependentType())
12523     return true;
12524   for (auto *I : VD->specific_attrs<AlignedAttr>())
12525     if (I->isAlignmentDependent())
12526       return true;
12527   return false;
12528 }
12529 
12530 /// Check if VD needs to be dllexport/dllimport due to being in a
12531 /// dllexport/import function.
12532 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12533   assert(VD->isStaticLocal());
12534 
12535   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12536 
12537   // Find outermost function when VD is in lambda function.
12538   while (FD && !getDLLAttr(FD) &&
12539          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12540          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12541     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12542   }
12543 
12544   if (!FD)
12545     return;
12546 
12547   // Static locals inherit dll attributes from their function.
12548   if (Attr *A = getDLLAttr(FD)) {
12549     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12550     NewAttr->setInherited(true);
12551     VD->addAttr(NewAttr);
12552   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12553     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12554     NewAttr->setInherited(true);
12555     VD->addAttr(NewAttr);
12556 
12557     // Export this function to enforce exporting this static variable even
12558     // if it is not used in this compilation unit.
12559     if (!FD->hasAttr<DLLExportAttr>())
12560       FD->addAttr(NewAttr);
12561 
12562   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12563     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12564     NewAttr->setInherited(true);
12565     VD->addAttr(NewAttr);
12566   }
12567 }
12568 
12569 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12570 /// any semantic actions necessary after any initializer has been attached.
12571 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12572   // Note that we are no longer parsing the initializer for this declaration.
12573   ParsingInitForAutoVars.erase(ThisDecl);
12574 
12575   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12576   if (!VD)
12577     return;
12578 
12579   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12580   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12581       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12582     if (PragmaClangBSSSection.Valid)
12583       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12584           Context, PragmaClangBSSSection.SectionName,
12585           PragmaClangBSSSection.PragmaLocation,
12586           AttributeCommonInfo::AS_Pragma));
12587     if (PragmaClangDataSection.Valid)
12588       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12589           Context, PragmaClangDataSection.SectionName,
12590           PragmaClangDataSection.PragmaLocation,
12591           AttributeCommonInfo::AS_Pragma));
12592     if (PragmaClangRodataSection.Valid)
12593       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12594           Context, PragmaClangRodataSection.SectionName,
12595           PragmaClangRodataSection.PragmaLocation,
12596           AttributeCommonInfo::AS_Pragma));
12597   }
12598 
12599   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12600     for (auto *BD : DD->bindings()) {
12601       FinalizeDeclaration(BD);
12602     }
12603   }
12604 
12605   checkAttributesAfterMerging(*this, *VD);
12606 
12607   // Perform TLS alignment check here after attributes attached to the variable
12608   // which may affect the alignment have been processed. Only perform the check
12609   // if the target has a maximum TLS alignment (zero means no constraints).
12610   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12611     // Protect the check so that it's not performed on dependent types and
12612     // dependent alignments (we can't determine the alignment in that case).
12613     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12614         !VD->isInvalidDecl()) {
12615       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12616       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12617         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12618           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12619           << (unsigned)MaxAlignChars.getQuantity();
12620       }
12621     }
12622   }
12623 
12624   if (VD->isStaticLocal()) {
12625     CheckStaticLocalForDllExport(VD);
12626 
12627     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12628       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12629       // function, only __shared__ variables or variables without any device
12630       // memory qualifiers may be declared with static storage class.
12631       // Note: It is unclear how a function-scope non-const static variable
12632       // without device memory qualifier is implemented, therefore only static
12633       // const variable without device memory qualifier is allowed.
12634       [&]() {
12635         if (!getLangOpts().CUDA)
12636           return;
12637         if (VD->hasAttr<CUDASharedAttr>())
12638           return;
12639         if (VD->getType().isConstQualified() &&
12640             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12641           return;
12642         if (CUDADiagIfDeviceCode(VD->getLocation(),
12643                                  diag::err_device_static_local_var)
12644             << CurrentCUDATarget())
12645           VD->setInvalidDecl();
12646       }();
12647     }
12648   }
12649 
12650   // Perform check for initializers of device-side global variables.
12651   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12652   // 7.5). We must also apply the same checks to all __shared__
12653   // variables whether they are local or not. CUDA also allows
12654   // constant initializers for __constant__ and __device__ variables.
12655   if (getLangOpts().CUDA)
12656     checkAllowedCUDAInitializer(VD);
12657 
12658   // Grab the dllimport or dllexport attribute off of the VarDecl.
12659   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12660 
12661   // Imported static data members cannot be defined out-of-line.
12662   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12663     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12664         VD->isThisDeclarationADefinition()) {
12665       // We allow definitions of dllimport class template static data members
12666       // with a warning.
12667       CXXRecordDecl *Context =
12668         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12669       bool IsClassTemplateMember =
12670           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12671           Context->getDescribedClassTemplate();
12672 
12673       Diag(VD->getLocation(),
12674            IsClassTemplateMember
12675                ? diag::warn_attribute_dllimport_static_field_definition
12676                : diag::err_attribute_dllimport_static_field_definition);
12677       Diag(IA->getLocation(), diag::note_attribute);
12678       if (!IsClassTemplateMember)
12679         VD->setInvalidDecl();
12680     }
12681   }
12682 
12683   // dllimport/dllexport variables cannot be thread local, their TLS index
12684   // isn't exported with the variable.
12685   if (DLLAttr && VD->getTLSKind()) {
12686     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12687     if (F && getDLLAttr(F)) {
12688       assert(VD->isStaticLocal());
12689       // But if this is a static local in a dlimport/dllexport function, the
12690       // function will never be inlined, which means the var would never be
12691       // imported, so having it marked import/export is safe.
12692     } else {
12693       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12694                                                                     << DLLAttr;
12695       VD->setInvalidDecl();
12696     }
12697   }
12698 
12699   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12700     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12701       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12702       VD->dropAttr<UsedAttr>();
12703     }
12704   }
12705 
12706   const DeclContext *DC = VD->getDeclContext();
12707   // If there's a #pragma GCC visibility in scope, and this isn't a class
12708   // member, set the visibility of this variable.
12709   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12710     AddPushedVisibilityAttribute(VD);
12711 
12712   // FIXME: Warn on unused var template partial specializations.
12713   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12714     MarkUnusedFileScopedDecl(VD);
12715 
12716   // Now we have parsed the initializer and can update the table of magic
12717   // tag values.
12718   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12719       !VD->getType()->isIntegralOrEnumerationType())
12720     return;
12721 
12722   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12723     const Expr *MagicValueExpr = VD->getInit();
12724     if (!MagicValueExpr) {
12725       continue;
12726     }
12727     llvm::APSInt MagicValueInt;
12728     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12729       Diag(I->getRange().getBegin(),
12730            diag::err_type_tag_for_datatype_not_ice)
12731         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12732       continue;
12733     }
12734     if (MagicValueInt.getActiveBits() > 64) {
12735       Diag(I->getRange().getBegin(),
12736            diag::err_type_tag_for_datatype_too_large)
12737         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12738       continue;
12739     }
12740     uint64_t MagicValue = MagicValueInt.getZExtValue();
12741     RegisterTypeTagForDatatype(I->getArgumentKind(),
12742                                MagicValue,
12743                                I->getMatchingCType(),
12744                                I->getLayoutCompatible(),
12745                                I->getMustBeNull());
12746   }
12747 }
12748 
12749 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12750   auto *VD = dyn_cast<VarDecl>(DD);
12751   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12752 }
12753 
12754 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12755                                                    ArrayRef<Decl *> Group) {
12756   SmallVector<Decl*, 8> Decls;
12757 
12758   if (DS.isTypeSpecOwned())
12759     Decls.push_back(DS.getRepAsDecl());
12760 
12761   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12762   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12763   bool DiagnosedMultipleDecomps = false;
12764   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12765   bool DiagnosedNonDeducedAuto = false;
12766 
12767   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12768     if (Decl *D = Group[i]) {
12769       // For declarators, there are some additional syntactic-ish checks we need
12770       // to perform.
12771       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12772         if (!FirstDeclaratorInGroup)
12773           FirstDeclaratorInGroup = DD;
12774         if (!FirstDecompDeclaratorInGroup)
12775           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12776         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12777             !hasDeducedAuto(DD))
12778           FirstNonDeducedAutoInGroup = DD;
12779 
12780         if (FirstDeclaratorInGroup != DD) {
12781           // A decomposition declaration cannot be combined with any other
12782           // declaration in the same group.
12783           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12784             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12785                  diag::err_decomp_decl_not_alone)
12786                 << FirstDeclaratorInGroup->getSourceRange()
12787                 << DD->getSourceRange();
12788             DiagnosedMultipleDecomps = true;
12789           }
12790 
12791           // A declarator that uses 'auto' in any way other than to declare a
12792           // variable with a deduced type cannot be combined with any other
12793           // declarator in the same group.
12794           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12795             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12796                  diag::err_auto_non_deduced_not_alone)
12797                 << FirstNonDeducedAutoInGroup->getType()
12798                        ->hasAutoForTrailingReturnType()
12799                 << FirstDeclaratorInGroup->getSourceRange()
12800                 << DD->getSourceRange();
12801             DiagnosedNonDeducedAuto = true;
12802           }
12803         }
12804       }
12805 
12806       Decls.push_back(D);
12807     }
12808   }
12809 
12810   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12811     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12812       handleTagNumbering(Tag, S);
12813       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12814           getLangOpts().CPlusPlus)
12815         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12816     }
12817   }
12818 
12819   return BuildDeclaratorGroup(Decls);
12820 }
12821 
12822 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12823 /// group, performing any necessary semantic checking.
12824 Sema::DeclGroupPtrTy
12825 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12826   // C++14 [dcl.spec.auto]p7: (DR1347)
12827   //   If the type that replaces the placeholder type is not the same in each
12828   //   deduction, the program is ill-formed.
12829   if (Group.size() > 1) {
12830     QualType Deduced;
12831     VarDecl *DeducedDecl = nullptr;
12832     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12833       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12834       if (!D || D->isInvalidDecl())
12835         break;
12836       DeducedType *DT = D->getType()->getContainedDeducedType();
12837       if (!DT || DT->getDeducedType().isNull())
12838         continue;
12839       if (Deduced.isNull()) {
12840         Deduced = DT->getDeducedType();
12841         DeducedDecl = D;
12842       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12843         auto *AT = dyn_cast<AutoType>(DT);
12844         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12845              diag::err_auto_different_deductions)
12846           << (AT ? (unsigned)AT->getKeyword() : 3)
12847           << Deduced << DeducedDecl->getDeclName()
12848           << DT->getDeducedType() << D->getDeclName()
12849           << DeducedDecl->getInit()->getSourceRange()
12850           << D->getInit()->getSourceRange();
12851         D->setInvalidDecl();
12852         break;
12853       }
12854     }
12855   }
12856 
12857   ActOnDocumentableDecls(Group);
12858 
12859   return DeclGroupPtrTy::make(
12860       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12861 }
12862 
12863 void Sema::ActOnDocumentableDecl(Decl *D) {
12864   ActOnDocumentableDecls(D);
12865 }
12866 
12867 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12868   // Don't parse the comment if Doxygen diagnostics are ignored.
12869   if (Group.empty() || !Group[0])
12870     return;
12871 
12872   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12873                       Group[0]->getLocation()) &&
12874       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12875                       Group[0]->getLocation()))
12876     return;
12877 
12878   if (Group.size() >= 2) {
12879     // This is a decl group.  Normally it will contain only declarations
12880     // produced from declarator list.  But in case we have any definitions or
12881     // additional declaration references:
12882     //   'typedef struct S {} S;'
12883     //   'typedef struct S *S;'
12884     //   'struct S *pS;'
12885     // FinalizeDeclaratorGroup adds these as separate declarations.
12886     Decl *MaybeTagDecl = Group[0];
12887     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12888       Group = Group.slice(1);
12889     }
12890   }
12891 
12892   // FIMXE: We assume every Decl in the group is in the same file.
12893   // This is false when preprocessor constructs the group from decls in
12894   // different files (e. g. macros or #include).
12895   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
12896 }
12897 
12898 /// Common checks for a parameter-declaration that should apply to both function
12899 /// parameters and non-type template parameters.
12900 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12901   // Check that there are no default arguments inside the type of this
12902   // parameter.
12903   if (getLangOpts().CPlusPlus)
12904     CheckExtraCXXDefaultArguments(D);
12905 
12906   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12907   if (D.getCXXScopeSpec().isSet()) {
12908     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12909       << D.getCXXScopeSpec().getRange();
12910   }
12911 
12912   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12913   // simple identifier except [...irrelevant cases...].
12914   switch (D.getName().getKind()) {
12915   case UnqualifiedIdKind::IK_Identifier:
12916     break;
12917 
12918   case UnqualifiedIdKind::IK_OperatorFunctionId:
12919   case UnqualifiedIdKind::IK_ConversionFunctionId:
12920   case UnqualifiedIdKind::IK_LiteralOperatorId:
12921   case UnqualifiedIdKind::IK_ConstructorName:
12922   case UnqualifiedIdKind::IK_DestructorName:
12923   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12924   case UnqualifiedIdKind::IK_DeductionGuideName:
12925     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12926       << GetNameForDeclarator(D).getName();
12927     break;
12928 
12929   case UnqualifiedIdKind::IK_TemplateId:
12930   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12931     // GetNameForDeclarator would not produce a useful name in this case.
12932     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12933     break;
12934   }
12935 }
12936 
12937 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12938 /// to introduce parameters into function prototype scope.
12939 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12940   const DeclSpec &DS = D.getDeclSpec();
12941 
12942   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12943 
12944   // C++03 [dcl.stc]p2 also permits 'auto'.
12945   StorageClass SC = SC_None;
12946   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12947     SC = SC_Register;
12948     // In C++11, the 'register' storage class specifier is deprecated.
12949     // In C++17, it is not allowed, but we tolerate it as an extension.
12950     if (getLangOpts().CPlusPlus11) {
12951       Diag(DS.getStorageClassSpecLoc(),
12952            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12953                                      : diag::warn_deprecated_register)
12954         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12955     }
12956   } else if (getLangOpts().CPlusPlus &&
12957              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12958     SC = SC_Auto;
12959   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12960     Diag(DS.getStorageClassSpecLoc(),
12961          diag::err_invalid_storage_class_in_func_decl);
12962     D.getMutableDeclSpec().ClearStorageClassSpecs();
12963   }
12964 
12965   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12966     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12967       << DeclSpec::getSpecifierName(TSCS);
12968   if (DS.isInlineSpecified())
12969     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12970         << getLangOpts().CPlusPlus17;
12971   if (DS.hasConstexprSpecifier())
12972     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12973         << 0 << D.getDeclSpec().getConstexprSpecifier();
12974 
12975   DiagnoseFunctionSpecifiers(DS);
12976 
12977   CheckFunctionOrTemplateParamDeclarator(S, D);
12978 
12979   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12980   QualType parmDeclType = TInfo->getType();
12981 
12982   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12983   IdentifierInfo *II = D.getIdentifier();
12984   if (II) {
12985     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12986                    ForVisibleRedeclaration);
12987     LookupName(R, S);
12988     if (R.isSingleResult()) {
12989       NamedDecl *PrevDecl = R.getFoundDecl();
12990       if (PrevDecl->isTemplateParameter()) {
12991         // Maybe we will complain about the shadowed template parameter.
12992         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12993         // Just pretend that we didn't see the previous declaration.
12994         PrevDecl = nullptr;
12995       } else if (S->isDeclScope(PrevDecl)) {
12996         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12997         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12998 
12999         // Recover by removing the name
13000         II = nullptr;
13001         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13002         D.setInvalidType(true);
13003       }
13004     }
13005   }
13006 
13007   // Temporarily put parameter variables in the translation unit, not
13008   // the enclosing context.  This prevents them from accidentally
13009   // looking like class members in C++.
13010   ParmVarDecl *New =
13011       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13012                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13013 
13014   if (D.isInvalidType())
13015     New->setInvalidDecl();
13016 
13017   assert(S->isFunctionPrototypeScope());
13018   assert(S->getFunctionPrototypeDepth() >= 1);
13019   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13020                     S->getNextFunctionPrototypeIndex());
13021 
13022   // Add the parameter declaration into this scope.
13023   S->AddDecl(New);
13024   if (II)
13025     IdResolver.AddDecl(New);
13026 
13027   ProcessDeclAttributes(S, New, D);
13028 
13029   if (D.getDeclSpec().isModulePrivateSpecified())
13030     Diag(New->getLocation(), diag::err_module_private_local)
13031       << 1 << New->getDeclName()
13032       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13033       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13034 
13035   if (New->hasAttr<BlocksAttr>()) {
13036     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13037   }
13038   return New;
13039 }
13040 
13041 /// Synthesizes a variable for a parameter arising from a
13042 /// typedef.
13043 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13044                                               SourceLocation Loc,
13045                                               QualType T) {
13046   /* FIXME: setting StartLoc == Loc.
13047      Would it be worth to modify callers so as to provide proper source
13048      location for the unnamed parameters, embedding the parameter's type? */
13049   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13050                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13051                                            SC_None, nullptr);
13052   Param->setImplicit();
13053   return Param;
13054 }
13055 
13056 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13057   // Don't diagnose unused-parameter errors in template instantiations; we
13058   // will already have done so in the template itself.
13059   if (inTemplateInstantiation())
13060     return;
13061 
13062   for (const ParmVarDecl *Parameter : Parameters) {
13063     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13064         !Parameter->hasAttr<UnusedAttr>()) {
13065       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13066         << Parameter->getDeclName();
13067     }
13068   }
13069 }
13070 
13071 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13072     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13073   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13074     return;
13075 
13076   // Warn if the return value is pass-by-value and larger than the specified
13077   // threshold.
13078   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13079     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13080     if (Size > LangOpts.NumLargeByValueCopy)
13081       Diag(D->getLocation(), diag::warn_return_value_size)
13082           << D->getDeclName() << Size;
13083   }
13084 
13085   // Warn if any parameter is pass-by-value and larger than the specified
13086   // threshold.
13087   for (const ParmVarDecl *Parameter : Parameters) {
13088     QualType T = Parameter->getType();
13089     if (T->isDependentType() || !T.isPODType(Context))
13090       continue;
13091     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13092     if (Size > LangOpts.NumLargeByValueCopy)
13093       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13094           << Parameter->getDeclName() << Size;
13095   }
13096 }
13097 
13098 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13099                                   SourceLocation NameLoc, IdentifierInfo *Name,
13100                                   QualType T, TypeSourceInfo *TSInfo,
13101                                   StorageClass SC) {
13102   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13103   if (getLangOpts().ObjCAutoRefCount &&
13104       T.getObjCLifetime() == Qualifiers::OCL_None &&
13105       T->isObjCLifetimeType()) {
13106 
13107     Qualifiers::ObjCLifetime lifetime;
13108 
13109     // Special cases for arrays:
13110     //   - if it's const, use __unsafe_unretained
13111     //   - otherwise, it's an error
13112     if (T->isArrayType()) {
13113       if (!T.isConstQualified()) {
13114         if (DelayedDiagnostics.shouldDelayDiagnostics())
13115           DelayedDiagnostics.add(
13116               sema::DelayedDiagnostic::makeForbiddenType(
13117               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13118         else
13119           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13120               << TSInfo->getTypeLoc().getSourceRange();
13121       }
13122       lifetime = Qualifiers::OCL_ExplicitNone;
13123     } else {
13124       lifetime = T->getObjCARCImplicitLifetime();
13125     }
13126     T = Context.getLifetimeQualifiedType(T, lifetime);
13127   }
13128 
13129   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13130                                          Context.getAdjustedParameterType(T),
13131                                          TSInfo, SC, nullptr);
13132 
13133   // Make a note if we created a new pack in the scope of a lambda, so that
13134   // we know that references to that pack must also be expanded within the
13135   // lambda scope.
13136   if (New->isParameterPack())
13137     if (auto *LSI = getEnclosingLambda())
13138       LSI->LocalPacks.push_back(New);
13139 
13140   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13141       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13142     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13143                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13144 
13145   // Parameters can not be abstract class types.
13146   // For record types, this is done by the AbstractClassUsageDiagnoser once
13147   // the class has been completely parsed.
13148   if (!CurContext->isRecord() &&
13149       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13150                              AbstractParamType))
13151     New->setInvalidDecl();
13152 
13153   // Parameter declarators cannot be interface types. All ObjC objects are
13154   // passed by reference.
13155   if (T->isObjCObjectType()) {
13156     SourceLocation TypeEndLoc =
13157         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13158     Diag(NameLoc,
13159          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13160       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13161     T = Context.getObjCObjectPointerType(T);
13162     New->setType(T);
13163   }
13164 
13165   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13166   // duration shall not be qualified by an address-space qualifier."
13167   // Since all parameters have automatic store duration, they can not have
13168   // an address space.
13169   if (T.getAddressSpace() != LangAS::Default &&
13170       // OpenCL allows function arguments declared to be an array of a type
13171       // to be qualified with an address space.
13172       !(getLangOpts().OpenCL &&
13173         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13174     Diag(NameLoc, diag::err_arg_with_address_space);
13175     New->setInvalidDecl();
13176   }
13177 
13178   return New;
13179 }
13180 
13181 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13182                                            SourceLocation LocAfterDecls) {
13183   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13184 
13185   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13186   // for a K&R function.
13187   if (!FTI.hasPrototype) {
13188     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13189       --i;
13190       if (FTI.Params[i].Param == nullptr) {
13191         SmallString<256> Code;
13192         llvm::raw_svector_ostream(Code)
13193             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13194         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13195             << FTI.Params[i].Ident
13196             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13197 
13198         // Implicitly declare the argument as type 'int' for lack of a better
13199         // type.
13200         AttributeFactory attrs;
13201         DeclSpec DS(attrs);
13202         const char* PrevSpec; // unused
13203         unsigned DiagID; // unused
13204         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13205                            DiagID, Context.getPrintingPolicy());
13206         // Use the identifier location for the type source range.
13207         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13208         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13209         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13210         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13211         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13212       }
13213     }
13214   }
13215 }
13216 
13217 Decl *
13218 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13219                               MultiTemplateParamsArg TemplateParameterLists,
13220                               SkipBodyInfo *SkipBody) {
13221   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13222   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13223   Scope *ParentScope = FnBodyScope->getParent();
13224 
13225   D.setFunctionDefinitionKind(FDK_Definition);
13226   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13227   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13228 }
13229 
13230 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13231   Consumer.HandleInlineFunctionDefinition(D);
13232 }
13233 
13234 static bool
13235 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13236                                 const FunctionDecl *&PossiblePrototype) {
13237   // Don't warn about invalid declarations.
13238   if (FD->isInvalidDecl())
13239     return false;
13240 
13241   // Or declarations that aren't global.
13242   if (!FD->isGlobal())
13243     return false;
13244 
13245   // Don't warn about C++ member functions.
13246   if (isa<CXXMethodDecl>(FD))
13247     return false;
13248 
13249   // Don't warn about 'main'.
13250   if (FD->isMain())
13251     return false;
13252 
13253   // Don't warn about inline functions.
13254   if (FD->isInlined())
13255     return false;
13256 
13257   // Don't warn about function templates.
13258   if (FD->getDescribedFunctionTemplate())
13259     return false;
13260 
13261   // Don't warn about function template specializations.
13262   if (FD->isFunctionTemplateSpecialization())
13263     return false;
13264 
13265   // Don't warn for OpenCL kernels.
13266   if (FD->hasAttr<OpenCLKernelAttr>())
13267     return false;
13268 
13269   // Don't warn on explicitly deleted functions.
13270   if (FD->isDeleted())
13271     return false;
13272 
13273   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13274        Prev; Prev = Prev->getPreviousDecl()) {
13275     // Ignore any declarations that occur in function or method
13276     // scope, because they aren't visible from the header.
13277     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13278       continue;
13279 
13280     PossiblePrototype = Prev;
13281     return Prev->getType()->isFunctionNoProtoType();
13282   }
13283 
13284   return true;
13285 }
13286 
13287 void
13288 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13289                                    const FunctionDecl *EffectiveDefinition,
13290                                    SkipBodyInfo *SkipBody) {
13291   const FunctionDecl *Definition = EffectiveDefinition;
13292   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13293     // If this is a friend function defined in a class template, it does not
13294     // have a body until it is used, nevertheless it is a definition, see
13295     // [temp.inst]p2:
13296     //
13297     // ... for the purpose of determining whether an instantiated redeclaration
13298     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13299     // corresponds to a definition in the template is considered to be a
13300     // definition.
13301     //
13302     // The following code must produce redefinition error:
13303     //
13304     //     template<typename T> struct C20 { friend void func_20() {} };
13305     //     C20<int> c20i;
13306     //     void func_20() {}
13307     //
13308     for (auto I : FD->redecls()) {
13309       if (I != FD && !I->isInvalidDecl() &&
13310           I->getFriendObjectKind() != Decl::FOK_None) {
13311         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13312           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13313             // A merged copy of the same function, instantiated as a member of
13314             // the same class, is OK.
13315             if (declaresSameEntity(OrigFD, Original) &&
13316                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13317                                    cast<Decl>(FD->getLexicalDeclContext())))
13318               continue;
13319           }
13320 
13321           if (Original->isThisDeclarationADefinition()) {
13322             Definition = I;
13323             break;
13324           }
13325         }
13326       }
13327     }
13328   }
13329 
13330   if (!Definition)
13331     // Similar to friend functions a friend function template may be a
13332     // definition and do not have a body if it is instantiated in a class
13333     // template.
13334     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13335       for (auto I : FTD->redecls()) {
13336         auto D = cast<FunctionTemplateDecl>(I);
13337         if (D != FTD) {
13338           assert(!D->isThisDeclarationADefinition() &&
13339                  "More than one definition in redeclaration chain");
13340           if (D->getFriendObjectKind() != Decl::FOK_None)
13341             if (FunctionTemplateDecl *FT =
13342                                        D->getInstantiatedFromMemberTemplate()) {
13343               if (FT->isThisDeclarationADefinition()) {
13344                 Definition = D->getTemplatedDecl();
13345                 break;
13346               }
13347             }
13348         }
13349       }
13350     }
13351 
13352   if (!Definition)
13353     return;
13354 
13355   if (canRedefineFunction(Definition, getLangOpts()))
13356     return;
13357 
13358   // Don't emit an error when this is redefinition of a typo-corrected
13359   // definition.
13360   if (TypoCorrectedFunctionDefinitions.count(Definition))
13361     return;
13362 
13363   // If we don't have a visible definition of the function, and it's inline or
13364   // a template, skip the new definition.
13365   if (SkipBody && !hasVisibleDefinition(Definition) &&
13366       (Definition->getFormalLinkage() == InternalLinkage ||
13367        Definition->isInlined() ||
13368        Definition->getDescribedFunctionTemplate() ||
13369        Definition->getNumTemplateParameterLists())) {
13370     SkipBody->ShouldSkip = true;
13371     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13372     if (auto *TD = Definition->getDescribedFunctionTemplate())
13373       makeMergedDefinitionVisible(TD);
13374     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13375     return;
13376   }
13377 
13378   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13379       Definition->getStorageClass() == SC_Extern)
13380     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13381         << FD->getDeclName() << getLangOpts().CPlusPlus;
13382   else
13383     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13384 
13385   Diag(Definition->getLocation(), diag::note_previous_definition);
13386   FD->setInvalidDecl();
13387 }
13388 
13389 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13390                                    Sema &S) {
13391   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13392 
13393   LambdaScopeInfo *LSI = S.PushLambdaScope();
13394   LSI->CallOperator = CallOperator;
13395   LSI->Lambda = LambdaClass;
13396   LSI->ReturnType = CallOperator->getReturnType();
13397   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13398 
13399   if (LCD == LCD_None)
13400     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13401   else if (LCD == LCD_ByCopy)
13402     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13403   else if (LCD == LCD_ByRef)
13404     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13405   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13406 
13407   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13408   LSI->Mutable = !CallOperator->isConst();
13409 
13410   // Add the captures to the LSI so they can be noted as already
13411   // captured within tryCaptureVar.
13412   auto I = LambdaClass->field_begin();
13413   for (const auto &C : LambdaClass->captures()) {
13414     if (C.capturesVariable()) {
13415       VarDecl *VD = C.getCapturedVar();
13416       if (VD->isInitCapture())
13417         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13418       QualType CaptureType = VD->getType();
13419       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13420       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13421           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13422           /*EllipsisLoc*/C.isPackExpansion()
13423                          ? C.getEllipsisLoc() : SourceLocation(),
13424           CaptureType, /*Invalid*/false);
13425 
13426     } else if (C.capturesThis()) {
13427       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13428                           C.getCaptureKind() == LCK_StarThis);
13429     } else {
13430       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13431                              I->getType());
13432     }
13433     ++I;
13434   }
13435 }
13436 
13437 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13438                                     SkipBodyInfo *SkipBody) {
13439   if (!D) {
13440     // Parsing the function declaration failed in some way. Push on a fake scope
13441     // anyway so we can try to parse the function body.
13442     PushFunctionScope();
13443     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13444     return D;
13445   }
13446 
13447   FunctionDecl *FD = nullptr;
13448 
13449   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13450     FD = FunTmpl->getTemplatedDecl();
13451   else
13452     FD = cast<FunctionDecl>(D);
13453 
13454   // Do not push if it is a lambda because one is already pushed when building
13455   // the lambda in ActOnStartOfLambdaDefinition().
13456   if (!isLambdaCallOperator(FD))
13457     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13458 
13459   // Check for defining attributes before the check for redefinition.
13460   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13461     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13462     FD->dropAttr<AliasAttr>();
13463     FD->setInvalidDecl();
13464   }
13465   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13466     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13467     FD->dropAttr<IFuncAttr>();
13468     FD->setInvalidDecl();
13469   }
13470 
13471   // See if this is a redefinition. If 'will have body' is already set, then
13472   // these checks were already performed when it was set.
13473   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13474     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13475 
13476     // If we're skipping the body, we're done. Don't enter the scope.
13477     if (SkipBody && SkipBody->ShouldSkip)
13478       return D;
13479   }
13480 
13481   // Mark this function as "will have a body eventually".  This lets users to
13482   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13483   // this function.
13484   FD->setWillHaveBody();
13485 
13486   // If we are instantiating a generic lambda call operator, push
13487   // a LambdaScopeInfo onto the function stack.  But use the information
13488   // that's already been calculated (ActOnLambdaExpr) to prime the current
13489   // LambdaScopeInfo.
13490   // When the template operator is being specialized, the LambdaScopeInfo,
13491   // has to be properly restored so that tryCaptureVariable doesn't try
13492   // and capture any new variables. In addition when calculating potential
13493   // captures during transformation of nested lambdas, it is necessary to
13494   // have the LSI properly restored.
13495   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13496     assert(inTemplateInstantiation() &&
13497            "There should be an active template instantiation on the stack "
13498            "when instantiating a generic lambda!");
13499     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13500   } else {
13501     // Enter a new function scope
13502     PushFunctionScope();
13503   }
13504 
13505   // Builtin functions cannot be defined.
13506   if (unsigned BuiltinID = FD->getBuiltinID()) {
13507     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13508         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13509       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13510       FD->setInvalidDecl();
13511     }
13512   }
13513 
13514   // The return type of a function definition must be complete
13515   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13516   QualType ResultType = FD->getReturnType();
13517   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13518       !FD->isInvalidDecl() &&
13519       RequireCompleteType(FD->getLocation(), ResultType,
13520                           diag::err_func_def_incomplete_result))
13521     FD->setInvalidDecl();
13522 
13523   if (FnBodyScope)
13524     PushDeclContext(FnBodyScope, FD);
13525 
13526   // Check the validity of our function parameters
13527   CheckParmsForFunctionDef(FD->parameters(),
13528                            /*CheckParameterNames=*/true);
13529 
13530   // Add non-parameter declarations already in the function to the current
13531   // scope.
13532   if (FnBodyScope) {
13533     for (Decl *NPD : FD->decls()) {
13534       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13535       if (!NonParmDecl)
13536         continue;
13537       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13538              "parameters should not be in newly created FD yet");
13539 
13540       // If the decl has a name, make it accessible in the current scope.
13541       if (NonParmDecl->getDeclName())
13542         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13543 
13544       // Similarly, dive into enums and fish their constants out, making them
13545       // accessible in this scope.
13546       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13547         for (auto *EI : ED->enumerators())
13548           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13549       }
13550     }
13551   }
13552 
13553   // Introduce our parameters into the function scope
13554   for (auto Param : FD->parameters()) {
13555     Param->setOwningFunction(FD);
13556 
13557     // If this has an identifier, add it to the scope stack.
13558     if (Param->getIdentifier() && FnBodyScope) {
13559       CheckShadow(FnBodyScope, Param);
13560 
13561       PushOnScopeChains(Param, FnBodyScope);
13562     }
13563   }
13564 
13565   // Ensure that the function's exception specification is instantiated.
13566   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13567     ResolveExceptionSpec(D->getLocation(), FPT);
13568 
13569   // dllimport cannot be applied to non-inline function definitions.
13570   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13571       !FD->isTemplateInstantiation()) {
13572     assert(!FD->hasAttr<DLLExportAttr>());
13573     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13574     FD->setInvalidDecl();
13575     return D;
13576   }
13577   // We want to attach documentation to original Decl (which might be
13578   // a function template).
13579   ActOnDocumentableDecl(D);
13580   if (getCurLexicalContext()->isObjCContainer() &&
13581       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13582       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13583     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13584 
13585   return D;
13586 }
13587 
13588 /// Given the set of return statements within a function body,
13589 /// compute the variables that are subject to the named return value
13590 /// optimization.
13591 ///
13592 /// Each of the variables that is subject to the named return value
13593 /// optimization will be marked as NRVO variables in the AST, and any
13594 /// return statement that has a marked NRVO variable as its NRVO candidate can
13595 /// use the named return value optimization.
13596 ///
13597 /// This function applies a very simplistic algorithm for NRVO: if every return
13598 /// statement in the scope of a variable has the same NRVO candidate, that
13599 /// candidate is an NRVO variable.
13600 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13601   ReturnStmt **Returns = Scope->Returns.data();
13602 
13603   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13604     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13605       if (!NRVOCandidate->isNRVOVariable())
13606         Returns[I]->setNRVOCandidate(nullptr);
13607     }
13608   }
13609 }
13610 
13611 bool Sema::canDelayFunctionBody(const Declarator &D) {
13612   // We can't delay parsing the body of a constexpr function template (yet).
13613   if (D.getDeclSpec().hasConstexprSpecifier())
13614     return false;
13615 
13616   // We can't delay parsing the body of a function template with a deduced
13617   // return type (yet).
13618   if (D.getDeclSpec().hasAutoTypeSpec()) {
13619     // If the placeholder introduces a non-deduced trailing return type,
13620     // we can still delay parsing it.
13621     if (D.getNumTypeObjects()) {
13622       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13623       if (Outer.Kind == DeclaratorChunk::Function &&
13624           Outer.Fun.hasTrailingReturnType()) {
13625         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13626         return Ty.isNull() || !Ty->isUndeducedType();
13627       }
13628     }
13629     return false;
13630   }
13631 
13632   return true;
13633 }
13634 
13635 bool Sema::canSkipFunctionBody(Decl *D) {
13636   // We cannot skip the body of a function (or function template) which is
13637   // constexpr, since we may need to evaluate its body in order to parse the
13638   // rest of the file.
13639   // We cannot skip the body of a function with an undeduced return type,
13640   // because any callers of that function need to know the type.
13641   if (const FunctionDecl *FD = D->getAsFunction()) {
13642     if (FD->isConstexpr())
13643       return false;
13644     // We can't simply call Type::isUndeducedType here, because inside template
13645     // auto can be deduced to a dependent type, which is not considered
13646     // "undeduced".
13647     if (FD->getReturnType()->getContainedDeducedType())
13648       return false;
13649   }
13650   return Consumer.shouldSkipFunctionBody(D);
13651 }
13652 
13653 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13654   if (!Decl)
13655     return nullptr;
13656   if (FunctionDecl *FD = Decl->getAsFunction())
13657     FD->setHasSkippedBody();
13658   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13659     MD->setHasSkippedBody();
13660   return Decl;
13661 }
13662 
13663 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13664   return ActOnFinishFunctionBody(D, BodyArg, false);
13665 }
13666 
13667 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13668 /// body.
13669 class ExitFunctionBodyRAII {
13670 public:
13671   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13672   ~ExitFunctionBodyRAII() {
13673     if (!IsLambda)
13674       S.PopExpressionEvaluationContext();
13675   }
13676 
13677 private:
13678   Sema &S;
13679   bool IsLambda = false;
13680 };
13681 
13682 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13683   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13684 
13685   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13686     if (EscapeInfo.count(BD))
13687       return EscapeInfo[BD];
13688 
13689     bool R = false;
13690     const BlockDecl *CurBD = BD;
13691 
13692     do {
13693       R = !CurBD->doesNotEscape();
13694       if (R)
13695         break;
13696       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13697     } while (CurBD);
13698 
13699     return EscapeInfo[BD] = R;
13700   };
13701 
13702   // If the location where 'self' is implicitly retained is inside a escaping
13703   // block, emit a diagnostic.
13704   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13705        S.ImplicitlyRetainedSelfLocs)
13706     if (IsOrNestedInEscapingBlock(P.second))
13707       S.Diag(P.first, diag::warn_implicitly_retains_self)
13708           << FixItHint::CreateInsertion(P.first, "self->");
13709 }
13710 
13711 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13712                                     bool IsInstantiation) {
13713   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13714 
13715   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13716   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13717 
13718   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13719     CheckCompletedCoroutineBody(FD, Body);
13720 
13721   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13722   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13723   // meant to pop the context added in ActOnStartOfFunctionDef().
13724   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13725 
13726   if (FD) {
13727     FD->setBody(Body);
13728     FD->setWillHaveBody(false);
13729 
13730     if (getLangOpts().CPlusPlus14) {
13731       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13732           FD->getReturnType()->isUndeducedType()) {
13733         // If the function has a deduced result type but contains no 'return'
13734         // statements, the result type as written must be exactly 'auto', and
13735         // the deduced result type is 'void'.
13736         if (!FD->getReturnType()->getAs<AutoType>()) {
13737           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13738               << FD->getReturnType();
13739           FD->setInvalidDecl();
13740         } else {
13741           // Substitute 'void' for the 'auto' in the type.
13742           TypeLoc ResultType = getReturnTypeLoc(FD);
13743           Context.adjustDeducedFunctionResultType(
13744               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13745         }
13746       }
13747     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13748       // In C++11, we don't use 'auto' deduction rules for lambda call
13749       // operators because we don't support return type deduction.
13750       auto *LSI = getCurLambda();
13751       if (LSI->HasImplicitReturnType) {
13752         deduceClosureReturnType(*LSI);
13753 
13754         // C++11 [expr.prim.lambda]p4:
13755         //   [...] if there are no return statements in the compound-statement
13756         //   [the deduced type is] the type void
13757         QualType RetType =
13758             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13759 
13760         // Update the return type to the deduced type.
13761         const FunctionProtoType *Proto =
13762             FD->getType()->getAs<FunctionProtoType>();
13763         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13764                                             Proto->getExtProtoInfo()));
13765       }
13766     }
13767 
13768     // If the function implicitly returns zero (like 'main') or is naked,
13769     // don't complain about missing return statements.
13770     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13771       WP.disableCheckFallThrough();
13772 
13773     // MSVC permits the use of pure specifier (=0) on function definition,
13774     // defined at class scope, warn about this non-standard construct.
13775     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13776       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13777 
13778     if (!FD->isInvalidDecl()) {
13779       // Don't diagnose unused parameters of defaulted or deleted functions.
13780       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13781         DiagnoseUnusedParameters(FD->parameters());
13782       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13783                                              FD->getReturnType(), FD);
13784 
13785       // If this is a structor, we need a vtable.
13786       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13787         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13788       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13789         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13790 
13791       // Try to apply the named return value optimization. We have to check
13792       // if we can do this here because lambdas keep return statements around
13793       // to deduce an implicit return type.
13794       if (FD->getReturnType()->isRecordType() &&
13795           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13796         computeNRVO(Body, getCurFunction());
13797     }
13798 
13799     // GNU warning -Wmissing-prototypes:
13800     //   Warn if a global function is defined without a previous
13801     //   prototype declaration. This warning is issued even if the
13802     //   definition itself provides a prototype. The aim is to detect
13803     //   global functions that fail to be declared in header files.
13804     const FunctionDecl *PossiblePrototype = nullptr;
13805     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13806       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13807 
13808       if (PossiblePrototype) {
13809         // We found a declaration that is not a prototype,
13810         // but that could be a zero-parameter prototype
13811         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13812           TypeLoc TL = TI->getTypeLoc();
13813           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13814             Diag(PossiblePrototype->getLocation(),
13815                  diag::note_declaration_not_a_prototype)
13816                 << (FD->getNumParams() != 0)
13817                 << (FD->getNumParams() == 0
13818                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13819                         : FixItHint{});
13820         }
13821       } else {
13822         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13823             << /* function */ 1
13824             << (FD->getStorageClass() == SC_None
13825                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13826                                                  "static ")
13827                     : FixItHint{});
13828       }
13829 
13830       // GNU warning -Wstrict-prototypes
13831       //   Warn if K&R function is defined without a previous declaration.
13832       //   This warning is issued only if the definition itself does not provide
13833       //   a prototype. Only K&R definitions do not provide a prototype.
13834       //   An empty list in a function declarator that is part of a definition
13835       //   of that function specifies that the function has no parameters
13836       //   (C99 6.7.5.3p14)
13837       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13838           !LangOpts.CPlusPlus) {
13839         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13840         TypeLoc TL = TI->getTypeLoc();
13841         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13842         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13843       }
13844     }
13845 
13846     // Warn on CPUDispatch with an actual body.
13847     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13848       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13849         if (!CmpndBody->body_empty())
13850           Diag(CmpndBody->body_front()->getBeginLoc(),
13851                diag::warn_dispatch_body_ignored);
13852 
13853     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13854       const CXXMethodDecl *KeyFunction;
13855       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13856           MD->isVirtual() &&
13857           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13858           MD == KeyFunction->getCanonicalDecl()) {
13859         // Update the key-function state if necessary for this ABI.
13860         if (FD->isInlined() &&
13861             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13862           Context.setNonKeyFunction(MD);
13863 
13864           // If the newly-chosen key function is already defined, then we
13865           // need to mark the vtable as used retroactively.
13866           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13867           const FunctionDecl *Definition;
13868           if (KeyFunction && KeyFunction->isDefined(Definition))
13869             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13870         } else {
13871           // We just defined they key function; mark the vtable as used.
13872           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13873         }
13874       }
13875     }
13876 
13877     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13878            "Function parsing confused");
13879   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13880     assert(MD == getCurMethodDecl() && "Method parsing confused");
13881     MD->setBody(Body);
13882     if (!MD->isInvalidDecl()) {
13883       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13884                                              MD->getReturnType(), MD);
13885 
13886       if (Body)
13887         computeNRVO(Body, getCurFunction());
13888     }
13889     if (getCurFunction()->ObjCShouldCallSuper) {
13890       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13891           << MD->getSelector().getAsString();
13892       getCurFunction()->ObjCShouldCallSuper = false;
13893     }
13894     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13895       const ObjCMethodDecl *InitMethod = nullptr;
13896       bool isDesignated =
13897           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13898       assert(isDesignated && InitMethod);
13899       (void)isDesignated;
13900 
13901       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13902         auto IFace = MD->getClassInterface();
13903         if (!IFace)
13904           return false;
13905         auto SuperD = IFace->getSuperClass();
13906         if (!SuperD)
13907           return false;
13908         return SuperD->getIdentifier() ==
13909             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13910       };
13911       // Don't issue this warning for unavailable inits or direct subclasses
13912       // of NSObject.
13913       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13914         Diag(MD->getLocation(),
13915              diag::warn_objc_designated_init_missing_super_call);
13916         Diag(InitMethod->getLocation(),
13917              diag::note_objc_designated_init_marked_here);
13918       }
13919       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13920     }
13921     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13922       // Don't issue this warning for unavaialable inits.
13923       if (!MD->isUnavailable())
13924         Diag(MD->getLocation(),
13925              diag::warn_objc_secondary_init_missing_init_call);
13926       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13927     }
13928 
13929     diagnoseImplicitlyRetainedSelf(*this);
13930   } else {
13931     // Parsing the function declaration failed in some way. Pop the fake scope
13932     // we pushed on.
13933     PopFunctionScopeInfo(ActivePolicy, dcl);
13934     return nullptr;
13935   }
13936 
13937   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13938     DiagnoseUnguardedAvailabilityViolations(dcl);
13939 
13940   assert(!getCurFunction()->ObjCShouldCallSuper &&
13941          "This should only be set for ObjC methods, which should have been "
13942          "handled in the block above.");
13943 
13944   // Verify and clean out per-function state.
13945   if (Body && (!FD || !FD->isDefaulted())) {
13946     // C++ constructors that have function-try-blocks can't have return
13947     // statements in the handlers of that block. (C++ [except.handle]p14)
13948     // Verify this.
13949     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13950       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13951 
13952     // Verify that gotos and switch cases don't jump into scopes illegally.
13953     if (getCurFunction()->NeedsScopeChecking() &&
13954         !PP.isCodeCompletionEnabled())
13955       DiagnoseInvalidJumps(Body);
13956 
13957     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13958       if (!Destructor->getParent()->isDependentType())
13959         CheckDestructor(Destructor);
13960 
13961       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13962                                              Destructor->getParent());
13963     }
13964 
13965     // If any errors have occurred, clear out any temporaries that may have
13966     // been leftover. This ensures that these temporaries won't be picked up for
13967     // deletion in some later function.
13968     if (getDiagnostics().hasErrorOccurred() ||
13969         getDiagnostics().getSuppressAllDiagnostics()) {
13970       DiscardCleanupsInEvaluationContext();
13971     }
13972     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13973         !isa<FunctionTemplateDecl>(dcl)) {
13974       // Since the body is valid, issue any analysis-based warnings that are
13975       // enabled.
13976       ActivePolicy = &WP;
13977     }
13978 
13979     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13980         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
13981       FD->setInvalidDecl();
13982 
13983     if (FD && FD->hasAttr<NakedAttr>()) {
13984       for (const Stmt *S : Body->children()) {
13985         // Allow local register variables without initializer as they don't
13986         // require prologue.
13987         bool RegisterVariables = false;
13988         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13989           for (const auto *Decl : DS->decls()) {
13990             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13991               RegisterVariables =
13992                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13993               if (!RegisterVariables)
13994                 break;
13995             }
13996           }
13997         }
13998         if (RegisterVariables)
13999           continue;
14000         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14001           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14002           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14003           FD->setInvalidDecl();
14004           break;
14005         }
14006       }
14007     }
14008 
14009     assert(ExprCleanupObjects.size() ==
14010                ExprEvalContexts.back().NumCleanupObjects &&
14011            "Leftover temporaries in function");
14012     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14013     assert(MaybeODRUseExprs.empty() &&
14014            "Leftover expressions for odr-use checking");
14015   }
14016 
14017   if (!IsInstantiation)
14018     PopDeclContext();
14019 
14020   PopFunctionScopeInfo(ActivePolicy, dcl);
14021   // If any errors have occurred, clear out any temporaries that may have
14022   // been leftover. This ensures that these temporaries won't be picked up for
14023   // deletion in some later function.
14024   if (getDiagnostics().hasErrorOccurred()) {
14025     DiscardCleanupsInEvaluationContext();
14026   }
14027 
14028   return dcl;
14029 }
14030 
14031 /// When we finish delayed parsing of an attribute, we must attach it to the
14032 /// relevant Decl.
14033 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14034                                        ParsedAttributes &Attrs) {
14035   // Always attach attributes to the underlying decl.
14036   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14037     D = TD->getTemplatedDecl();
14038   ProcessDeclAttributeList(S, D, Attrs);
14039 
14040   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14041     if (Method->isStatic())
14042       checkThisInStaticMemberFunctionAttributes(Method);
14043 }
14044 
14045 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14046 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14047 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14048                                           IdentifierInfo &II, Scope *S) {
14049   // Find the scope in which the identifier is injected and the corresponding
14050   // DeclContext.
14051   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14052   // In that case, we inject the declaration into the translation unit scope
14053   // instead.
14054   Scope *BlockScope = S;
14055   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14056     BlockScope = BlockScope->getParent();
14057 
14058   Scope *ContextScope = BlockScope;
14059   while (!ContextScope->getEntity())
14060     ContextScope = ContextScope->getParent();
14061   ContextRAII SavedContext(*this, ContextScope->getEntity());
14062 
14063   // Before we produce a declaration for an implicitly defined
14064   // function, see whether there was a locally-scoped declaration of
14065   // this name as a function or variable. If so, use that
14066   // (non-visible) declaration, and complain about it.
14067   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14068   if (ExternCPrev) {
14069     // We still need to inject the function into the enclosing block scope so
14070     // that later (non-call) uses can see it.
14071     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14072 
14073     // C89 footnote 38:
14074     //   If in fact it is not defined as having type "function returning int",
14075     //   the behavior is undefined.
14076     if (!isa<FunctionDecl>(ExternCPrev) ||
14077         !Context.typesAreCompatible(
14078             cast<FunctionDecl>(ExternCPrev)->getType(),
14079             Context.getFunctionNoProtoType(Context.IntTy))) {
14080       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14081           << ExternCPrev << !getLangOpts().C99;
14082       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14083       return ExternCPrev;
14084     }
14085   }
14086 
14087   // Extension in C99.  Legal in C90, but warn about it.
14088   unsigned diag_id;
14089   if (II.getName().startswith("__builtin_"))
14090     diag_id = diag::warn_builtin_unknown;
14091   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14092   else if (getLangOpts().OpenCL)
14093     diag_id = diag::err_opencl_implicit_function_decl;
14094   else if (getLangOpts().C99)
14095     diag_id = diag::ext_implicit_function_decl;
14096   else
14097     diag_id = diag::warn_implicit_function_decl;
14098   Diag(Loc, diag_id) << &II;
14099 
14100   // If we found a prior declaration of this function, don't bother building
14101   // another one. We've already pushed that one into scope, so there's nothing
14102   // more to do.
14103   if (ExternCPrev)
14104     return ExternCPrev;
14105 
14106   // Because typo correction is expensive, only do it if the implicit
14107   // function declaration is going to be treated as an error.
14108   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14109     TypoCorrection Corrected;
14110     DeclFilterCCC<FunctionDecl> CCC{};
14111     if (S && (Corrected =
14112                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14113                               S, nullptr, CCC, CTK_NonError)))
14114       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14115                    /*ErrorRecovery*/false);
14116   }
14117 
14118   // Set a Declarator for the implicit definition: int foo();
14119   const char *Dummy;
14120   AttributeFactory attrFactory;
14121   DeclSpec DS(attrFactory);
14122   unsigned DiagID;
14123   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14124                                   Context.getPrintingPolicy());
14125   (void)Error; // Silence warning.
14126   assert(!Error && "Error setting up implicit decl!");
14127   SourceLocation NoLoc;
14128   Declarator D(DS, DeclaratorContext::BlockContext);
14129   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14130                                              /*IsAmbiguous=*/false,
14131                                              /*LParenLoc=*/NoLoc,
14132                                              /*Params=*/nullptr,
14133                                              /*NumParams=*/0,
14134                                              /*EllipsisLoc=*/NoLoc,
14135                                              /*RParenLoc=*/NoLoc,
14136                                              /*RefQualifierIsLvalueRef=*/true,
14137                                              /*RefQualifierLoc=*/NoLoc,
14138                                              /*MutableLoc=*/NoLoc, EST_None,
14139                                              /*ESpecRange=*/SourceRange(),
14140                                              /*Exceptions=*/nullptr,
14141                                              /*ExceptionRanges=*/nullptr,
14142                                              /*NumExceptions=*/0,
14143                                              /*NoexceptExpr=*/nullptr,
14144                                              /*ExceptionSpecTokens=*/nullptr,
14145                                              /*DeclsInPrototype=*/None, Loc,
14146                                              Loc, D),
14147                 std::move(DS.getAttributes()), SourceLocation());
14148   D.SetIdentifier(&II, Loc);
14149 
14150   // Insert this function into the enclosing block scope.
14151   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14152   FD->setImplicit();
14153 
14154   AddKnownFunctionAttributes(FD);
14155 
14156   return FD;
14157 }
14158 
14159 /// Adds any function attributes that we know a priori based on
14160 /// the declaration of this function.
14161 ///
14162 /// These attributes can apply both to implicitly-declared builtins
14163 /// (like __builtin___printf_chk) or to library-declared functions
14164 /// like NSLog or printf.
14165 ///
14166 /// We need to check for duplicate attributes both here and where user-written
14167 /// attributes are applied to declarations.
14168 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14169   if (FD->isInvalidDecl())
14170     return;
14171 
14172   // If this is a built-in function, map its builtin attributes to
14173   // actual attributes.
14174   if (unsigned BuiltinID = FD->getBuiltinID()) {
14175     // Handle printf-formatting attributes.
14176     unsigned FormatIdx;
14177     bool HasVAListArg;
14178     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14179       if (!FD->hasAttr<FormatAttr>()) {
14180         const char *fmt = "printf";
14181         unsigned int NumParams = FD->getNumParams();
14182         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14183             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14184           fmt = "NSString";
14185         FD->addAttr(FormatAttr::CreateImplicit(Context,
14186                                                &Context.Idents.get(fmt),
14187                                                FormatIdx+1,
14188                                                HasVAListArg ? 0 : FormatIdx+2,
14189                                                FD->getLocation()));
14190       }
14191     }
14192     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14193                                              HasVAListArg)) {
14194      if (!FD->hasAttr<FormatAttr>())
14195        FD->addAttr(FormatAttr::CreateImplicit(Context,
14196                                               &Context.Idents.get("scanf"),
14197                                               FormatIdx+1,
14198                                               HasVAListArg ? 0 : FormatIdx+2,
14199                                               FD->getLocation()));
14200     }
14201 
14202     // Handle automatically recognized callbacks.
14203     SmallVector<int, 4> Encoding;
14204     if (!FD->hasAttr<CallbackAttr>() &&
14205         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14206       FD->addAttr(CallbackAttr::CreateImplicit(
14207           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14208 
14209     // Mark const if we don't care about errno and that is the only thing
14210     // preventing the function from being const. This allows IRgen to use LLVM
14211     // intrinsics for such functions.
14212     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14213         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14214       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14215 
14216     // We make "fma" on some platforms const because we know it does not set
14217     // errno in those environments even though it could set errno based on the
14218     // C standard.
14219     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14220     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14221         !FD->hasAttr<ConstAttr>()) {
14222       switch (BuiltinID) {
14223       case Builtin::BI__builtin_fma:
14224       case Builtin::BI__builtin_fmaf:
14225       case Builtin::BI__builtin_fmal:
14226       case Builtin::BIfma:
14227       case Builtin::BIfmaf:
14228       case Builtin::BIfmal:
14229         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14230         break;
14231       default:
14232         break;
14233       }
14234     }
14235 
14236     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14237         !FD->hasAttr<ReturnsTwiceAttr>())
14238       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14239                                          FD->getLocation()));
14240     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14241       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14242     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14243       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14244     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14245       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14246     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14247         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14248       // Add the appropriate attribute, depending on the CUDA compilation mode
14249       // and which target the builtin belongs to. For example, during host
14250       // compilation, aux builtins are __device__, while the rest are __host__.
14251       if (getLangOpts().CUDAIsDevice !=
14252           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14253         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14254       else
14255         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14256     }
14257   }
14258 
14259   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14260   // throw, add an implicit nothrow attribute to any extern "C" function we come
14261   // across.
14262   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14263       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14264     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14265     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14266       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14267   }
14268 
14269   IdentifierInfo *Name = FD->getIdentifier();
14270   if (!Name)
14271     return;
14272   if ((!getLangOpts().CPlusPlus &&
14273        FD->getDeclContext()->isTranslationUnit()) ||
14274       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14275        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14276        LinkageSpecDecl::lang_c)) {
14277     // Okay: this could be a libc/libm/Objective-C function we know
14278     // about.
14279   } else
14280     return;
14281 
14282   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14283     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14284     // target-specific builtins, perhaps?
14285     if (!FD->hasAttr<FormatAttr>())
14286       FD->addAttr(FormatAttr::CreateImplicit(Context,
14287                                              &Context.Idents.get("printf"), 2,
14288                                              Name->isStr("vasprintf") ? 0 : 3,
14289                                              FD->getLocation()));
14290   }
14291 
14292   if (Name->isStr("__CFStringMakeConstantString")) {
14293     // We already have a __builtin___CFStringMakeConstantString,
14294     // but builds that use -fno-constant-cfstrings don't go through that.
14295     if (!FD->hasAttr<FormatArgAttr>())
14296       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14297                                                 FD->getLocation()));
14298   }
14299 }
14300 
14301 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14302                                     TypeSourceInfo *TInfo) {
14303   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14304   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14305 
14306   if (!TInfo) {
14307     assert(D.isInvalidType() && "no declarator info for valid type");
14308     TInfo = Context.getTrivialTypeSourceInfo(T);
14309   }
14310 
14311   // Scope manipulation handled by caller.
14312   TypedefDecl *NewTD =
14313       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14314                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14315 
14316   // Bail out immediately if we have an invalid declaration.
14317   if (D.isInvalidType()) {
14318     NewTD->setInvalidDecl();
14319     return NewTD;
14320   }
14321 
14322   if (D.getDeclSpec().isModulePrivateSpecified()) {
14323     if (CurContext->isFunctionOrMethod())
14324       Diag(NewTD->getLocation(), diag::err_module_private_local)
14325         << 2 << NewTD->getDeclName()
14326         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14327         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14328     else
14329       NewTD->setModulePrivate();
14330   }
14331 
14332   // C++ [dcl.typedef]p8:
14333   //   If the typedef declaration defines an unnamed class (or
14334   //   enum), the first typedef-name declared by the declaration
14335   //   to be that class type (or enum type) is used to denote the
14336   //   class type (or enum type) for linkage purposes only.
14337   // We need to check whether the type was declared in the declaration.
14338   switch (D.getDeclSpec().getTypeSpecType()) {
14339   case TST_enum:
14340   case TST_struct:
14341   case TST_interface:
14342   case TST_union:
14343   case TST_class: {
14344     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14345     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14346     break;
14347   }
14348 
14349   default:
14350     break;
14351   }
14352 
14353   return NewTD;
14354 }
14355 
14356 /// Check that this is a valid underlying type for an enum declaration.
14357 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14358   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14359   QualType T = TI->getType();
14360 
14361   if (T->isDependentType())
14362     return false;
14363 
14364   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14365     if (BT->isInteger())
14366       return false;
14367 
14368   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14369   return true;
14370 }
14371 
14372 /// Check whether this is a valid redeclaration of a previous enumeration.
14373 /// \return true if the redeclaration was invalid.
14374 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14375                                   QualType EnumUnderlyingTy, bool IsFixed,
14376                                   const EnumDecl *Prev) {
14377   if (IsScoped != Prev->isScoped()) {
14378     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14379       << Prev->isScoped();
14380     Diag(Prev->getLocation(), diag::note_previous_declaration);
14381     return true;
14382   }
14383 
14384   if (IsFixed && Prev->isFixed()) {
14385     if (!EnumUnderlyingTy->isDependentType() &&
14386         !Prev->getIntegerType()->isDependentType() &&
14387         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14388                                         Prev->getIntegerType())) {
14389       // TODO: Highlight the underlying type of the redeclaration.
14390       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14391         << EnumUnderlyingTy << Prev->getIntegerType();
14392       Diag(Prev->getLocation(), diag::note_previous_declaration)
14393           << Prev->getIntegerTypeRange();
14394       return true;
14395     }
14396   } else if (IsFixed != Prev->isFixed()) {
14397     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14398       << Prev->isFixed();
14399     Diag(Prev->getLocation(), diag::note_previous_declaration);
14400     return true;
14401   }
14402 
14403   return false;
14404 }
14405 
14406 /// Get diagnostic %select index for tag kind for
14407 /// redeclaration diagnostic message.
14408 /// WARNING: Indexes apply to particular diagnostics only!
14409 ///
14410 /// \returns diagnostic %select index.
14411 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14412   switch (Tag) {
14413   case TTK_Struct: return 0;
14414   case TTK_Interface: return 1;
14415   case TTK_Class:  return 2;
14416   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14417   }
14418 }
14419 
14420 /// Determine if tag kind is a class-key compatible with
14421 /// class for redeclaration (class, struct, or __interface).
14422 ///
14423 /// \returns true iff the tag kind is compatible.
14424 static bool isClassCompatTagKind(TagTypeKind Tag)
14425 {
14426   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14427 }
14428 
14429 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14430                                              TagTypeKind TTK) {
14431   if (isa<TypedefDecl>(PrevDecl))
14432     return NTK_Typedef;
14433   else if (isa<TypeAliasDecl>(PrevDecl))
14434     return NTK_TypeAlias;
14435   else if (isa<ClassTemplateDecl>(PrevDecl))
14436     return NTK_Template;
14437   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14438     return NTK_TypeAliasTemplate;
14439   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14440     return NTK_TemplateTemplateArgument;
14441   switch (TTK) {
14442   case TTK_Struct:
14443   case TTK_Interface:
14444   case TTK_Class:
14445     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14446   case TTK_Union:
14447     return NTK_NonUnion;
14448   case TTK_Enum:
14449     return NTK_NonEnum;
14450   }
14451   llvm_unreachable("invalid TTK");
14452 }
14453 
14454 /// Determine whether a tag with a given kind is acceptable
14455 /// as a redeclaration of the given tag declaration.
14456 ///
14457 /// \returns true if the new tag kind is acceptable, false otherwise.
14458 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14459                                         TagTypeKind NewTag, bool isDefinition,
14460                                         SourceLocation NewTagLoc,
14461                                         const IdentifierInfo *Name) {
14462   // C++ [dcl.type.elab]p3:
14463   //   The class-key or enum keyword present in the
14464   //   elaborated-type-specifier shall agree in kind with the
14465   //   declaration to which the name in the elaborated-type-specifier
14466   //   refers. This rule also applies to the form of
14467   //   elaborated-type-specifier that declares a class-name or
14468   //   friend class since it can be construed as referring to the
14469   //   definition of the class. Thus, in any
14470   //   elaborated-type-specifier, the enum keyword shall be used to
14471   //   refer to an enumeration (7.2), the union class-key shall be
14472   //   used to refer to a union (clause 9), and either the class or
14473   //   struct class-key shall be used to refer to a class (clause 9)
14474   //   declared using the class or struct class-key.
14475   TagTypeKind OldTag = Previous->getTagKind();
14476   if (OldTag != NewTag &&
14477       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14478     return false;
14479 
14480   // Tags are compatible, but we might still want to warn on mismatched tags.
14481   // Non-class tags can't be mismatched at this point.
14482   if (!isClassCompatTagKind(NewTag))
14483     return true;
14484 
14485   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14486   // by our warning analysis. We don't want to warn about mismatches with (eg)
14487   // declarations in system headers that are designed to be specialized, but if
14488   // a user asks us to warn, we should warn if their code contains mismatched
14489   // declarations.
14490   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14491     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14492                                       Loc);
14493   };
14494   if (IsIgnoredLoc(NewTagLoc))
14495     return true;
14496 
14497   auto IsIgnored = [&](const TagDecl *Tag) {
14498     return IsIgnoredLoc(Tag->getLocation());
14499   };
14500   while (IsIgnored(Previous)) {
14501     Previous = Previous->getPreviousDecl();
14502     if (!Previous)
14503       return true;
14504     OldTag = Previous->getTagKind();
14505   }
14506 
14507   bool isTemplate = false;
14508   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14509     isTemplate = Record->getDescribedClassTemplate();
14510 
14511   if (inTemplateInstantiation()) {
14512     if (OldTag != NewTag) {
14513       // In a template instantiation, do not offer fix-its for tag mismatches
14514       // since they usually mess up the template instead of fixing the problem.
14515       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14516         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14517         << getRedeclDiagFromTagKind(OldTag);
14518       // FIXME: Note previous location?
14519     }
14520     return true;
14521   }
14522 
14523   if (isDefinition) {
14524     // On definitions, check all previous tags and issue a fix-it for each
14525     // one that doesn't match the current tag.
14526     if (Previous->getDefinition()) {
14527       // Don't suggest fix-its for redefinitions.
14528       return true;
14529     }
14530 
14531     bool previousMismatch = false;
14532     for (const TagDecl *I : Previous->redecls()) {
14533       if (I->getTagKind() != NewTag) {
14534         // Ignore previous declarations for which the warning was disabled.
14535         if (IsIgnored(I))
14536           continue;
14537 
14538         if (!previousMismatch) {
14539           previousMismatch = true;
14540           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14541             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14542             << getRedeclDiagFromTagKind(I->getTagKind());
14543         }
14544         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14545           << getRedeclDiagFromTagKind(NewTag)
14546           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14547                TypeWithKeyword::getTagTypeKindName(NewTag));
14548       }
14549     }
14550     return true;
14551   }
14552 
14553   // Identify the prevailing tag kind: this is the kind of the definition (if
14554   // there is a non-ignored definition), or otherwise the kind of the prior
14555   // (non-ignored) declaration.
14556   const TagDecl *PrevDef = Previous->getDefinition();
14557   if (PrevDef && IsIgnored(PrevDef))
14558     PrevDef = nullptr;
14559   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14560   if (Redecl->getTagKind() != NewTag) {
14561     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14562       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14563       << getRedeclDiagFromTagKind(OldTag);
14564     Diag(Redecl->getLocation(), diag::note_previous_use);
14565 
14566     // If there is a previous definition, suggest a fix-it.
14567     if (PrevDef) {
14568       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14569         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14570         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14571              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14572     }
14573   }
14574 
14575   return true;
14576 }
14577 
14578 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14579 /// from an outer enclosing namespace or file scope inside a friend declaration.
14580 /// This should provide the commented out code in the following snippet:
14581 ///   namespace N {
14582 ///     struct X;
14583 ///     namespace M {
14584 ///       struct Y { friend struct /*N::*/ X; };
14585 ///     }
14586 ///   }
14587 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14588                                          SourceLocation NameLoc) {
14589   // While the decl is in a namespace, do repeated lookup of that name and see
14590   // if we get the same namespace back.  If we do not, continue until
14591   // translation unit scope, at which point we have a fully qualified NNS.
14592   SmallVector<IdentifierInfo *, 4> Namespaces;
14593   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14594   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14595     // This tag should be declared in a namespace, which can only be enclosed by
14596     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14597     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14598     if (!Namespace || Namespace->isAnonymousNamespace())
14599       return FixItHint();
14600     IdentifierInfo *II = Namespace->getIdentifier();
14601     Namespaces.push_back(II);
14602     NamedDecl *Lookup = SemaRef.LookupSingleName(
14603         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14604     if (Lookup == Namespace)
14605       break;
14606   }
14607 
14608   // Once we have all the namespaces, reverse them to go outermost first, and
14609   // build an NNS.
14610   SmallString<64> Insertion;
14611   llvm::raw_svector_ostream OS(Insertion);
14612   if (DC->isTranslationUnit())
14613     OS << "::";
14614   std::reverse(Namespaces.begin(), Namespaces.end());
14615   for (auto *II : Namespaces)
14616     OS << II->getName() << "::";
14617   return FixItHint::CreateInsertion(NameLoc, Insertion);
14618 }
14619 
14620 /// Determine whether a tag originally declared in context \p OldDC can
14621 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14622 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14623 /// using-declaration).
14624 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14625                                          DeclContext *NewDC) {
14626   OldDC = OldDC->getRedeclContext();
14627   NewDC = NewDC->getRedeclContext();
14628 
14629   if (OldDC->Equals(NewDC))
14630     return true;
14631 
14632   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14633   // encloses the other).
14634   if (S.getLangOpts().MSVCCompat &&
14635       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14636     return true;
14637 
14638   return false;
14639 }
14640 
14641 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14642 /// former case, Name will be non-null.  In the later case, Name will be null.
14643 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14644 /// reference/declaration/definition of a tag.
14645 ///
14646 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14647 /// trailing-type-specifier) other than one in an alias-declaration.
14648 ///
14649 /// \param SkipBody If non-null, will be set to indicate if the caller should
14650 /// skip the definition of this tag and treat it as if it were a declaration.
14651 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14652                      SourceLocation KWLoc, CXXScopeSpec &SS,
14653                      IdentifierInfo *Name, SourceLocation NameLoc,
14654                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14655                      SourceLocation ModulePrivateLoc,
14656                      MultiTemplateParamsArg TemplateParameterLists,
14657                      bool &OwnedDecl, bool &IsDependent,
14658                      SourceLocation ScopedEnumKWLoc,
14659                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14660                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14661                      SkipBodyInfo *SkipBody) {
14662   // If this is not a definition, it must have a name.
14663   IdentifierInfo *OrigName = Name;
14664   assert((Name != nullptr || TUK == TUK_Definition) &&
14665          "Nameless record must be a definition!");
14666   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14667 
14668   OwnedDecl = false;
14669   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14670   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14671 
14672   // FIXME: Check member specializations more carefully.
14673   bool isMemberSpecialization = false;
14674   bool Invalid = false;
14675 
14676   // We only need to do this matching if we have template parameters
14677   // or a scope specifier, which also conveniently avoids this work
14678   // for non-C++ cases.
14679   if (TemplateParameterLists.size() > 0 ||
14680       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14681     if (TemplateParameterList *TemplateParams =
14682             MatchTemplateParametersToScopeSpecifier(
14683                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14684                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14685       if (Kind == TTK_Enum) {
14686         Diag(KWLoc, diag::err_enum_template);
14687         return nullptr;
14688       }
14689 
14690       if (TemplateParams->size() > 0) {
14691         // This is a declaration or definition of a class template (which may
14692         // be a member of another template).
14693 
14694         if (Invalid)
14695           return nullptr;
14696 
14697         OwnedDecl = false;
14698         DeclResult Result = CheckClassTemplate(
14699             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14700             AS, ModulePrivateLoc,
14701             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14702             TemplateParameterLists.data(), SkipBody);
14703         return Result.get();
14704       } else {
14705         // The "template<>" header is extraneous.
14706         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14707           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14708         isMemberSpecialization = true;
14709       }
14710     }
14711   }
14712 
14713   // Figure out the underlying type if this a enum declaration. We need to do
14714   // this early, because it's needed to detect if this is an incompatible
14715   // redeclaration.
14716   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14717   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14718 
14719   if (Kind == TTK_Enum) {
14720     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14721       // No underlying type explicitly specified, or we failed to parse the
14722       // type, default to int.
14723       EnumUnderlying = Context.IntTy.getTypePtr();
14724     } else if (UnderlyingType.get()) {
14725       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14726       // integral type; any cv-qualification is ignored.
14727       TypeSourceInfo *TI = nullptr;
14728       GetTypeFromParser(UnderlyingType.get(), &TI);
14729       EnumUnderlying = TI;
14730 
14731       if (CheckEnumUnderlyingType(TI))
14732         // Recover by falling back to int.
14733         EnumUnderlying = Context.IntTy.getTypePtr();
14734 
14735       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14736                                           UPPC_FixedUnderlyingType))
14737         EnumUnderlying = Context.IntTy.getTypePtr();
14738 
14739     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14740       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14741       // of 'int'. However, if this is an unfixed forward declaration, don't set
14742       // the underlying type unless the user enables -fms-compatibility. This
14743       // makes unfixed forward declared enums incomplete and is more conforming.
14744       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14745         EnumUnderlying = Context.IntTy.getTypePtr();
14746     }
14747   }
14748 
14749   DeclContext *SearchDC = CurContext;
14750   DeclContext *DC = CurContext;
14751   bool isStdBadAlloc = false;
14752   bool isStdAlignValT = false;
14753 
14754   RedeclarationKind Redecl = forRedeclarationInCurContext();
14755   if (TUK == TUK_Friend || TUK == TUK_Reference)
14756     Redecl = NotForRedeclaration;
14757 
14758   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14759   /// implemented asks for structural equivalence checking, the returned decl
14760   /// here is passed back to the parser, allowing the tag body to be parsed.
14761   auto createTagFromNewDecl = [&]() -> TagDecl * {
14762     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14763     // If there is an identifier, use the location of the identifier as the
14764     // location of the decl, otherwise use the location of the struct/union
14765     // keyword.
14766     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14767     TagDecl *New = nullptr;
14768 
14769     if (Kind == TTK_Enum) {
14770       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14771                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14772       // If this is an undefined enum, bail.
14773       if (TUK != TUK_Definition && !Invalid)
14774         return nullptr;
14775       if (EnumUnderlying) {
14776         EnumDecl *ED = cast<EnumDecl>(New);
14777         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14778           ED->setIntegerTypeSourceInfo(TI);
14779         else
14780           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14781         ED->setPromotionType(ED->getIntegerType());
14782       }
14783     } else { // struct/union
14784       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14785                                nullptr);
14786     }
14787 
14788     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14789       // Add alignment attributes if necessary; these attributes are checked
14790       // when the ASTContext lays out the structure.
14791       //
14792       // It is important for implementing the correct semantics that this
14793       // happen here (in ActOnTag). The #pragma pack stack is
14794       // maintained as a result of parser callbacks which can occur at
14795       // many points during the parsing of a struct declaration (because
14796       // the #pragma tokens are effectively skipped over during the
14797       // parsing of the struct).
14798       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14799         AddAlignmentAttributesForRecord(RD);
14800         AddMsStructLayoutForRecord(RD);
14801       }
14802     }
14803     New->setLexicalDeclContext(CurContext);
14804     return New;
14805   };
14806 
14807   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14808   if (Name && SS.isNotEmpty()) {
14809     // We have a nested-name tag ('struct foo::bar').
14810 
14811     // Check for invalid 'foo::'.
14812     if (SS.isInvalid()) {
14813       Name = nullptr;
14814       goto CreateNewDecl;
14815     }
14816 
14817     // If this is a friend or a reference to a class in a dependent
14818     // context, don't try to make a decl for it.
14819     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14820       DC = computeDeclContext(SS, false);
14821       if (!DC) {
14822         IsDependent = true;
14823         return nullptr;
14824       }
14825     } else {
14826       DC = computeDeclContext(SS, true);
14827       if (!DC) {
14828         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14829           << SS.getRange();
14830         return nullptr;
14831       }
14832     }
14833 
14834     if (RequireCompleteDeclContext(SS, DC))
14835       return nullptr;
14836 
14837     SearchDC = DC;
14838     // Look-up name inside 'foo::'.
14839     LookupQualifiedName(Previous, DC);
14840 
14841     if (Previous.isAmbiguous())
14842       return nullptr;
14843 
14844     if (Previous.empty()) {
14845       // Name lookup did not find anything. However, if the
14846       // nested-name-specifier refers to the current instantiation,
14847       // and that current instantiation has any dependent base
14848       // classes, we might find something at instantiation time: treat
14849       // this as a dependent elaborated-type-specifier.
14850       // But this only makes any sense for reference-like lookups.
14851       if (Previous.wasNotFoundInCurrentInstantiation() &&
14852           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14853         IsDependent = true;
14854         return nullptr;
14855       }
14856 
14857       // A tag 'foo::bar' must already exist.
14858       Diag(NameLoc, diag::err_not_tag_in_scope)
14859         << Kind << Name << DC << SS.getRange();
14860       Name = nullptr;
14861       Invalid = true;
14862       goto CreateNewDecl;
14863     }
14864   } else if (Name) {
14865     // C++14 [class.mem]p14:
14866     //   If T is the name of a class, then each of the following shall have a
14867     //   name different from T:
14868     //    -- every member of class T that is itself a type
14869     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14870         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14871       return nullptr;
14872 
14873     // If this is a named struct, check to see if there was a previous forward
14874     // declaration or definition.
14875     // FIXME: We're looking into outer scopes here, even when we
14876     // shouldn't be. Doing so can result in ambiguities that we
14877     // shouldn't be diagnosing.
14878     LookupName(Previous, S);
14879 
14880     // When declaring or defining a tag, ignore ambiguities introduced
14881     // by types using'ed into this scope.
14882     if (Previous.isAmbiguous() &&
14883         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14884       LookupResult::Filter F = Previous.makeFilter();
14885       while (F.hasNext()) {
14886         NamedDecl *ND = F.next();
14887         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14888                 SearchDC->getRedeclContext()))
14889           F.erase();
14890       }
14891       F.done();
14892     }
14893 
14894     // C++11 [namespace.memdef]p3:
14895     //   If the name in a friend declaration is neither qualified nor
14896     //   a template-id and the declaration is a function or an
14897     //   elaborated-type-specifier, the lookup to determine whether
14898     //   the entity has been previously declared shall not consider
14899     //   any scopes outside the innermost enclosing namespace.
14900     //
14901     // MSVC doesn't implement the above rule for types, so a friend tag
14902     // declaration may be a redeclaration of a type declared in an enclosing
14903     // scope.  They do implement this rule for friend functions.
14904     //
14905     // Does it matter that this should be by scope instead of by
14906     // semantic context?
14907     if (!Previous.empty() && TUK == TUK_Friend) {
14908       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14909       LookupResult::Filter F = Previous.makeFilter();
14910       bool FriendSawTagOutsideEnclosingNamespace = false;
14911       while (F.hasNext()) {
14912         NamedDecl *ND = F.next();
14913         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14914         if (DC->isFileContext() &&
14915             !EnclosingNS->Encloses(ND->getDeclContext())) {
14916           if (getLangOpts().MSVCCompat)
14917             FriendSawTagOutsideEnclosingNamespace = true;
14918           else
14919             F.erase();
14920         }
14921       }
14922       F.done();
14923 
14924       // Diagnose this MSVC extension in the easy case where lookup would have
14925       // unambiguously found something outside the enclosing namespace.
14926       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14927         NamedDecl *ND = Previous.getFoundDecl();
14928         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14929             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14930       }
14931     }
14932 
14933     // Note:  there used to be some attempt at recovery here.
14934     if (Previous.isAmbiguous())
14935       return nullptr;
14936 
14937     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14938       // FIXME: This makes sure that we ignore the contexts associated
14939       // with C structs, unions, and enums when looking for a matching
14940       // tag declaration or definition. See the similar lookup tweak
14941       // in Sema::LookupName; is there a better way to deal with this?
14942       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14943         SearchDC = SearchDC->getParent();
14944     }
14945   }
14946 
14947   if (Previous.isSingleResult() &&
14948       Previous.getFoundDecl()->isTemplateParameter()) {
14949     // Maybe we will complain about the shadowed template parameter.
14950     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14951     // Just pretend that we didn't see the previous declaration.
14952     Previous.clear();
14953   }
14954 
14955   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14956       DC->Equals(getStdNamespace())) {
14957     if (Name->isStr("bad_alloc")) {
14958       // This is a declaration of or a reference to "std::bad_alloc".
14959       isStdBadAlloc = true;
14960 
14961       // If std::bad_alloc has been implicitly declared (but made invisible to
14962       // name lookup), fill in this implicit declaration as the previous
14963       // declaration, so that the declarations get chained appropriately.
14964       if (Previous.empty() && StdBadAlloc)
14965         Previous.addDecl(getStdBadAlloc());
14966     } else if (Name->isStr("align_val_t")) {
14967       isStdAlignValT = true;
14968       if (Previous.empty() && StdAlignValT)
14969         Previous.addDecl(getStdAlignValT());
14970     }
14971   }
14972 
14973   // If we didn't find a previous declaration, and this is a reference
14974   // (or friend reference), move to the correct scope.  In C++, we
14975   // also need to do a redeclaration lookup there, just in case
14976   // there's a shadow friend decl.
14977   if (Name && Previous.empty() &&
14978       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14979     if (Invalid) goto CreateNewDecl;
14980     assert(SS.isEmpty());
14981 
14982     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14983       // C++ [basic.scope.pdecl]p5:
14984       //   -- for an elaborated-type-specifier of the form
14985       //
14986       //          class-key identifier
14987       //
14988       //      if the elaborated-type-specifier is used in the
14989       //      decl-specifier-seq or parameter-declaration-clause of a
14990       //      function defined in namespace scope, the identifier is
14991       //      declared as a class-name in the namespace that contains
14992       //      the declaration; otherwise, except as a friend
14993       //      declaration, the identifier is declared in the smallest
14994       //      non-class, non-function-prototype scope that contains the
14995       //      declaration.
14996       //
14997       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14998       // C structs and unions.
14999       //
15000       // It is an error in C++ to declare (rather than define) an enum
15001       // type, including via an elaborated type specifier.  We'll
15002       // diagnose that later; for now, declare the enum in the same
15003       // scope as we would have picked for any other tag type.
15004       //
15005       // GNU C also supports this behavior as part of its incomplete
15006       // enum types extension, while GNU C++ does not.
15007       //
15008       // Find the context where we'll be declaring the tag.
15009       // FIXME: We would like to maintain the current DeclContext as the
15010       // lexical context,
15011       SearchDC = getTagInjectionContext(SearchDC);
15012 
15013       // Find the scope where we'll be declaring the tag.
15014       S = getTagInjectionScope(S, getLangOpts());
15015     } else {
15016       assert(TUK == TUK_Friend);
15017       // C++ [namespace.memdef]p3:
15018       //   If a friend declaration in a non-local class first declares a
15019       //   class or function, the friend class or function is a member of
15020       //   the innermost enclosing namespace.
15021       SearchDC = SearchDC->getEnclosingNamespaceContext();
15022     }
15023 
15024     // In C++, we need to do a redeclaration lookup to properly
15025     // diagnose some problems.
15026     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15027     // hidden declaration so that we don't get ambiguity errors when using a
15028     // type declared by an elaborated-type-specifier.  In C that is not correct
15029     // and we should instead merge compatible types found by lookup.
15030     if (getLangOpts().CPlusPlus) {
15031       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15032       LookupQualifiedName(Previous, SearchDC);
15033     } else {
15034       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15035       LookupName(Previous, S);
15036     }
15037   }
15038 
15039   // If we have a known previous declaration to use, then use it.
15040   if (Previous.empty() && SkipBody && SkipBody->Previous)
15041     Previous.addDecl(SkipBody->Previous);
15042 
15043   if (!Previous.empty()) {
15044     NamedDecl *PrevDecl = Previous.getFoundDecl();
15045     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15046 
15047     // It's okay to have a tag decl in the same scope as a typedef
15048     // which hides a tag decl in the same scope.  Finding this
15049     // insanity with a redeclaration lookup can only actually happen
15050     // in C++.
15051     //
15052     // This is also okay for elaborated-type-specifiers, which is
15053     // technically forbidden by the current standard but which is
15054     // okay according to the likely resolution of an open issue;
15055     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15056     if (getLangOpts().CPlusPlus) {
15057       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15058         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15059           TagDecl *Tag = TT->getDecl();
15060           if (Tag->getDeclName() == Name &&
15061               Tag->getDeclContext()->getRedeclContext()
15062                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15063             PrevDecl = Tag;
15064             Previous.clear();
15065             Previous.addDecl(Tag);
15066             Previous.resolveKind();
15067           }
15068         }
15069       }
15070     }
15071 
15072     // If this is a redeclaration of a using shadow declaration, it must
15073     // declare a tag in the same context. In MSVC mode, we allow a
15074     // redefinition if either context is within the other.
15075     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15076       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15077       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15078           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15079           !(OldTag && isAcceptableTagRedeclContext(
15080                           *this, OldTag->getDeclContext(), SearchDC))) {
15081         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15082         Diag(Shadow->getTargetDecl()->getLocation(),
15083              diag::note_using_decl_target);
15084         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15085             << 0;
15086         // Recover by ignoring the old declaration.
15087         Previous.clear();
15088         goto CreateNewDecl;
15089       }
15090     }
15091 
15092     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15093       // If this is a use of a previous tag, or if the tag is already declared
15094       // in the same scope (so that the definition/declaration completes or
15095       // rementions the tag), reuse the decl.
15096       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15097           isDeclInScope(DirectPrevDecl, SearchDC, S,
15098                         SS.isNotEmpty() || isMemberSpecialization)) {
15099         // Make sure that this wasn't declared as an enum and now used as a
15100         // struct or something similar.
15101         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15102                                           TUK == TUK_Definition, KWLoc,
15103                                           Name)) {
15104           bool SafeToContinue
15105             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15106                Kind != TTK_Enum);
15107           if (SafeToContinue)
15108             Diag(KWLoc, diag::err_use_with_wrong_tag)
15109               << Name
15110               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15111                                               PrevTagDecl->getKindName());
15112           else
15113             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15114           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15115 
15116           if (SafeToContinue)
15117             Kind = PrevTagDecl->getTagKind();
15118           else {
15119             // Recover by making this an anonymous redefinition.
15120             Name = nullptr;
15121             Previous.clear();
15122             Invalid = true;
15123           }
15124         }
15125 
15126         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15127           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15128 
15129           // If this is an elaborated-type-specifier for a scoped enumeration,
15130           // the 'class' keyword is not necessary and not permitted.
15131           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15132             if (ScopedEnum)
15133               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15134                 << PrevEnum->isScoped()
15135                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15136             return PrevTagDecl;
15137           }
15138 
15139           QualType EnumUnderlyingTy;
15140           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15141             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15142           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15143             EnumUnderlyingTy = QualType(T, 0);
15144 
15145           // All conflicts with previous declarations are recovered by
15146           // returning the previous declaration, unless this is a definition,
15147           // in which case we want the caller to bail out.
15148           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15149                                      ScopedEnum, EnumUnderlyingTy,
15150                                      IsFixed, PrevEnum))
15151             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15152         }
15153 
15154         // C++11 [class.mem]p1:
15155         //   A member shall not be declared twice in the member-specification,
15156         //   except that a nested class or member class template can be declared
15157         //   and then later defined.
15158         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15159             S->isDeclScope(PrevDecl)) {
15160           Diag(NameLoc, diag::ext_member_redeclared);
15161           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15162         }
15163 
15164         if (!Invalid) {
15165           // If this is a use, just return the declaration we found, unless
15166           // we have attributes.
15167           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15168             if (!Attrs.empty()) {
15169               // FIXME: Diagnose these attributes. For now, we create a new
15170               // declaration to hold them.
15171             } else if (TUK == TUK_Reference &&
15172                        (PrevTagDecl->getFriendObjectKind() ==
15173                             Decl::FOK_Undeclared ||
15174                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15175                        SS.isEmpty()) {
15176               // This declaration is a reference to an existing entity, but
15177               // has different visibility from that entity: it either makes
15178               // a friend visible or it makes a type visible in a new module.
15179               // In either case, create a new declaration. We only do this if
15180               // the declaration would have meant the same thing if no prior
15181               // declaration were found, that is, if it was found in the same
15182               // scope where we would have injected a declaration.
15183               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15184                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15185                 return PrevTagDecl;
15186               // This is in the injected scope, create a new declaration in
15187               // that scope.
15188               S = getTagInjectionScope(S, getLangOpts());
15189             } else {
15190               return PrevTagDecl;
15191             }
15192           }
15193 
15194           // Diagnose attempts to redefine a tag.
15195           if (TUK == TUK_Definition) {
15196             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15197               // If we're defining a specialization and the previous definition
15198               // is from an implicit instantiation, don't emit an error
15199               // here; we'll catch this in the general case below.
15200               bool IsExplicitSpecializationAfterInstantiation = false;
15201               if (isMemberSpecialization) {
15202                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15203                   IsExplicitSpecializationAfterInstantiation =
15204                     RD->getTemplateSpecializationKind() !=
15205                     TSK_ExplicitSpecialization;
15206                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15207                   IsExplicitSpecializationAfterInstantiation =
15208                     ED->getTemplateSpecializationKind() !=
15209                     TSK_ExplicitSpecialization;
15210               }
15211 
15212               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15213               // not keep more that one definition around (merge them). However,
15214               // ensure the decl passes the structural compatibility check in
15215               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15216               NamedDecl *Hidden = nullptr;
15217               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15218                 // There is a definition of this tag, but it is not visible. We
15219                 // explicitly make use of C++'s one definition rule here, and
15220                 // assume that this definition is identical to the hidden one
15221                 // we already have. Make the existing definition visible and
15222                 // use it in place of this one.
15223                 if (!getLangOpts().CPlusPlus) {
15224                   // Postpone making the old definition visible until after we
15225                   // complete parsing the new one and do the structural
15226                   // comparison.
15227                   SkipBody->CheckSameAsPrevious = true;
15228                   SkipBody->New = createTagFromNewDecl();
15229                   SkipBody->Previous = Def;
15230                   return Def;
15231                 } else {
15232                   SkipBody->ShouldSkip = true;
15233                   SkipBody->Previous = Def;
15234                   makeMergedDefinitionVisible(Hidden);
15235                   // Carry on and handle it like a normal definition. We'll
15236                   // skip starting the definitiion later.
15237                 }
15238               } else if (!IsExplicitSpecializationAfterInstantiation) {
15239                 // A redeclaration in function prototype scope in C isn't
15240                 // visible elsewhere, so merely issue a warning.
15241                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15242                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15243                 else
15244                   Diag(NameLoc, diag::err_redefinition) << Name;
15245                 notePreviousDefinition(Def,
15246                                        NameLoc.isValid() ? NameLoc : KWLoc);
15247                 // If this is a redefinition, recover by making this
15248                 // struct be anonymous, which will make any later
15249                 // references get the previous definition.
15250                 Name = nullptr;
15251                 Previous.clear();
15252                 Invalid = true;
15253               }
15254             } else {
15255               // If the type is currently being defined, complain
15256               // about a nested redefinition.
15257               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15258               if (TD->isBeingDefined()) {
15259                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15260                 Diag(PrevTagDecl->getLocation(),
15261                      diag::note_previous_definition);
15262                 Name = nullptr;
15263                 Previous.clear();
15264                 Invalid = true;
15265               }
15266             }
15267 
15268             // Okay, this is definition of a previously declared or referenced
15269             // tag. We're going to create a new Decl for it.
15270           }
15271 
15272           // Okay, we're going to make a redeclaration.  If this is some kind
15273           // of reference, make sure we build the redeclaration in the same DC
15274           // as the original, and ignore the current access specifier.
15275           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15276             SearchDC = PrevTagDecl->getDeclContext();
15277             AS = AS_none;
15278           }
15279         }
15280         // If we get here we have (another) forward declaration or we
15281         // have a definition.  Just create a new decl.
15282 
15283       } else {
15284         // If we get here, this is a definition of a new tag type in a nested
15285         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15286         // new decl/type.  We set PrevDecl to NULL so that the entities
15287         // have distinct types.
15288         Previous.clear();
15289       }
15290       // If we get here, we're going to create a new Decl. If PrevDecl
15291       // is non-NULL, it's a definition of the tag declared by
15292       // PrevDecl. If it's NULL, we have a new definition.
15293 
15294     // Otherwise, PrevDecl is not a tag, but was found with tag
15295     // lookup.  This is only actually possible in C++, where a few
15296     // things like templates still live in the tag namespace.
15297     } else {
15298       // Use a better diagnostic if an elaborated-type-specifier
15299       // found the wrong kind of type on the first
15300       // (non-redeclaration) lookup.
15301       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15302           !Previous.isForRedeclaration()) {
15303         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15304         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15305                                                        << Kind;
15306         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15307         Invalid = true;
15308 
15309       // Otherwise, only diagnose if the declaration is in scope.
15310       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15311                                 SS.isNotEmpty() || isMemberSpecialization)) {
15312         // do nothing
15313 
15314       // Diagnose implicit declarations introduced by elaborated types.
15315       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15316         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15317         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15318         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15319         Invalid = true;
15320 
15321       // Otherwise it's a declaration.  Call out a particularly common
15322       // case here.
15323       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15324         unsigned Kind = 0;
15325         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15326         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15327           << Name << Kind << TND->getUnderlyingType();
15328         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15329         Invalid = true;
15330 
15331       // Otherwise, diagnose.
15332       } else {
15333         // The tag name clashes with something else in the target scope,
15334         // issue an error and recover by making this tag be anonymous.
15335         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15336         notePreviousDefinition(PrevDecl, NameLoc);
15337         Name = nullptr;
15338         Invalid = true;
15339       }
15340 
15341       // The existing declaration isn't relevant to us; we're in a
15342       // new scope, so clear out the previous declaration.
15343       Previous.clear();
15344     }
15345   }
15346 
15347 CreateNewDecl:
15348 
15349   TagDecl *PrevDecl = nullptr;
15350   if (Previous.isSingleResult())
15351     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15352 
15353   // If there is an identifier, use the location of the identifier as the
15354   // location of the decl, otherwise use the location of the struct/union
15355   // keyword.
15356   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15357 
15358   // Otherwise, create a new declaration. If there is a previous
15359   // declaration of the same entity, the two will be linked via
15360   // PrevDecl.
15361   TagDecl *New;
15362 
15363   if (Kind == TTK_Enum) {
15364     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15365     // enum X { A, B, C } D;    D should chain to X.
15366     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15367                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15368                            ScopedEnumUsesClassTag, IsFixed);
15369 
15370     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15371       StdAlignValT = cast<EnumDecl>(New);
15372 
15373     // If this is an undefined enum, warn.
15374     if (TUK != TUK_Definition && !Invalid) {
15375       TagDecl *Def;
15376       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15377         // C++0x: 7.2p2: opaque-enum-declaration.
15378         // Conflicts are diagnosed above. Do nothing.
15379       }
15380       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15381         Diag(Loc, diag::ext_forward_ref_enum_def)
15382           << New;
15383         Diag(Def->getLocation(), diag::note_previous_definition);
15384       } else {
15385         unsigned DiagID = diag::ext_forward_ref_enum;
15386         if (getLangOpts().MSVCCompat)
15387           DiagID = diag::ext_ms_forward_ref_enum;
15388         else if (getLangOpts().CPlusPlus)
15389           DiagID = diag::err_forward_ref_enum;
15390         Diag(Loc, DiagID);
15391       }
15392     }
15393 
15394     if (EnumUnderlying) {
15395       EnumDecl *ED = cast<EnumDecl>(New);
15396       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15397         ED->setIntegerTypeSourceInfo(TI);
15398       else
15399         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15400       ED->setPromotionType(ED->getIntegerType());
15401       assert(ED->isComplete() && "enum with type should be complete");
15402     }
15403   } else {
15404     // struct/union/class
15405 
15406     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15407     // struct X { int A; } D;    D should chain to X.
15408     if (getLangOpts().CPlusPlus) {
15409       // FIXME: Look for a way to use RecordDecl for simple structs.
15410       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15411                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15412 
15413       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15414         StdBadAlloc = cast<CXXRecordDecl>(New);
15415     } else
15416       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15417                                cast_or_null<RecordDecl>(PrevDecl));
15418   }
15419 
15420   // C++11 [dcl.type]p3:
15421   //   A type-specifier-seq shall not define a class or enumeration [...].
15422   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15423       TUK == TUK_Definition) {
15424     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15425       << Context.getTagDeclType(New);
15426     Invalid = true;
15427   }
15428 
15429   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15430       DC->getDeclKind() == Decl::Enum) {
15431     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15432       << Context.getTagDeclType(New);
15433     Invalid = true;
15434   }
15435 
15436   // Maybe add qualifier info.
15437   if (SS.isNotEmpty()) {
15438     if (SS.isSet()) {
15439       // If this is either a declaration or a definition, check the
15440       // nested-name-specifier against the current context.
15441       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15442           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15443                                        isMemberSpecialization))
15444         Invalid = true;
15445 
15446       New->setQualifierInfo(SS.getWithLocInContext(Context));
15447       if (TemplateParameterLists.size() > 0) {
15448         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15449       }
15450     }
15451     else
15452       Invalid = true;
15453   }
15454 
15455   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15456     // Add alignment attributes if necessary; these attributes are checked when
15457     // the ASTContext lays out the structure.
15458     //
15459     // It is important for implementing the correct semantics that this
15460     // happen here (in ActOnTag). The #pragma pack stack is
15461     // maintained as a result of parser callbacks which can occur at
15462     // many points during the parsing of a struct declaration (because
15463     // the #pragma tokens are effectively skipped over during the
15464     // parsing of the struct).
15465     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15466       AddAlignmentAttributesForRecord(RD);
15467       AddMsStructLayoutForRecord(RD);
15468     }
15469   }
15470 
15471   if (ModulePrivateLoc.isValid()) {
15472     if (isMemberSpecialization)
15473       Diag(New->getLocation(), diag::err_module_private_specialization)
15474         << 2
15475         << FixItHint::CreateRemoval(ModulePrivateLoc);
15476     // __module_private__ does not apply to local classes. However, we only
15477     // diagnose this as an error when the declaration specifiers are
15478     // freestanding. Here, we just ignore the __module_private__.
15479     else if (!SearchDC->isFunctionOrMethod())
15480       New->setModulePrivate();
15481   }
15482 
15483   // If this is a specialization of a member class (of a class template),
15484   // check the specialization.
15485   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15486     Invalid = true;
15487 
15488   // If we're declaring or defining a tag in function prototype scope in C,
15489   // note that this type can only be used within the function and add it to
15490   // the list of decls to inject into the function definition scope.
15491   if ((Name || Kind == TTK_Enum) &&
15492       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15493     if (getLangOpts().CPlusPlus) {
15494       // C++ [dcl.fct]p6:
15495       //   Types shall not be defined in return or parameter types.
15496       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15497         Diag(Loc, diag::err_type_defined_in_param_type)
15498             << Name;
15499         Invalid = true;
15500       }
15501     } else if (!PrevDecl) {
15502       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15503     }
15504   }
15505 
15506   if (Invalid)
15507     New->setInvalidDecl();
15508 
15509   // Set the lexical context. If the tag has a C++ scope specifier, the
15510   // lexical context will be different from the semantic context.
15511   New->setLexicalDeclContext(CurContext);
15512 
15513   // Mark this as a friend decl if applicable.
15514   // In Microsoft mode, a friend declaration also acts as a forward
15515   // declaration so we always pass true to setObjectOfFriendDecl to make
15516   // the tag name visible.
15517   if (TUK == TUK_Friend)
15518     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15519 
15520   // Set the access specifier.
15521   if (!Invalid && SearchDC->isRecord())
15522     SetMemberAccessSpecifier(New, PrevDecl, AS);
15523 
15524   if (PrevDecl)
15525     CheckRedeclarationModuleOwnership(New, PrevDecl);
15526 
15527   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15528     New->startDefinition();
15529 
15530   ProcessDeclAttributeList(S, New, Attrs);
15531   AddPragmaAttributes(S, New);
15532 
15533   // If this has an identifier, add it to the scope stack.
15534   if (TUK == TUK_Friend) {
15535     // We might be replacing an existing declaration in the lookup tables;
15536     // if so, borrow its access specifier.
15537     if (PrevDecl)
15538       New->setAccess(PrevDecl->getAccess());
15539 
15540     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15541     DC->makeDeclVisibleInContext(New);
15542     if (Name) // can be null along some error paths
15543       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15544         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15545   } else if (Name) {
15546     S = getNonFieldDeclScope(S);
15547     PushOnScopeChains(New, S, true);
15548   } else {
15549     CurContext->addDecl(New);
15550   }
15551 
15552   // If this is the C FILE type, notify the AST context.
15553   if (IdentifierInfo *II = New->getIdentifier())
15554     if (!New->isInvalidDecl() &&
15555         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15556         II->isStr("FILE"))
15557       Context.setFILEDecl(New);
15558 
15559   if (PrevDecl)
15560     mergeDeclAttributes(New, PrevDecl);
15561 
15562   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15563     inferGslOwnerPointerAttribute(CXXRD);
15564 
15565   // If there's a #pragma GCC visibility in scope, set the visibility of this
15566   // record.
15567   AddPushedVisibilityAttribute(New);
15568 
15569   if (isMemberSpecialization && !New->isInvalidDecl())
15570     CompleteMemberSpecialization(New, Previous);
15571 
15572   OwnedDecl = true;
15573   // In C++, don't return an invalid declaration. We can't recover well from
15574   // the cases where we make the type anonymous.
15575   if (Invalid && getLangOpts().CPlusPlus) {
15576     if (New->isBeingDefined())
15577       if (auto RD = dyn_cast<RecordDecl>(New))
15578         RD->completeDefinition();
15579     return nullptr;
15580   } else if (SkipBody && SkipBody->ShouldSkip) {
15581     return SkipBody->Previous;
15582   } else {
15583     return New;
15584   }
15585 }
15586 
15587 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15588   AdjustDeclIfTemplate(TagD);
15589   TagDecl *Tag = cast<TagDecl>(TagD);
15590 
15591   // Enter the tag context.
15592   PushDeclContext(S, Tag);
15593 
15594   ActOnDocumentableDecl(TagD);
15595 
15596   // If there's a #pragma GCC visibility in scope, set the visibility of this
15597   // record.
15598   AddPushedVisibilityAttribute(Tag);
15599 }
15600 
15601 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15602                                     SkipBodyInfo &SkipBody) {
15603   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15604     return false;
15605 
15606   // Make the previous decl visible.
15607   makeMergedDefinitionVisible(SkipBody.Previous);
15608   return true;
15609 }
15610 
15611 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15612   assert(isa<ObjCContainerDecl>(IDecl) &&
15613          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15614   DeclContext *OCD = cast<DeclContext>(IDecl);
15615   assert(getContainingDC(OCD) == CurContext &&
15616       "The next DeclContext should be lexically contained in the current one.");
15617   CurContext = OCD;
15618   return IDecl;
15619 }
15620 
15621 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15622                                            SourceLocation FinalLoc,
15623                                            bool IsFinalSpelledSealed,
15624                                            SourceLocation LBraceLoc) {
15625   AdjustDeclIfTemplate(TagD);
15626   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15627 
15628   FieldCollector->StartClass();
15629 
15630   if (!Record->getIdentifier())
15631     return;
15632 
15633   if (FinalLoc.isValid())
15634     Record->addAttr(FinalAttr::Create(
15635         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15636         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15637 
15638   // C++ [class]p2:
15639   //   [...] The class-name is also inserted into the scope of the
15640   //   class itself; this is known as the injected-class-name. For
15641   //   purposes of access checking, the injected-class-name is treated
15642   //   as if it were a public member name.
15643   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15644       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15645       Record->getLocation(), Record->getIdentifier(),
15646       /*PrevDecl=*/nullptr,
15647       /*DelayTypeCreation=*/true);
15648   Context.getTypeDeclType(InjectedClassName, Record);
15649   InjectedClassName->setImplicit();
15650   InjectedClassName->setAccess(AS_public);
15651   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15652       InjectedClassName->setDescribedClassTemplate(Template);
15653   PushOnScopeChains(InjectedClassName, S);
15654   assert(InjectedClassName->isInjectedClassName() &&
15655          "Broken injected-class-name");
15656 }
15657 
15658 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15659                                     SourceRange BraceRange) {
15660   AdjustDeclIfTemplate(TagD);
15661   TagDecl *Tag = cast<TagDecl>(TagD);
15662   Tag->setBraceRange(BraceRange);
15663 
15664   // Make sure we "complete" the definition even it is invalid.
15665   if (Tag->isBeingDefined()) {
15666     assert(Tag->isInvalidDecl() && "We should already have completed it");
15667     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15668       RD->completeDefinition();
15669   }
15670 
15671   if (isa<CXXRecordDecl>(Tag)) {
15672     FieldCollector->FinishClass();
15673   }
15674 
15675   // Exit this scope of this tag's definition.
15676   PopDeclContext();
15677 
15678   if (getCurLexicalContext()->isObjCContainer() &&
15679       Tag->getDeclContext()->isFileContext())
15680     Tag->setTopLevelDeclInObjCContainer();
15681 
15682   // Notify the consumer that we've defined a tag.
15683   if (!Tag->isInvalidDecl())
15684     Consumer.HandleTagDeclDefinition(Tag);
15685 }
15686 
15687 void Sema::ActOnObjCContainerFinishDefinition() {
15688   // Exit this scope of this interface definition.
15689   PopDeclContext();
15690 }
15691 
15692 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15693   assert(DC == CurContext && "Mismatch of container contexts");
15694   OriginalLexicalContext = DC;
15695   ActOnObjCContainerFinishDefinition();
15696 }
15697 
15698 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15699   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15700   OriginalLexicalContext = nullptr;
15701 }
15702 
15703 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15704   AdjustDeclIfTemplate(TagD);
15705   TagDecl *Tag = cast<TagDecl>(TagD);
15706   Tag->setInvalidDecl();
15707 
15708   // Make sure we "complete" the definition even it is invalid.
15709   if (Tag->isBeingDefined()) {
15710     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15711       RD->completeDefinition();
15712   }
15713 
15714   // We're undoing ActOnTagStartDefinition here, not
15715   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15716   // the FieldCollector.
15717 
15718   PopDeclContext();
15719 }
15720 
15721 // Note that FieldName may be null for anonymous bitfields.
15722 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15723                                 IdentifierInfo *FieldName,
15724                                 QualType FieldTy, bool IsMsStruct,
15725                                 Expr *BitWidth, bool *ZeroWidth) {
15726   // Default to true; that shouldn't confuse checks for emptiness
15727   if (ZeroWidth)
15728     *ZeroWidth = true;
15729 
15730   // C99 6.7.2.1p4 - verify the field type.
15731   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15732   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15733     // Handle incomplete types with specific error.
15734     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15735       return ExprError();
15736     if (FieldName)
15737       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15738         << FieldName << FieldTy << BitWidth->getSourceRange();
15739     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15740       << FieldTy << BitWidth->getSourceRange();
15741   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15742                                              UPPC_BitFieldWidth))
15743     return ExprError();
15744 
15745   // If the bit-width is type- or value-dependent, don't try to check
15746   // it now.
15747   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15748     return BitWidth;
15749 
15750   llvm::APSInt Value;
15751   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15752   if (ICE.isInvalid())
15753     return ICE;
15754   BitWidth = ICE.get();
15755 
15756   if (Value != 0 && ZeroWidth)
15757     *ZeroWidth = false;
15758 
15759   // Zero-width bitfield is ok for anonymous field.
15760   if (Value == 0 && FieldName)
15761     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15762 
15763   if (Value.isSigned() && Value.isNegative()) {
15764     if (FieldName)
15765       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15766                << FieldName << Value.toString(10);
15767     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15768       << Value.toString(10);
15769   }
15770 
15771   if (!FieldTy->isDependentType()) {
15772     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15773     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15774     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15775 
15776     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15777     // ABI.
15778     bool CStdConstraintViolation =
15779         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15780     bool MSBitfieldViolation =
15781         Value.ugt(TypeStorageSize) &&
15782         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15783     if (CStdConstraintViolation || MSBitfieldViolation) {
15784       unsigned DiagWidth =
15785           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15786       if (FieldName)
15787         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15788                << FieldName << (unsigned)Value.getZExtValue()
15789                << !CStdConstraintViolation << DiagWidth;
15790 
15791       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15792              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15793              << DiagWidth;
15794     }
15795 
15796     // Warn on types where the user might conceivably expect to get all
15797     // specified bits as value bits: that's all integral types other than
15798     // 'bool'.
15799     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15800       if (FieldName)
15801         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15802             << FieldName << (unsigned)Value.getZExtValue()
15803             << (unsigned)TypeWidth;
15804       else
15805         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15806             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15807     }
15808   }
15809 
15810   return BitWidth;
15811 }
15812 
15813 /// ActOnField - Each field of a C struct/union is passed into this in order
15814 /// to create a FieldDecl object for it.
15815 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15816                        Declarator &D, Expr *BitfieldWidth) {
15817   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15818                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15819                                /*InitStyle=*/ICIS_NoInit, AS_public);
15820   return Res;
15821 }
15822 
15823 /// HandleField - Analyze a field of a C struct or a C++ data member.
15824 ///
15825 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15826                              SourceLocation DeclStart,
15827                              Declarator &D, Expr *BitWidth,
15828                              InClassInitStyle InitStyle,
15829                              AccessSpecifier AS) {
15830   if (D.isDecompositionDeclarator()) {
15831     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15832     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15833       << Decomp.getSourceRange();
15834     return nullptr;
15835   }
15836 
15837   IdentifierInfo *II = D.getIdentifier();
15838   SourceLocation Loc = DeclStart;
15839   if (II) Loc = D.getIdentifierLoc();
15840 
15841   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15842   QualType T = TInfo->getType();
15843   if (getLangOpts().CPlusPlus) {
15844     CheckExtraCXXDefaultArguments(D);
15845 
15846     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15847                                         UPPC_DataMemberType)) {
15848       D.setInvalidType();
15849       T = Context.IntTy;
15850       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15851     }
15852   }
15853 
15854   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15855 
15856   if (D.getDeclSpec().isInlineSpecified())
15857     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15858         << getLangOpts().CPlusPlus17;
15859   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15860     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15861          diag::err_invalid_thread)
15862       << DeclSpec::getSpecifierName(TSCS);
15863 
15864   // Check to see if this name was declared as a member previously
15865   NamedDecl *PrevDecl = nullptr;
15866   LookupResult Previous(*this, II, Loc, LookupMemberName,
15867                         ForVisibleRedeclaration);
15868   LookupName(Previous, S);
15869   switch (Previous.getResultKind()) {
15870     case LookupResult::Found:
15871     case LookupResult::FoundUnresolvedValue:
15872       PrevDecl = Previous.getAsSingle<NamedDecl>();
15873       break;
15874 
15875     case LookupResult::FoundOverloaded:
15876       PrevDecl = Previous.getRepresentativeDecl();
15877       break;
15878 
15879     case LookupResult::NotFound:
15880     case LookupResult::NotFoundInCurrentInstantiation:
15881     case LookupResult::Ambiguous:
15882       break;
15883   }
15884   Previous.suppressDiagnostics();
15885 
15886   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15887     // Maybe we will complain about the shadowed template parameter.
15888     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15889     // Just pretend that we didn't see the previous declaration.
15890     PrevDecl = nullptr;
15891   }
15892 
15893   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15894     PrevDecl = nullptr;
15895 
15896   bool Mutable
15897     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15898   SourceLocation TSSL = D.getBeginLoc();
15899   FieldDecl *NewFD
15900     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15901                      TSSL, AS, PrevDecl, &D);
15902 
15903   if (NewFD->isInvalidDecl())
15904     Record->setInvalidDecl();
15905 
15906   if (D.getDeclSpec().isModulePrivateSpecified())
15907     NewFD->setModulePrivate();
15908 
15909   if (NewFD->isInvalidDecl() && PrevDecl) {
15910     // Don't introduce NewFD into scope; there's already something
15911     // with the same name in the same scope.
15912   } else if (II) {
15913     PushOnScopeChains(NewFD, S);
15914   } else
15915     Record->addDecl(NewFD);
15916 
15917   return NewFD;
15918 }
15919 
15920 /// Build a new FieldDecl and check its well-formedness.
15921 ///
15922 /// This routine builds a new FieldDecl given the fields name, type,
15923 /// record, etc. \p PrevDecl should refer to any previous declaration
15924 /// with the same name and in the same scope as the field to be
15925 /// created.
15926 ///
15927 /// \returns a new FieldDecl.
15928 ///
15929 /// \todo The Declarator argument is a hack. It will be removed once
15930 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15931                                 TypeSourceInfo *TInfo,
15932                                 RecordDecl *Record, SourceLocation Loc,
15933                                 bool Mutable, Expr *BitWidth,
15934                                 InClassInitStyle InitStyle,
15935                                 SourceLocation TSSL,
15936                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15937                                 Declarator *D) {
15938   IdentifierInfo *II = Name.getAsIdentifierInfo();
15939   bool InvalidDecl = false;
15940   if (D) InvalidDecl = D->isInvalidType();
15941 
15942   // If we receive a broken type, recover by assuming 'int' and
15943   // marking this declaration as invalid.
15944   if (T.isNull()) {
15945     InvalidDecl = true;
15946     T = Context.IntTy;
15947   }
15948 
15949   QualType EltTy = Context.getBaseElementType(T);
15950   if (!EltTy->isDependentType()) {
15951     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15952       // Fields of incomplete type force their record to be invalid.
15953       Record->setInvalidDecl();
15954       InvalidDecl = true;
15955     } else {
15956       NamedDecl *Def;
15957       EltTy->isIncompleteType(&Def);
15958       if (Def && Def->isInvalidDecl()) {
15959         Record->setInvalidDecl();
15960         InvalidDecl = true;
15961       }
15962     }
15963   }
15964 
15965   // TR 18037 does not allow fields to be declared with address space
15966   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15967       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15968     Diag(Loc, diag::err_field_with_address_space);
15969     Record->setInvalidDecl();
15970     InvalidDecl = true;
15971   }
15972 
15973   if (LangOpts.OpenCL) {
15974     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15975     // used as structure or union field: image, sampler, event or block types.
15976     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15977         T->isBlockPointerType()) {
15978       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15979       Record->setInvalidDecl();
15980       InvalidDecl = true;
15981     }
15982     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15983     if (BitWidth) {
15984       Diag(Loc, diag::err_opencl_bitfields);
15985       InvalidDecl = true;
15986     }
15987   }
15988 
15989   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15990   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15991       T.hasQualifiers()) {
15992     InvalidDecl = true;
15993     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15994   }
15995 
15996   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15997   // than a variably modified type.
15998   if (!InvalidDecl && T->isVariablyModifiedType()) {
15999     bool SizeIsNegative;
16000     llvm::APSInt Oversized;
16001 
16002     TypeSourceInfo *FixedTInfo =
16003       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16004                                                     SizeIsNegative,
16005                                                     Oversized);
16006     if (FixedTInfo) {
16007       Diag(Loc, diag::warn_illegal_constant_array_size);
16008       TInfo = FixedTInfo;
16009       T = FixedTInfo->getType();
16010     } else {
16011       if (SizeIsNegative)
16012         Diag(Loc, diag::err_typecheck_negative_array_size);
16013       else if (Oversized.getBoolValue())
16014         Diag(Loc, diag::err_array_too_large)
16015           << Oversized.toString(10);
16016       else
16017         Diag(Loc, diag::err_typecheck_field_variable_size);
16018       InvalidDecl = true;
16019     }
16020   }
16021 
16022   // Fields can not have abstract class types
16023   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16024                                              diag::err_abstract_type_in_decl,
16025                                              AbstractFieldType))
16026     InvalidDecl = true;
16027 
16028   bool ZeroWidth = false;
16029   if (InvalidDecl)
16030     BitWidth = nullptr;
16031   // If this is declared as a bit-field, check the bit-field.
16032   if (BitWidth) {
16033     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16034                               &ZeroWidth).get();
16035     if (!BitWidth) {
16036       InvalidDecl = true;
16037       BitWidth = nullptr;
16038       ZeroWidth = false;
16039     }
16040   }
16041 
16042   // Check that 'mutable' is consistent with the type of the declaration.
16043   if (!InvalidDecl && Mutable) {
16044     unsigned DiagID = 0;
16045     if (T->isReferenceType())
16046       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16047                                         : diag::err_mutable_reference;
16048     else if (T.isConstQualified())
16049       DiagID = diag::err_mutable_const;
16050 
16051     if (DiagID) {
16052       SourceLocation ErrLoc = Loc;
16053       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16054         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16055       Diag(ErrLoc, DiagID);
16056       if (DiagID != diag::ext_mutable_reference) {
16057         Mutable = false;
16058         InvalidDecl = true;
16059       }
16060     }
16061   }
16062 
16063   // C++11 [class.union]p8 (DR1460):
16064   //   At most one variant member of a union may have a
16065   //   brace-or-equal-initializer.
16066   if (InitStyle != ICIS_NoInit)
16067     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16068 
16069   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16070                                        BitWidth, Mutable, InitStyle);
16071   if (InvalidDecl)
16072     NewFD->setInvalidDecl();
16073 
16074   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16075     Diag(Loc, diag::err_duplicate_member) << II;
16076     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16077     NewFD->setInvalidDecl();
16078   }
16079 
16080   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16081     if (Record->isUnion()) {
16082       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16083         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16084         if (RDecl->getDefinition()) {
16085           // C++ [class.union]p1: An object of a class with a non-trivial
16086           // constructor, a non-trivial copy constructor, a non-trivial
16087           // destructor, or a non-trivial copy assignment operator
16088           // cannot be a member of a union, nor can an array of such
16089           // objects.
16090           if (CheckNontrivialField(NewFD))
16091             NewFD->setInvalidDecl();
16092         }
16093       }
16094 
16095       // C++ [class.union]p1: If a union contains a member of reference type,
16096       // the program is ill-formed, except when compiling with MSVC extensions
16097       // enabled.
16098       if (EltTy->isReferenceType()) {
16099         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16100                                     diag::ext_union_member_of_reference_type :
16101                                     diag::err_union_member_of_reference_type)
16102           << NewFD->getDeclName() << EltTy;
16103         if (!getLangOpts().MicrosoftExt)
16104           NewFD->setInvalidDecl();
16105       }
16106     }
16107   }
16108 
16109   // FIXME: We need to pass in the attributes given an AST
16110   // representation, not a parser representation.
16111   if (D) {
16112     // FIXME: The current scope is almost... but not entirely... correct here.
16113     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16114 
16115     if (NewFD->hasAttrs())
16116       CheckAlignasUnderalignment(NewFD);
16117   }
16118 
16119   // In auto-retain/release, infer strong retension for fields of
16120   // retainable type.
16121   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16122     NewFD->setInvalidDecl();
16123 
16124   if (T.isObjCGCWeak())
16125     Diag(Loc, diag::warn_attribute_weak_on_field);
16126 
16127   NewFD->setAccess(AS);
16128   return NewFD;
16129 }
16130 
16131 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16132   assert(FD);
16133   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16134 
16135   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16136     return false;
16137 
16138   QualType EltTy = Context.getBaseElementType(FD->getType());
16139   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16140     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16141     if (RDecl->getDefinition()) {
16142       // We check for copy constructors before constructors
16143       // because otherwise we'll never get complaints about
16144       // copy constructors.
16145 
16146       CXXSpecialMember member = CXXInvalid;
16147       // We're required to check for any non-trivial constructors. Since the
16148       // implicit default constructor is suppressed if there are any
16149       // user-declared constructors, we just need to check that there is a
16150       // trivial default constructor and a trivial copy constructor. (We don't
16151       // worry about move constructors here, since this is a C++98 check.)
16152       if (RDecl->hasNonTrivialCopyConstructor())
16153         member = CXXCopyConstructor;
16154       else if (!RDecl->hasTrivialDefaultConstructor())
16155         member = CXXDefaultConstructor;
16156       else if (RDecl->hasNonTrivialCopyAssignment())
16157         member = CXXCopyAssignment;
16158       else if (RDecl->hasNonTrivialDestructor())
16159         member = CXXDestructor;
16160 
16161       if (member != CXXInvalid) {
16162         if (!getLangOpts().CPlusPlus11 &&
16163             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16164           // Objective-C++ ARC: it is an error to have a non-trivial field of
16165           // a union. However, system headers in Objective-C programs
16166           // occasionally have Objective-C lifetime objects within unions,
16167           // and rather than cause the program to fail, we make those
16168           // members unavailable.
16169           SourceLocation Loc = FD->getLocation();
16170           if (getSourceManager().isInSystemHeader(Loc)) {
16171             if (!FD->hasAttr<UnavailableAttr>())
16172               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16173                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16174             return false;
16175           }
16176         }
16177 
16178         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16179                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16180                diag::err_illegal_union_or_anon_struct_member)
16181           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16182         DiagnoseNontrivial(RDecl, member);
16183         return !getLangOpts().CPlusPlus11;
16184       }
16185     }
16186   }
16187 
16188   return false;
16189 }
16190 
16191 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16192 ///  AST enum value.
16193 static ObjCIvarDecl::AccessControl
16194 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16195   switch (ivarVisibility) {
16196   default: llvm_unreachable("Unknown visitibility kind");
16197   case tok::objc_private: return ObjCIvarDecl::Private;
16198   case tok::objc_public: return ObjCIvarDecl::Public;
16199   case tok::objc_protected: return ObjCIvarDecl::Protected;
16200   case tok::objc_package: return ObjCIvarDecl::Package;
16201   }
16202 }
16203 
16204 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16205 /// in order to create an IvarDecl object for it.
16206 Decl *Sema::ActOnIvar(Scope *S,
16207                                 SourceLocation DeclStart,
16208                                 Declarator &D, Expr *BitfieldWidth,
16209                                 tok::ObjCKeywordKind Visibility) {
16210 
16211   IdentifierInfo *II = D.getIdentifier();
16212   Expr *BitWidth = (Expr*)BitfieldWidth;
16213   SourceLocation Loc = DeclStart;
16214   if (II) Loc = D.getIdentifierLoc();
16215 
16216   // FIXME: Unnamed fields can be handled in various different ways, for
16217   // example, unnamed unions inject all members into the struct namespace!
16218 
16219   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16220   QualType T = TInfo->getType();
16221 
16222   if (BitWidth) {
16223     // 6.7.2.1p3, 6.7.2.1p4
16224     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16225     if (!BitWidth)
16226       D.setInvalidType();
16227   } else {
16228     // Not a bitfield.
16229 
16230     // validate II.
16231 
16232   }
16233   if (T->isReferenceType()) {
16234     Diag(Loc, diag::err_ivar_reference_type);
16235     D.setInvalidType();
16236   }
16237   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16238   // than a variably modified type.
16239   else if (T->isVariablyModifiedType()) {
16240     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16241     D.setInvalidType();
16242   }
16243 
16244   // Get the visibility (access control) for this ivar.
16245   ObjCIvarDecl::AccessControl ac =
16246     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16247                                         : ObjCIvarDecl::None;
16248   // Must set ivar's DeclContext to its enclosing interface.
16249   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16250   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16251     return nullptr;
16252   ObjCContainerDecl *EnclosingContext;
16253   if (ObjCImplementationDecl *IMPDecl =
16254       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16255     if (LangOpts.ObjCRuntime.isFragile()) {
16256     // Case of ivar declared in an implementation. Context is that of its class.
16257       EnclosingContext = IMPDecl->getClassInterface();
16258       assert(EnclosingContext && "Implementation has no class interface!");
16259     }
16260     else
16261       EnclosingContext = EnclosingDecl;
16262   } else {
16263     if (ObjCCategoryDecl *CDecl =
16264         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16265       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16266         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16267         return nullptr;
16268       }
16269     }
16270     EnclosingContext = EnclosingDecl;
16271   }
16272 
16273   // Construct the decl.
16274   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16275                                              DeclStart, Loc, II, T,
16276                                              TInfo, ac, (Expr *)BitfieldWidth);
16277 
16278   if (II) {
16279     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16280                                            ForVisibleRedeclaration);
16281     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16282         && !isa<TagDecl>(PrevDecl)) {
16283       Diag(Loc, diag::err_duplicate_member) << II;
16284       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16285       NewID->setInvalidDecl();
16286     }
16287   }
16288 
16289   // Process attributes attached to the ivar.
16290   ProcessDeclAttributes(S, NewID, D);
16291 
16292   if (D.isInvalidType())
16293     NewID->setInvalidDecl();
16294 
16295   // In ARC, infer 'retaining' for ivars of retainable type.
16296   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16297     NewID->setInvalidDecl();
16298 
16299   if (D.getDeclSpec().isModulePrivateSpecified())
16300     NewID->setModulePrivate();
16301 
16302   if (II) {
16303     // FIXME: When interfaces are DeclContexts, we'll need to add
16304     // these to the interface.
16305     S->AddDecl(NewID);
16306     IdResolver.AddDecl(NewID);
16307   }
16308 
16309   if (LangOpts.ObjCRuntime.isNonFragile() &&
16310       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16311     Diag(Loc, diag::warn_ivars_in_interface);
16312 
16313   return NewID;
16314 }
16315 
16316 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16317 /// class and class extensions. For every class \@interface and class
16318 /// extension \@interface, if the last ivar is a bitfield of any type,
16319 /// then add an implicit `char :0` ivar to the end of that interface.
16320 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16321                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16322   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16323     return;
16324 
16325   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16326   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16327 
16328   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16329     return;
16330   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16331   if (!ID) {
16332     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16333       if (!CD->IsClassExtension())
16334         return;
16335     }
16336     // No need to add this to end of @implementation.
16337     else
16338       return;
16339   }
16340   // All conditions are met. Add a new bitfield to the tail end of ivars.
16341   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16342   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16343 
16344   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16345                               DeclLoc, DeclLoc, nullptr,
16346                               Context.CharTy,
16347                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16348                                                                DeclLoc),
16349                               ObjCIvarDecl::Private, BW,
16350                               true);
16351   AllIvarDecls.push_back(Ivar);
16352 }
16353 
16354 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16355                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16356                        SourceLocation RBrac,
16357                        const ParsedAttributesView &Attrs) {
16358   assert(EnclosingDecl && "missing record or interface decl");
16359 
16360   // If this is an Objective-C @implementation or category and we have
16361   // new fields here we should reset the layout of the interface since
16362   // it will now change.
16363   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16364     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16365     switch (DC->getKind()) {
16366     default: break;
16367     case Decl::ObjCCategory:
16368       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16369       break;
16370     case Decl::ObjCImplementation:
16371       Context.
16372         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16373       break;
16374     }
16375   }
16376 
16377   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16378   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16379 
16380   // Start counting up the number of named members; make sure to include
16381   // members of anonymous structs and unions in the total.
16382   unsigned NumNamedMembers = 0;
16383   if (Record) {
16384     for (const auto *I : Record->decls()) {
16385       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16386         if (IFD->getDeclName())
16387           ++NumNamedMembers;
16388     }
16389   }
16390 
16391   // Verify that all the fields are okay.
16392   SmallVector<FieldDecl*, 32> RecFields;
16393 
16394   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16395        i != end; ++i) {
16396     FieldDecl *FD = cast<FieldDecl>(*i);
16397 
16398     // Get the type for the field.
16399     const Type *FDTy = FD->getType().getTypePtr();
16400 
16401     if (!FD->isAnonymousStructOrUnion()) {
16402       // Remember all fields written by the user.
16403       RecFields.push_back(FD);
16404     }
16405 
16406     // If the field is already invalid for some reason, don't emit more
16407     // diagnostics about it.
16408     if (FD->isInvalidDecl()) {
16409       EnclosingDecl->setInvalidDecl();
16410       continue;
16411     }
16412 
16413     // C99 6.7.2.1p2:
16414     //   A structure or union shall not contain a member with
16415     //   incomplete or function type (hence, a structure shall not
16416     //   contain an instance of itself, but may contain a pointer to
16417     //   an instance of itself), except that the last member of a
16418     //   structure with more than one named member may have incomplete
16419     //   array type; such a structure (and any union containing,
16420     //   possibly recursively, a member that is such a structure)
16421     //   shall not be a member of a structure or an element of an
16422     //   array.
16423     bool IsLastField = (i + 1 == Fields.end());
16424     if (FDTy->isFunctionType()) {
16425       // Field declared as a function.
16426       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16427         << FD->getDeclName();
16428       FD->setInvalidDecl();
16429       EnclosingDecl->setInvalidDecl();
16430       continue;
16431     } else if (FDTy->isIncompleteArrayType() &&
16432                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16433       if (Record) {
16434         // Flexible array member.
16435         // Microsoft and g++ is more permissive regarding flexible array.
16436         // It will accept flexible array in union and also
16437         // as the sole element of a struct/class.
16438         unsigned DiagID = 0;
16439         if (!Record->isUnion() && !IsLastField) {
16440           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16441             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16442           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16443           FD->setInvalidDecl();
16444           EnclosingDecl->setInvalidDecl();
16445           continue;
16446         } else if (Record->isUnion())
16447           DiagID = getLangOpts().MicrosoftExt
16448                        ? diag::ext_flexible_array_union_ms
16449                        : getLangOpts().CPlusPlus
16450                              ? diag::ext_flexible_array_union_gnu
16451                              : diag::err_flexible_array_union;
16452         else if (NumNamedMembers < 1)
16453           DiagID = getLangOpts().MicrosoftExt
16454                        ? diag::ext_flexible_array_empty_aggregate_ms
16455                        : getLangOpts().CPlusPlus
16456                              ? diag::ext_flexible_array_empty_aggregate_gnu
16457                              : diag::err_flexible_array_empty_aggregate;
16458 
16459         if (DiagID)
16460           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16461                                           << Record->getTagKind();
16462         // While the layout of types that contain virtual bases is not specified
16463         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16464         // virtual bases after the derived members.  This would make a flexible
16465         // array member declared at the end of an object not adjacent to the end
16466         // of the type.
16467         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16468           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16469               << FD->getDeclName() << Record->getTagKind();
16470         if (!getLangOpts().C99)
16471           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16472             << FD->getDeclName() << Record->getTagKind();
16473 
16474         // If the element type has a non-trivial destructor, we would not
16475         // implicitly destroy the elements, so disallow it for now.
16476         //
16477         // FIXME: GCC allows this. We should probably either implicitly delete
16478         // the destructor of the containing class, or just allow this.
16479         QualType BaseElem = Context.getBaseElementType(FD->getType());
16480         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16481           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16482             << FD->getDeclName() << FD->getType();
16483           FD->setInvalidDecl();
16484           EnclosingDecl->setInvalidDecl();
16485           continue;
16486         }
16487         // Okay, we have a legal flexible array member at the end of the struct.
16488         Record->setHasFlexibleArrayMember(true);
16489       } else {
16490         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16491         // unless they are followed by another ivar. That check is done
16492         // elsewhere, after synthesized ivars are known.
16493       }
16494     } else if (!FDTy->isDependentType() &&
16495                RequireCompleteType(FD->getLocation(), FD->getType(),
16496                                    diag::err_field_incomplete)) {
16497       // Incomplete type
16498       FD->setInvalidDecl();
16499       EnclosingDecl->setInvalidDecl();
16500       continue;
16501     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16502       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16503         // A type which contains a flexible array member is considered to be a
16504         // flexible array member.
16505         Record->setHasFlexibleArrayMember(true);
16506         if (!Record->isUnion()) {
16507           // If this is a struct/class and this is not the last element, reject
16508           // it.  Note that GCC supports variable sized arrays in the middle of
16509           // structures.
16510           if (!IsLastField)
16511             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16512               << FD->getDeclName() << FD->getType();
16513           else {
16514             // We support flexible arrays at the end of structs in
16515             // other structs as an extension.
16516             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16517               << FD->getDeclName();
16518           }
16519         }
16520       }
16521       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16522           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16523                                  diag::err_abstract_type_in_decl,
16524                                  AbstractIvarType)) {
16525         // Ivars can not have abstract class types
16526         FD->setInvalidDecl();
16527       }
16528       if (Record && FDTTy->getDecl()->hasObjectMember())
16529         Record->setHasObjectMember(true);
16530       if (Record && FDTTy->getDecl()->hasVolatileMember())
16531         Record->setHasVolatileMember(true);
16532     } else if (FDTy->isObjCObjectType()) {
16533       /// A field cannot be an Objective-c object
16534       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16535         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16536       QualType T = Context.getObjCObjectPointerType(FD->getType());
16537       FD->setType(T);
16538     } else if (Record && Record->isUnion() &&
16539                FD->getType().hasNonTrivialObjCLifetime() &&
16540                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16541                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16542                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16543                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16544       // For backward compatibility, fields of C unions declared in system
16545       // headers that have non-trivial ObjC ownership qualifications are marked
16546       // as unavailable unless the qualifier is explicit and __strong. This can
16547       // break ABI compatibility between programs compiled with ARC and MRR, but
16548       // is a better option than rejecting programs using those unions under
16549       // ARC.
16550       FD->addAttr(UnavailableAttr::CreateImplicit(
16551           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16552           FD->getLocation()));
16553     } else if (getLangOpts().ObjC &&
16554                getLangOpts().getGC() != LangOptions::NonGC &&
16555                Record && !Record->hasObjectMember()) {
16556       if (FD->getType()->isObjCObjectPointerType() ||
16557           FD->getType().isObjCGCStrong())
16558         Record->setHasObjectMember(true);
16559       else if (Context.getAsArrayType(FD->getType())) {
16560         QualType BaseType = Context.getBaseElementType(FD->getType());
16561         if (BaseType->isRecordType() &&
16562             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16563           Record->setHasObjectMember(true);
16564         else if (BaseType->isObjCObjectPointerType() ||
16565                  BaseType.isObjCGCStrong())
16566                Record->setHasObjectMember(true);
16567       }
16568     }
16569 
16570     if (Record && !getLangOpts().CPlusPlus &&
16571         !shouldIgnoreForRecordTriviality(FD)) {
16572       QualType FT = FD->getType();
16573       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16574         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16575         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16576             Record->isUnion())
16577           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16578       }
16579       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16580       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16581         Record->setNonTrivialToPrimitiveCopy(true);
16582         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16583           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16584       }
16585       if (FT.isDestructedType()) {
16586         Record->setNonTrivialToPrimitiveDestroy(true);
16587         Record->setParamDestroyedInCallee(true);
16588         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16589           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16590       }
16591 
16592       if (const auto *RT = FT->getAs<RecordType>()) {
16593         if (RT->getDecl()->getArgPassingRestrictions() ==
16594             RecordDecl::APK_CanNeverPassInRegs)
16595           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16596       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16597         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16598     }
16599 
16600     if (Record && FD->getType().isVolatileQualified())
16601       Record->setHasVolatileMember(true);
16602     // Keep track of the number of named members.
16603     if (FD->getIdentifier())
16604       ++NumNamedMembers;
16605   }
16606 
16607   // Okay, we successfully defined 'Record'.
16608   if (Record) {
16609     bool Completed = false;
16610     if (CXXRecord) {
16611       if (!CXXRecord->isInvalidDecl()) {
16612         // Set access bits correctly on the directly-declared conversions.
16613         for (CXXRecordDecl::conversion_iterator
16614                I = CXXRecord->conversion_begin(),
16615                E = CXXRecord->conversion_end(); I != E; ++I)
16616           I.setAccess((*I)->getAccess());
16617       }
16618 
16619       if (!CXXRecord->isDependentType()) {
16620         // Add any implicitly-declared members to this class.
16621         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16622 
16623         if (!CXXRecord->isInvalidDecl()) {
16624           // If we have virtual base classes, we may end up finding multiple
16625           // final overriders for a given virtual function. Check for this
16626           // problem now.
16627           if (CXXRecord->getNumVBases()) {
16628             CXXFinalOverriderMap FinalOverriders;
16629             CXXRecord->getFinalOverriders(FinalOverriders);
16630 
16631             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16632                                              MEnd = FinalOverriders.end();
16633                  M != MEnd; ++M) {
16634               for (OverridingMethods::iterator SO = M->second.begin(),
16635                                             SOEnd = M->second.end();
16636                    SO != SOEnd; ++SO) {
16637                 assert(SO->second.size() > 0 &&
16638                        "Virtual function without overriding functions?");
16639                 if (SO->second.size() == 1)
16640                   continue;
16641 
16642                 // C++ [class.virtual]p2:
16643                 //   In a derived class, if a virtual member function of a base
16644                 //   class subobject has more than one final overrider the
16645                 //   program is ill-formed.
16646                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16647                   << (const NamedDecl *)M->first << Record;
16648                 Diag(M->first->getLocation(),
16649                      diag::note_overridden_virtual_function);
16650                 for (OverridingMethods::overriding_iterator
16651                           OM = SO->second.begin(),
16652                        OMEnd = SO->second.end();
16653                      OM != OMEnd; ++OM)
16654                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16655                     << (const NamedDecl *)M->first << OM->Method->getParent();
16656 
16657                 Record->setInvalidDecl();
16658               }
16659             }
16660             CXXRecord->completeDefinition(&FinalOverriders);
16661             Completed = true;
16662           }
16663         }
16664       }
16665     }
16666 
16667     if (!Completed)
16668       Record->completeDefinition();
16669 
16670     // Handle attributes before checking the layout.
16671     ProcessDeclAttributeList(S, Record, Attrs);
16672 
16673     // We may have deferred checking for a deleted destructor. Check now.
16674     if (CXXRecord) {
16675       auto *Dtor = CXXRecord->getDestructor();
16676       if (Dtor && Dtor->isImplicit() &&
16677           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16678         CXXRecord->setImplicitDestructorIsDeleted();
16679         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16680       }
16681     }
16682 
16683     if (Record->hasAttrs()) {
16684       CheckAlignasUnderalignment(Record);
16685 
16686       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16687         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16688                                            IA->getRange(), IA->getBestCase(),
16689                                            IA->getSemanticSpelling());
16690     }
16691 
16692     // Check if the structure/union declaration is a type that can have zero
16693     // size in C. For C this is a language extension, for C++ it may cause
16694     // compatibility problems.
16695     bool CheckForZeroSize;
16696     if (!getLangOpts().CPlusPlus) {
16697       CheckForZeroSize = true;
16698     } else {
16699       // For C++ filter out types that cannot be referenced in C code.
16700       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16701       CheckForZeroSize =
16702           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16703           !CXXRecord->isDependentType() &&
16704           CXXRecord->isCLike();
16705     }
16706     if (CheckForZeroSize) {
16707       bool ZeroSize = true;
16708       bool IsEmpty = true;
16709       unsigned NonBitFields = 0;
16710       for (RecordDecl::field_iterator I = Record->field_begin(),
16711                                       E = Record->field_end();
16712            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16713         IsEmpty = false;
16714         if (I->isUnnamedBitfield()) {
16715           if (!I->isZeroLengthBitField(Context))
16716             ZeroSize = false;
16717         } else {
16718           ++NonBitFields;
16719           QualType FieldType = I->getType();
16720           if (FieldType->isIncompleteType() ||
16721               !Context.getTypeSizeInChars(FieldType).isZero())
16722             ZeroSize = false;
16723         }
16724       }
16725 
16726       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16727       // allowed in C++, but warn if its declaration is inside
16728       // extern "C" block.
16729       if (ZeroSize) {
16730         Diag(RecLoc, getLangOpts().CPlusPlus ?
16731                          diag::warn_zero_size_struct_union_in_extern_c :
16732                          diag::warn_zero_size_struct_union_compat)
16733           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16734       }
16735 
16736       // Structs without named members are extension in C (C99 6.7.2.1p7),
16737       // but are accepted by GCC.
16738       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16739         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16740                                diag::ext_no_named_members_in_struct_union)
16741           << Record->isUnion();
16742       }
16743     }
16744   } else {
16745     ObjCIvarDecl **ClsFields =
16746       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16747     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16748       ID->setEndOfDefinitionLoc(RBrac);
16749       // Add ivar's to class's DeclContext.
16750       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16751         ClsFields[i]->setLexicalDeclContext(ID);
16752         ID->addDecl(ClsFields[i]);
16753       }
16754       // Must enforce the rule that ivars in the base classes may not be
16755       // duplicates.
16756       if (ID->getSuperClass())
16757         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16758     } else if (ObjCImplementationDecl *IMPDecl =
16759                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16760       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16761       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16762         // Ivar declared in @implementation never belongs to the implementation.
16763         // Only it is in implementation's lexical context.
16764         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16765       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16766       IMPDecl->setIvarLBraceLoc(LBrac);
16767       IMPDecl->setIvarRBraceLoc(RBrac);
16768     } else if (ObjCCategoryDecl *CDecl =
16769                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16770       // case of ivars in class extension; all other cases have been
16771       // reported as errors elsewhere.
16772       // FIXME. Class extension does not have a LocEnd field.
16773       // CDecl->setLocEnd(RBrac);
16774       // Add ivar's to class extension's DeclContext.
16775       // Diagnose redeclaration of private ivars.
16776       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16777       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16778         if (IDecl) {
16779           if (const ObjCIvarDecl *ClsIvar =
16780               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16781             Diag(ClsFields[i]->getLocation(),
16782                  diag::err_duplicate_ivar_declaration);
16783             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16784             continue;
16785           }
16786           for (const auto *Ext : IDecl->known_extensions()) {
16787             if (const ObjCIvarDecl *ClsExtIvar
16788                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16789               Diag(ClsFields[i]->getLocation(),
16790                    diag::err_duplicate_ivar_declaration);
16791               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16792               continue;
16793             }
16794           }
16795         }
16796         ClsFields[i]->setLexicalDeclContext(CDecl);
16797         CDecl->addDecl(ClsFields[i]);
16798       }
16799       CDecl->setIvarLBraceLoc(LBrac);
16800       CDecl->setIvarRBraceLoc(RBrac);
16801     }
16802   }
16803 }
16804 
16805 /// Determine whether the given integral value is representable within
16806 /// the given type T.
16807 static bool isRepresentableIntegerValue(ASTContext &Context,
16808                                         llvm::APSInt &Value,
16809                                         QualType T) {
16810   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16811          "Integral type required!");
16812   unsigned BitWidth = Context.getIntWidth(T);
16813 
16814   if (Value.isUnsigned() || Value.isNonNegative()) {
16815     if (T->isSignedIntegerOrEnumerationType())
16816       --BitWidth;
16817     return Value.getActiveBits() <= BitWidth;
16818   }
16819   return Value.getMinSignedBits() <= BitWidth;
16820 }
16821 
16822 // Given an integral type, return the next larger integral type
16823 // (or a NULL type of no such type exists).
16824 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16825   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16826   // enum checking below.
16827   assert((T->isIntegralType(Context) ||
16828          T->isEnumeralType()) && "Integral type required!");
16829   const unsigned NumTypes = 4;
16830   QualType SignedIntegralTypes[NumTypes] = {
16831     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16832   };
16833   QualType UnsignedIntegralTypes[NumTypes] = {
16834     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16835     Context.UnsignedLongLongTy
16836   };
16837 
16838   unsigned BitWidth = Context.getTypeSize(T);
16839   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16840                                                         : UnsignedIntegralTypes;
16841   for (unsigned I = 0; I != NumTypes; ++I)
16842     if (Context.getTypeSize(Types[I]) > BitWidth)
16843       return Types[I];
16844 
16845   return QualType();
16846 }
16847 
16848 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16849                                           EnumConstantDecl *LastEnumConst,
16850                                           SourceLocation IdLoc,
16851                                           IdentifierInfo *Id,
16852                                           Expr *Val) {
16853   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16854   llvm::APSInt EnumVal(IntWidth);
16855   QualType EltTy;
16856 
16857   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16858     Val = nullptr;
16859 
16860   if (Val)
16861     Val = DefaultLvalueConversion(Val).get();
16862 
16863   if (Val) {
16864     if (Enum->isDependentType() || Val->isTypeDependent())
16865       EltTy = Context.DependentTy;
16866     else {
16867       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
16868         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16869         // constant-expression in the enumerator-definition shall be a converted
16870         // constant expression of the underlying type.
16871         EltTy = Enum->getIntegerType();
16872         ExprResult Converted =
16873           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16874                                            CCEK_Enumerator);
16875         if (Converted.isInvalid())
16876           Val = nullptr;
16877         else
16878           Val = Converted.get();
16879       } else if (!Val->isValueDependent() &&
16880                  !(Val = VerifyIntegerConstantExpression(Val,
16881                                                          &EnumVal).get())) {
16882         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16883       } else {
16884         if (Enum->isComplete()) {
16885           EltTy = Enum->getIntegerType();
16886 
16887           // In Obj-C and Microsoft mode, require the enumeration value to be
16888           // representable in the underlying type of the enumeration. In C++11,
16889           // we perform a non-narrowing conversion as part of converted constant
16890           // expression checking.
16891           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16892             if (Context.getTargetInfo()
16893                     .getTriple()
16894                     .isWindowsMSVCEnvironment()) {
16895               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16896             } else {
16897               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16898             }
16899           }
16900 
16901           // Cast to the underlying type.
16902           Val = ImpCastExprToType(Val, EltTy,
16903                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
16904                                                          : CK_IntegralCast)
16905                     .get();
16906         } else if (getLangOpts().CPlusPlus) {
16907           // C++11 [dcl.enum]p5:
16908           //   If the underlying type is not fixed, the type of each enumerator
16909           //   is the type of its initializing value:
16910           //     - If an initializer is specified for an enumerator, the
16911           //       initializing value has the same type as the expression.
16912           EltTy = Val->getType();
16913         } else {
16914           // C99 6.7.2.2p2:
16915           //   The expression that defines the value of an enumeration constant
16916           //   shall be an integer constant expression that has a value
16917           //   representable as an int.
16918 
16919           // Complain if the value is not representable in an int.
16920           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16921             Diag(IdLoc, diag::ext_enum_value_not_int)
16922               << EnumVal.toString(10) << Val->getSourceRange()
16923               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16924           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16925             // Force the type of the expression to 'int'.
16926             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16927           }
16928           EltTy = Val->getType();
16929         }
16930       }
16931     }
16932   }
16933 
16934   if (!Val) {
16935     if (Enum->isDependentType())
16936       EltTy = Context.DependentTy;
16937     else if (!LastEnumConst) {
16938       // C++0x [dcl.enum]p5:
16939       //   If the underlying type is not fixed, the type of each enumerator
16940       //   is the type of its initializing value:
16941       //     - If no initializer is specified for the first enumerator, the
16942       //       initializing value has an unspecified integral type.
16943       //
16944       // GCC uses 'int' for its unspecified integral type, as does
16945       // C99 6.7.2.2p3.
16946       if (Enum->isFixed()) {
16947         EltTy = Enum->getIntegerType();
16948       }
16949       else {
16950         EltTy = Context.IntTy;
16951       }
16952     } else {
16953       // Assign the last value + 1.
16954       EnumVal = LastEnumConst->getInitVal();
16955       ++EnumVal;
16956       EltTy = LastEnumConst->getType();
16957 
16958       // Check for overflow on increment.
16959       if (EnumVal < LastEnumConst->getInitVal()) {
16960         // C++0x [dcl.enum]p5:
16961         //   If the underlying type is not fixed, the type of each enumerator
16962         //   is the type of its initializing value:
16963         //
16964         //     - Otherwise the type of the initializing value is the same as
16965         //       the type of the initializing value of the preceding enumerator
16966         //       unless the incremented value is not representable in that type,
16967         //       in which case the type is an unspecified integral type
16968         //       sufficient to contain the incremented value. If no such type
16969         //       exists, the program is ill-formed.
16970         QualType T = getNextLargerIntegralType(Context, EltTy);
16971         if (T.isNull() || Enum->isFixed()) {
16972           // There is no integral type larger enough to represent this
16973           // value. Complain, then allow the value to wrap around.
16974           EnumVal = LastEnumConst->getInitVal();
16975           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16976           ++EnumVal;
16977           if (Enum->isFixed())
16978             // When the underlying type is fixed, this is ill-formed.
16979             Diag(IdLoc, diag::err_enumerator_wrapped)
16980               << EnumVal.toString(10)
16981               << EltTy;
16982           else
16983             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16984               << EnumVal.toString(10);
16985         } else {
16986           EltTy = T;
16987         }
16988 
16989         // Retrieve the last enumerator's value, extent that type to the
16990         // type that is supposed to be large enough to represent the incremented
16991         // value, then increment.
16992         EnumVal = LastEnumConst->getInitVal();
16993         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16994         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16995         ++EnumVal;
16996 
16997         // If we're not in C++, diagnose the overflow of enumerator values,
16998         // which in C99 means that the enumerator value is not representable in
16999         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17000         // permits enumerator values that are representable in some larger
17001         // integral type.
17002         if (!getLangOpts().CPlusPlus && !T.isNull())
17003           Diag(IdLoc, diag::warn_enum_value_overflow);
17004       } else if (!getLangOpts().CPlusPlus &&
17005                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17006         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17007         Diag(IdLoc, diag::ext_enum_value_not_int)
17008           << EnumVal.toString(10) << 1;
17009       }
17010     }
17011   }
17012 
17013   if (!EltTy->isDependentType()) {
17014     // Make the enumerator value match the signedness and size of the
17015     // enumerator's type.
17016     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17017     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17018   }
17019 
17020   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17021                                   Val, EnumVal);
17022 }
17023 
17024 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17025                                                 SourceLocation IILoc) {
17026   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17027       !getLangOpts().CPlusPlus)
17028     return SkipBodyInfo();
17029 
17030   // We have an anonymous enum definition. Look up the first enumerator to
17031   // determine if we should merge the definition with an existing one and
17032   // skip the body.
17033   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17034                                          forRedeclarationInCurContext());
17035   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17036   if (!PrevECD)
17037     return SkipBodyInfo();
17038 
17039   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17040   NamedDecl *Hidden;
17041   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17042     SkipBodyInfo Skip;
17043     Skip.Previous = Hidden;
17044     return Skip;
17045   }
17046 
17047   return SkipBodyInfo();
17048 }
17049 
17050 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17051                               SourceLocation IdLoc, IdentifierInfo *Id,
17052                               const ParsedAttributesView &Attrs,
17053                               SourceLocation EqualLoc, Expr *Val) {
17054   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17055   EnumConstantDecl *LastEnumConst =
17056     cast_or_null<EnumConstantDecl>(lastEnumConst);
17057 
17058   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17059   // we find one that is.
17060   S = getNonFieldDeclScope(S);
17061 
17062   // Verify that there isn't already something declared with this name in this
17063   // scope.
17064   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17065   LookupName(R, S);
17066   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17067 
17068   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17069     // Maybe we will complain about the shadowed template parameter.
17070     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17071     // Just pretend that we didn't see the previous declaration.
17072     PrevDecl = nullptr;
17073   }
17074 
17075   // C++ [class.mem]p15:
17076   // If T is the name of a class, then each of the following shall have a name
17077   // different from T:
17078   // - every enumerator of every member of class T that is an unscoped
17079   // enumerated type
17080   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17081     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17082                             DeclarationNameInfo(Id, IdLoc));
17083 
17084   EnumConstantDecl *New =
17085     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17086   if (!New)
17087     return nullptr;
17088 
17089   if (PrevDecl) {
17090     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17091       // Check for other kinds of shadowing not already handled.
17092       CheckShadow(New, PrevDecl, R);
17093     }
17094 
17095     // When in C++, we may get a TagDecl with the same name; in this case the
17096     // enum constant will 'hide' the tag.
17097     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17098            "Received TagDecl when not in C++!");
17099     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17100       if (isa<EnumConstantDecl>(PrevDecl))
17101         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17102       else
17103         Diag(IdLoc, diag::err_redefinition) << Id;
17104       notePreviousDefinition(PrevDecl, IdLoc);
17105       return nullptr;
17106     }
17107   }
17108 
17109   // Process attributes.
17110   ProcessDeclAttributeList(S, New, Attrs);
17111   AddPragmaAttributes(S, New);
17112 
17113   // Register this decl in the current scope stack.
17114   New->setAccess(TheEnumDecl->getAccess());
17115   PushOnScopeChains(New, S);
17116 
17117   ActOnDocumentableDecl(New);
17118 
17119   return New;
17120 }
17121 
17122 // Returns true when the enum initial expression does not trigger the
17123 // duplicate enum warning.  A few common cases are exempted as follows:
17124 // Element2 = Element1
17125 // Element2 = Element1 + 1
17126 // Element2 = Element1 - 1
17127 // Where Element2 and Element1 are from the same enum.
17128 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17129   Expr *InitExpr = ECD->getInitExpr();
17130   if (!InitExpr)
17131     return true;
17132   InitExpr = InitExpr->IgnoreImpCasts();
17133 
17134   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17135     if (!BO->isAdditiveOp())
17136       return true;
17137     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17138     if (!IL)
17139       return true;
17140     if (IL->getValue() != 1)
17141       return true;
17142 
17143     InitExpr = BO->getLHS();
17144   }
17145 
17146   // This checks if the elements are from the same enum.
17147   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17148   if (!DRE)
17149     return true;
17150 
17151   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17152   if (!EnumConstant)
17153     return true;
17154 
17155   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17156       Enum)
17157     return true;
17158 
17159   return false;
17160 }
17161 
17162 // Emits a warning when an element is implicitly set a value that
17163 // a previous element has already been set to.
17164 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17165                                         EnumDecl *Enum, QualType EnumType) {
17166   // Avoid anonymous enums
17167   if (!Enum->getIdentifier())
17168     return;
17169 
17170   // Only check for small enums.
17171   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17172     return;
17173 
17174   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17175     return;
17176 
17177   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17178   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17179 
17180   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17181   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17182 
17183   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17184   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17185     llvm::APSInt Val = D->getInitVal();
17186     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17187   };
17188 
17189   DuplicatesVector DupVector;
17190   ValueToVectorMap EnumMap;
17191 
17192   // Populate the EnumMap with all values represented by enum constants without
17193   // an initializer.
17194   for (auto *Element : Elements) {
17195     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17196 
17197     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17198     // this constant.  Skip this enum since it may be ill-formed.
17199     if (!ECD) {
17200       return;
17201     }
17202 
17203     // Constants with initalizers are handled in the next loop.
17204     if (ECD->getInitExpr())
17205       continue;
17206 
17207     // Duplicate values are handled in the next loop.
17208     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17209   }
17210 
17211   if (EnumMap.size() == 0)
17212     return;
17213 
17214   // Create vectors for any values that has duplicates.
17215   for (auto *Element : Elements) {
17216     // The last loop returned if any constant was null.
17217     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17218     if (!ValidDuplicateEnum(ECD, Enum))
17219       continue;
17220 
17221     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17222     if (Iter == EnumMap.end())
17223       continue;
17224 
17225     DeclOrVector& Entry = Iter->second;
17226     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17227       // Ensure constants are different.
17228       if (D == ECD)
17229         continue;
17230 
17231       // Create new vector and push values onto it.
17232       auto Vec = std::make_unique<ECDVector>();
17233       Vec->push_back(D);
17234       Vec->push_back(ECD);
17235 
17236       // Update entry to point to the duplicates vector.
17237       Entry = Vec.get();
17238 
17239       // Store the vector somewhere we can consult later for quick emission of
17240       // diagnostics.
17241       DupVector.emplace_back(std::move(Vec));
17242       continue;
17243     }
17244 
17245     ECDVector *Vec = Entry.get<ECDVector*>();
17246     // Make sure constants are not added more than once.
17247     if (*Vec->begin() == ECD)
17248       continue;
17249 
17250     Vec->push_back(ECD);
17251   }
17252 
17253   // Emit diagnostics.
17254   for (const auto &Vec : DupVector) {
17255     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17256 
17257     // Emit warning for one enum constant.
17258     auto *FirstECD = Vec->front();
17259     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17260       << FirstECD << FirstECD->getInitVal().toString(10)
17261       << FirstECD->getSourceRange();
17262 
17263     // Emit one note for each of the remaining enum constants with
17264     // the same value.
17265     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17266       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17267         << ECD << ECD->getInitVal().toString(10)
17268         << ECD->getSourceRange();
17269   }
17270 }
17271 
17272 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17273                              bool AllowMask) const {
17274   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17275   assert(ED->isCompleteDefinition() && "expected enum definition");
17276 
17277   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17278   llvm::APInt &FlagBits = R.first->second;
17279 
17280   if (R.second) {
17281     for (auto *E : ED->enumerators()) {
17282       const auto &EVal = E->getInitVal();
17283       // Only single-bit enumerators introduce new flag values.
17284       if (EVal.isPowerOf2())
17285         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17286     }
17287   }
17288 
17289   // A value is in a flag enum if either its bits are a subset of the enum's
17290   // flag bits (the first condition) or we are allowing masks and the same is
17291   // true of its complement (the second condition). When masks are allowed, we
17292   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17293   //
17294   // While it's true that any value could be used as a mask, the assumption is
17295   // that a mask will have all of the insignificant bits set. Anything else is
17296   // likely a logic error.
17297   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17298   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17299 }
17300 
17301 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17302                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17303                          const ParsedAttributesView &Attrs) {
17304   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17305   QualType EnumType = Context.getTypeDeclType(Enum);
17306 
17307   ProcessDeclAttributeList(S, Enum, Attrs);
17308 
17309   if (Enum->isDependentType()) {
17310     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17311       EnumConstantDecl *ECD =
17312         cast_or_null<EnumConstantDecl>(Elements[i]);
17313       if (!ECD) continue;
17314 
17315       ECD->setType(EnumType);
17316     }
17317 
17318     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17319     return;
17320   }
17321 
17322   // TODO: If the result value doesn't fit in an int, it must be a long or long
17323   // long value.  ISO C does not support this, but GCC does as an extension,
17324   // emit a warning.
17325   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17326   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17327   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17328 
17329   // Verify that all the values are okay, compute the size of the values, and
17330   // reverse the list.
17331   unsigned NumNegativeBits = 0;
17332   unsigned NumPositiveBits = 0;
17333 
17334   // Keep track of whether all elements have type int.
17335   bool AllElementsInt = true;
17336 
17337   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17338     EnumConstantDecl *ECD =
17339       cast_or_null<EnumConstantDecl>(Elements[i]);
17340     if (!ECD) continue;  // Already issued a diagnostic.
17341 
17342     const llvm::APSInt &InitVal = ECD->getInitVal();
17343 
17344     // Keep track of the size of positive and negative values.
17345     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17346       NumPositiveBits = std::max(NumPositiveBits,
17347                                  (unsigned)InitVal.getActiveBits());
17348     else
17349       NumNegativeBits = std::max(NumNegativeBits,
17350                                  (unsigned)InitVal.getMinSignedBits());
17351 
17352     // Keep track of whether every enum element has type int (very common).
17353     if (AllElementsInt)
17354       AllElementsInt = ECD->getType() == Context.IntTy;
17355   }
17356 
17357   // Figure out the type that should be used for this enum.
17358   QualType BestType;
17359   unsigned BestWidth;
17360 
17361   // C++0x N3000 [conv.prom]p3:
17362   //   An rvalue of an unscoped enumeration type whose underlying
17363   //   type is not fixed can be converted to an rvalue of the first
17364   //   of the following types that can represent all the values of
17365   //   the enumeration: int, unsigned int, long int, unsigned long
17366   //   int, long long int, or unsigned long long int.
17367   // C99 6.4.4.3p2:
17368   //   An identifier declared as an enumeration constant has type int.
17369   // The C99 rule is modified by a gcc extension
17370   QualType BestPromotionType;
17371 
17372   bool Packed = Enum->hasAttr<PackedAttr>();
17373   // -fshort-enums is the equivalent to specifying the packed attribute on all
17374   // enum definitions.
17375   if (LangOpts.ShortEnums)
17376     Packed = true;
17377 
17378   // If the enum already has a type because it is fixed or dictated by the
17379   // target, promote that type instead of analyzing the enumerators.
17380   if (Enum->isComplete()) {
17381     BestType = Enum->getIntegerType();
17382     if (BestType->isPromotableIntegerType())
17383       BestPromotionType = Context.getPromotedIntegerType(BestType);
17384     else
17385       BestPromotionType = BestType;
17386 
17387     BestWidth = Context.getIntWidth(BestType);
17388   }
17389   else if (NumNegativeBits) {
17390     // If there is a negative value, figure out the smallest integer type (of
17391     // int/long/longlong) that fits.
17392     // If it's packed, check also if it fits a char or a short.
17393     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17394       BestType = Context.SignedCharTy;
17395       BestWidth = CharWidth;
17396     } else if (Packed && NumNegativeBits <= ShortWidth &&
17397                NumPositiveBits < ShortWidth) {
17398       BestType = Context.ShortTy;
17399       BestWidth = ShortWidth;
17400     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17401       BestType = Context.IntTy;
17402       BestWidth = IntWidth;
17403     } else {
17404       BestWidth = Context.getTargetInfo().getLongWidth();
17405 
17406       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17407         BestType = Context.LongTy;
17408       } else {
17409         BestWidth = Context.getTargetInfo().getLongLongWidth();
17410 
17411         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17412           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17413         BestType = Context.LongLongTy;
17414       }
17415     }
17416     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17417   } else {
17418     // If there is no negative value, figure out the smallest type that fits
17419     // all of the enumerator values.
17420     // If it's packed, check also if it fits a char or a short.
17421     if (Packed && NumPositiveBits <= CharWidth) {
17422       BestType = Context.UnsignedCharTy;
17423       BestPromotionType = Context.IntTy;
17424       BestWidth = CharWidth;
17425     } else if (Packed && NumPositiveBits <= ShortWidth) {
17426       BestType = Context.UnsignedShortTy;
17427       BestPromotionType = Context.IntTy;
17428       BestWidth = ShortWidth;
17429     } else if (NumPositiveBits <= IntWidth) {
17430       BestType = Context.UnsignedIntTy;
17431       BestWidth = IntWidth;
17432       BestPromotionType
17433         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17434                            ? Context.UnsignedIntTy : Context.IntTy;
17435     } else if (NumPositiveBits <=
17436                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17437       BestType = Context.UnsignedLongTy;
17438       BestPromotionType
17439         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17440                            ? Context.UnsignedLongTy : Context.LongTy;
17441     } else {
17442       BestWidth = Context.getTargetInfo().getLongLongWidth();
17443       assert(NumPositiveBits <= BestWidth &&
17444              "How could an initializer get larger than ULL?");
17445       BestType = Context.UnsignedLongLongTy;
17446       BestPromotionType
17447         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17448                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17449     }
17450   }
17451 
17452   // Loop over all of the enumerator constants, changing their types to match
17453   // the type of the enum if needed.
17454   for (auto *D : Elements) {
17455     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17456     if (!ECD) continue;  // Already issued a diagnostic.
17457 
17458     // Standard C says the enumerators have int type, but we allow, as an
17459     // extension, the enumerators to be larger than int size.  If each
17460     // enumerator value fits in an int, type it as an int, otherwise type it the
17461     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17462     // that X has type 'int', not 'unsigned'.
17463 
17464     // Determine whether the value fits into an int.
17465     llvm::APSInt InitVal = ECD->getInitVal();
17466 
17467     // If it fits into an integer type, force it.  Otherwise force it to match
17468     // the enum decl type.
17469     QualType NewTy;
17470     unsigned NewWidth;
17471     bool NewSign;
17472     if (!getLangOpts().CPlusPlus &&
17473         !Enum->isFixed() &&
17474         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17475       NewTy = Context.IntTy;
17476       NewWidth = IntWidth;
17477       NewSign = true;
17478     } else if (ECD->getType() == BestType) {
17479       // Already the right type!
17480       if (getLangOpts().CPlusPlus)
17481         // C++ [dcl.enum]p4: Following the closing brace of an
17482         // enum-specifier, each enumerator has the type of its
17483         // enumeration.
17484         ECD->setType(EnumType);
17485       continue;
17486     } else {
17487       NewTy = BestType;
17488       NewWidth = BestWidth;
17489       NewSign = BestType->isSignedIntegerOrEnumerationType();
17490     }
17491 
17492     // Adjust the APSInt value.
17493     InitVal = InitVal.extOrTrunc(NewWidth);
17494     InitVal.setIsSigned(NewSign);
17495     ECD->setInitVal(InitVal);
17496 
17497     // Adjust the Expr initializer and type.
17498     if (ECD->getInitExpr() &&
17499         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17500       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17501                                                 CK_IntegralCast,
17502                                                 ECD->getInitExpr(),
17503                                                 /*base paths*/ nullptr,
17504                                                 VK_RValue));
17505     if (getLangOpts().CPlusPlus)
17506       // C++ [dcl.enum]p4: Following the closing brace of an
17507       // enum-specifier, each enumerator has the type of its
17508       // enumeration.
17509       ECD->setType(EnumType);
17510     else
17511       ECD->setType(NewTy);
17512   }
17513 
17514   Enum->completeDefinition(BestType, BestPromotionType,
17515                            NumPositiveBits, NumNegativeBits);
17516 
17517   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17518 
17519   if (Enum->isClosedFlag()) {
17520     for (Decl *D : Elements) {
17521       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17522       if (!ECD) continue;  // Already issued a diagnostic.
17523 
17524       llvm::APSInt InitVal = ECD->getInitVal();
17525       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17526           !IsValueInFlagEnum(Enum, InitVal, true))
17527         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17528           << ECD << Enum;
17529     }
17530   }
17531 
17532   // Now that the enum type is defined, ensure it's not been underaligned.
17533   if (Enum->hasAttrs())
17534     CheckAlignasUnderalignment(Enum);
17535 }
17536 
17537 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17538                                   SourceLocation StartLoc,
17539                                   SourceLocation EndLoc) {
17540   StringLiteral *AsmString = cast<StringLiteral>(expr);
17541 
17542   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17543                                                    AsmString, StartLoc,
17544                                                    EndLoc);
17545   CurContext->addDecl(New);
17546   return New;
17547 }
17548 
17549 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17550                                       IdentifierInfo* AliasName,
17551                                       SourceLocation PragmaLoc,
17552                                       SourceLocation NameLoc,
17553                                       SourceLocation AliasNameLoc) {
17554   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17555                                          LookupOrdinaryName);
17556   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17557                            AttributeCommonInfo::AS_Pragma);
17558   AsmLabelAttr *Attr =
17559       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
17560 
17561   // If a declaration that:
17562   // 1) declares a function or a variable
17563   // 2) has external linkage
17564   // already exists, add a label attribute to it.
17565   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17566     if (isDeclExternC(PrevDecl))
17567       PrevDecl->addAttr(Attr);
17568     else
17569       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17570           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17571   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17572   } else
17573     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17574 }
17575 
17576 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17577                              SourceLocation PragmaLoc,
17578                              SourceLocation NameLoc) {
17579   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17580 
17581   if (PrevDecl) {
17582     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17583   } else {
17584     (void)WeakUndeclaredIdentifiers.insert(
17585       std::pair<IdentifierInfo*,WeakInfo>
17586         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17587   }
17588 }
17589 
17590 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17591                                 IdentifierInfo* AliasName,
17592                                 SourceLocation PragmaLoc,
17593                                 SourceLocation NameLoc,
17594                                 SourceLocation AliasNameLoc) {
17595   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17596                                     LookupOrdinaryName);
17597   WeakInfo W = WeakInfo(Name, NameLoc);
17598 
17599   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17600     if (!PrevDecl->hasAttr<AliasAttr>())
17601       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17602         DeclApplyPragmaWeak(TUScope, ND, W);
17603   } else {
17604     (void)WeakUndeclaredIdentifiers.insert(
17605       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17606   }
17607 }
17608 
17609 Decl *Sema::getObjCDeclContext() const {
17610   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17611 }
17612