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 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
849                                             IdentifierInfo *&Name,
850                                             SourceLocation NameLoc,
851                                             const Token &NextToken,
852                                             CorrectionCandidateCallback *CCC) {
853   DeclarationNameInfo NameInfo(Name, NameLoc);
854   ObjCMethodDecl *CurMethod = getCurMethodDecl();
855 
856   assert(NextToken.isNot(tok::coloncolon) &&
857          "parse nested name specifiers before calling ClassifyName");
858   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     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
884     if (Ivar.isInvalid())
885       return NameClassification::Error();
886     if (Ivar.isUsable())
887       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
888 
889     // We defer builtin creation until after ivar lookup inside ObjC methods.
890     if (Result.empty())
891       LookupBuiltin(Result);
892   }
893 
894   bool SecondTry = false;
895   bool IsFilteredTemplateName = false;
896 
897 Corrected:
898   switch (Result.getResultKind()) {
899   case LookupResult::NotFound:
900     // If an unqualified-id is followed by a '(', then we have a function
901     // call.
902     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
903       // In C++, this is an ADL-only call.
904       // FIXME: Reference?
905       if (getLangOpts().CPlusPlus)
906         return NameClassification::UndeclaredNonType();
907 
908       // C90 6.3.2.2:
909       //   If the expression that precedes the parenthesized argument list in a
910       //   function call consists solely of an identifier, and if no
911       //   declaration is visible for this identifier, the identifier is
912       //   implicitly declared exactly as if, in the innermost block containing
913       //   the function call, the declaration
914       //
915       //     extern int identifier ();
916       //
917       //   appeared.
918       //
919       // We also allow this in C99 as an extension.
920       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
921         return NameClassification::NonType(D);
922     }
923 
924     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
925       // In C++20 onwards, this could be an ADL-only call to a function
926       // template, and we're required to assume that this is a template name.
927       //
928       // FIXME: Find a way to still do typo correction in this case.
929       TemplateName Template =
930           Context.getAssumedTemplateName(NameInfo.getName());
931       return NameClassification::UndeclaredTemplate(Template);
932     }
933 
934     // In C, we first see whether there is a tag type by the same name, in
935     // which case it's likely that the user just forgot to write "enum",
936     // "struct", or "union".
937     if (!getLangOpts().CPlusPlus && !SecondTry &&
938         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
939       break;
940     }
941 
942     // Perform typo correction to determine if there is another name that is
943     // close to this name.
944     if (!SecondTry && CCC) {
945       SecondTry = true;
946       if (TypoCorrection Corrected =
947               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
948                           &SS, *CCC, CTK_ErrorRecovery)) {
949         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
950         unsigned QualifiedDiag = diag::err_no_member_suggest;
951 
952         NamedDecl *FirstDecl = Corrected.getFoundDecl();
953         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
954         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
955             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
956           UnqualifiedDiag = diag::err_no_template_suggest;
957           QualifiedDiag = diag::err_no_member_template_suggest;
958         } else if (UnderlyingFirstDecl &&
959                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
960                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
961                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
962           UnqualifiedDiag = diag::err_unknown_typename_suggest;
963           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
964         }
965 
966         if (SS.isEmpty()) {
967           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
968         } else {// FIXME: is this even reachable? Test it.
969           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
970           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
971                                   Name->getName().equals(CorrectedStr);
972           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
973                                     << Name << computeDeclContext(SS, false)
974                                     << DroppedSpecifier << SS.getRange());
975         }
976 
977         // Update the name, so that the caller has the new name.
978         Name = Corrected.getCorrectionAsIdentifierInfo();
979 
980         // Typo correction corrected to a keyword.
981         if (Corrected.isKeyword())
982           return Name;
983 
984         // Also update the LookupResult...
985         // FIXME: This should probably go away at some point
986         Result.clear();
987         Result.setLookupName(Corrected.getCorrection());
988         if (FirstDecl)
989           Result.addDecl(FirstDecl);
990 
991         // If we found an Objective-C instance variable, let
992         // LookupInObjCMethod build the appropriate expression to
993         // reference the ivar.
994         // FIXME: This is a gross hack.
995         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
996           DeclResult R =
997               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
998           if (R.isInvalid())
999             return NameClassification::Error();
1000           if (R.isUsable())
1001             return NameClassification::NonType(Ivar);
1002         }
1003 
1004         goto Corrected;
1005       }
1006     }
1007 
1008     // We failed to correct; just fall through and let the parser deal with it.
1009     Result.suppressDiagnostics();
1010     return NameClassification::Unknown();
1011 
1012   case LookupResult::NotFoundInCurrentInstantiation: {
1013     // We performed name lookup into the current instantiation, and there were
1014     // dependent bases, so we treat this result the same way as any other
1015     // dependent nested-name-specifier.
1016 
1017     // C++ [temp.res]p2:
1018     //   A name used in a template declaration or definition and that is
1019     //   dependent on a template-parameter is assumed not to name a type
1020     //   unless the applicable name lookup finds a type name or the name is
1021     //   qualified by the keyword typename.
1022     //
1023     // FIXME: If the next token is '<', we might want to ask the parser to
1024     // perform some heroics to see if we actually have a
1025     // template-argument-list, which would indicate a missing 'template'
1026     // keyword here.
1027     return NameClassification::DependentNonType();
1028   }
1029 
1030   case LookupResult::Found:
1031   case LookupResult::FoundOverloaded:
1032   case LookupResult::FoundUnresolvedValue:
1033     break;
1034 
1035   case LookupResult::Ambiguous:
1036     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1037         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1038                                       /*AllowDependent=*/false)) {
1039       // C++ [temp.local]p3:
1040       //   A lookup that finds an injected-class-name (10.2) can result in an
1041       //   ambiguity in certain cases (for example, if it is found in more than
1042       //   one base class). If all of the injected-class-names that are found
1043       //   refer to specializations of the same class template, and if the name
1044       //   is followed by a template-argument-list, the reference refers to the
1045       //   class template itself and not a specialization thereof, and is not
1046       //   ambiguous.
1047       //
1048       // This filtering can make an ambiguous result into an unambiguous one,
1049       // so try again after filtering out template names.
1050       FilterAcceptableTemplateNames(Result);
1051       if (!Result.isAmbiguous()) {
1052         IsFilteredTemplateName = true;
1053         break;
1054       }
1055     }
1056 
1057     // Diagnose the ambiguity and return an error.
1058     return NameClassification::Error();
1059   }
1060 
1061   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1062       (IsFilteredTemplateName ||
1063        hasAnyAcceptableTemplateNames(
1064            Result, /*AllowFunctionTemplates=*/true,
1065            /*AllowDependent=*/false,
1066            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1067                getLangOpts().CPlusPlus2a))) {
1068     // C++ [temp.names]p3:
1069     //   After name lookup (3.4) finds that a name is a template-name or that
1070     //   an operator-function-id or a literal- operator-id refers to a set of
1071     //   overloaded functions any member of which is a function template if
1072     //   this is followed by a <, the < is always taken as the delimiter of a
1073     //   template-argument-list and never as the less-than operator.
1074     // C++2a [temp.names]p2:
1075     //   A name is also considered to refer to a template if it is an
1076     //   unqualified-id followed by a < and name lookup finds either one
1077     //   or more functions or finds nothing.
1078     if (!IsFilteredTemplateName)
1079       FilterAcceptableTemplateNames(Result);
1080 
1081     bool IsFunctionTemplate;
1082     bool IsVarTemplate;
1083     TemplateName Template;
1084     if (Result.end() - Result.begin() > 1) {
1085       IsFunctionTemplate = true;
1086       Template = Context.getOverloadedTemplateName(Result.begin(),
1087                                                    Result.end());
1088     } else if (!Result.empty()) {
1089       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1090           *Result.begin(), /*AllowFunctionTemplates=*/true,
1091           /*AllowDependent=*/false));
1092       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1093       IsVarTemplate = isa<VarTemplateDecl>(TD);
1094 
1095       if (SS.isSet() && !SS.isInvalid())
1096         Template =
1097             Context.getQualifiedTemplateName(SS.getScopeRep(),
1098                                              /*TemplateKeyword=*/false, TD);
1099       else
1100         Template = TemplateName(TD);
1101     } else {
1102       // All results were non-template functions. This is a function template
1103       // name.
1104       IsFunctionTemplate = true;
1105       Template = Context.getAssumedTemplateName(NameInfo.getName());
1106     }
1107 
1108     if (IsFunctionTemplate) {
1109       // Function templates always go through overload resolution, at which
1110       // point we'll perform the various checks (e.g., accessibility) we need
1111       // to based on which function we selected.
1112       Result.suppressDiagnostics();
1113 
1114       return NameClassification::FunctionTemplate(Template);
1115     }
1116 
1117     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1118                          : NameClassification::TypeTemplate(Template);
1119   }
1120 
1121   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1122   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1123     DiagnoseUseOfDecl(Type, NameLoc);
1124     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1125     QualType T = Context.getTypeDeclType(Type);
1126     if (SS.isNotEmpty())
1127       return buildNestedType(*this, SS, T, NameLoc);
1128     return ParsedType::make(T);
1129   }
1130 
1131   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1132   if (!Class) {
1133     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1134     if (ObjCCompatibleAliasDecl *Alias =
1135             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1136       Class = Alias->getClassInterface();
1137   }
1138 
1139   if (Class) {
1140     DiagnoseUseOfDecl(Class, NameLoc);
1141 
1142     if (NextToken.is(tok::period)) {
1143       // Interface. <something> is parsed as a property reference expression.
1144       // Just return "unknown" as a fall-through for now.
1145       Result.suppressDiagnostics();
1146       return NameClassification::Unknown();
1147     }
1148 
1149     QualType T = Context.getObjCInterfaceType(Class);
1150     return ParsedType::make(T);
1151   }
1152 
1153   // We can have a type template here if we're classifying a template argument.
1154   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1155       !isa<VarTemplateDecl>(FirstDecl))
1156     return NameClassification::TypeTemplate(
1157         TemplateName(cast<TemplateDecl>(FirstDecl)));
1158 
1159   // Check for a tag type hidden by a non-type decl in a few cases where it
1160   // seems likely a type is wanted instead of the non-type that was found.
1161   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1162   if ((NextToken.is(tok::identifier) ||
1163        (NextIsOp &&
1164         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1165       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1166     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1167     DiagnoseUseOfDecl(Type, NameLoc);
1168     QualType T = Context.getTypeDeclType(Type);
1169     if (SS.isNotEmpty())
1170       return buildNestedType(*this, SS, T, NameLoc);
1171     return ParsedType::make(T);
1172   }
1173 
1174   // FIXME: This is context-dependent. We need to defer building the member
1175   // expression until the classification is consumed.
1176   if (FirstDecl->isCXXClassMember())
1177     return NameClassification::ContextIndependentExpr(
1178         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1179                                         S));
1180 
1181   // If we already know which single declaration is referenced, just annotate
1182   // that declaration directly.
1183   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1184   if (Result.isSingleResult() && !ADL)
1185     return NameClassification::NonType(Result.getRepresentativeDecl());
1186 
1187   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1188   // context in which we performed classification, so it's safe to do now.
1189   return NameClassification::ContextIndependentExpr(
1190       BuildDeclarationNameExpr(SS, Result, ADL));
1191 }
1192 
1193 ExprResult
1194 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1195                                              SourceLocation NameLoc) {
1196   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1197   CXXScopeSpec SS;
1198   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1199   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1200 }
1201 
1202 ExprResult
1203 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1204                                             IdentifierInfo *Name,
1205                                             SourceLocation NameLoc,
1206                                             bool IsAddressOfOperand) {
1207   DeclarationNameInfo NameInfo(Name, NameLoc);
1208   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1209                                     NameInfo, IsAddressOfOperand,
1210                                     /*TemplateArgs=*/nullptr);
1211 }
1212 
1213 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1214                                               NamedDecl *Found,
1215                                               SourceLocation NameLoc,
1216                                               const Token &NextToken) {
1217   if (getCurMethodDecl() && SS.isEmpty())
1218     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1219       return BuildIvarRefExpr(S, NameLoc, Ivar);
1220 
1221   // Reconstruct the lookup result.
1222   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1223   Result.addDecl(Found);
1224   Result.resolveKind();
1225 
1226   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1227   return BuildDeclarationNameExpr(SS, Result, ADL);
1228 }
1229 
1230 Sema::TemplateNameKindForDiagnostics
1231 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1232   auto *TD = Name.getAsTemplateDecl();
1233   if (!TD)
1234     return TemplateNameKindForDiagnostics::DependentTemplate;
1235   if (isa<ClassTemplateDecl>(TD))
1236     return TemplateNameKindForDiagnostics::ClassTemplate;
1237   if (isa<FunctionTemplateDecl>(TD))
1238     return TemplateNameKindForDiagnostics::FunctionTemplate;
1239   if (isa<VarTemplateDecl>(TD))
1240     return TemplateNameKindForDiagnostics::VarTemplate;
1241   if (isa<TypeAliasTemplateDecl>(TD))
1242     return TemplateNameKindForDiagnostics::AliasTemplate;
1243   if (isa<TemplateTemplateParmDecl>(TD))
1244     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1245   if (isa<ConceptDecl>(TD))
1246     return TemplateNameKindForDiagnostics::Concept;
1247   return TemplateNameKindForDiagnostics::DependentTemplate;
1248 }
1249 
1250 // Determines the context to return to after temporarily entering a
1251 // context.  This depends in an unnecessarily complicated way on the
1252 // exact ordering of callbacks from the parser.
1253 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1254 
1255   // Functions defined inline within classes aren't parsed until we've
1256   // finished parsing the top-level class, so the top-level class is
1257   // the context we'll need to return to.
1258   // A Lambda call operator whose parent is a class must not be treated
1259   // as an inline member function.  A Lambda can be used legally
1260   // either as an in-class member initializer or a default argument.  These
1261   // are parsed once the class has been marked complete and so the containing
1262   // context would be the nested class (when the lambda is defined in one);
1263   // If the class is not complete, then the lambda is being used in an
1264   // ill-formed fashion (such as to specify the width of a bit-field, or
1265   // in an array-bound) - in which case we still want to return the
1266   // lexically containing DC (which could be a nested class).
1267   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1268     DC = DC->getLexicalParent();
1269 
1270     // A function not defined within a class will always return to its
1271     // lexical context.
1272     if (!isa<CXXRecordDecl>(DC))
1273       return DC;
1274 
1275     // A C++ inline method/friend is parsed *after* the topmost class
1276     // it was declared in is fully parsed ("complete");  the topmost
1277     // class is the context we need to return to.
1278     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1279       DC = RD;
1280 
1281     // Return the declaration context of the topmost class the inline method is
1282     // declared in.
1283     return DC;
1284   }
1285 
1286   return DC->getLexicalParent();
1287 }
1288 
1289 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1290   assert(getContainingDC(DC) == CurContext &&
1291       "The next DeclContext should be lexically contained in the current one.");
1292   CurContext = DC;
1293   S->setEntity(DC);
1294 }
1295 
1296 void Sema::PopDeclContext() {
1297   assert(CurContext && "DeclContext imbalance!");
1298 
1299   CurContext = getContainingDC(CurContext);
1300   assert(CurContext && "Popped translation unit!");
1301 }
1302 
1303 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1304                                                                     Decl *D) {
1305   // Unlike PushDeclContext, the context to which we return is not necessarily
1306   // the containing DC of TD, because the new context will be some pre-existing
1307   // TagDecl definition instead of a fresh one.
1308   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1309   CurContext = cast<TagDecl>(D)->getDefinition();
1310   assert(CurContext && "skipping definition of undefined tag");
1311   // Start lookups from the parent of the current context; we don't want to look
1312   // into the pre-existing complete definition.
1313   S->setEntity(CurContext->getLookupParent());
1314   return Result;
1315 }
1316 
1317 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1318   CurContext = static_cast<decltype(CurContext)>(Context);
1319 }
1320 
1321 /// EnterDeclaratorContext - Used when we must lookup names in the context
1322 /// of a declarator's nested name specifier.
1323 ///
1324 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1325   // C++0x [basic.lookup.unqual]p13:
1326   //   A name used in the definition of a static data member of class
1327   //   X (after the qualified-id of the static member) is looked up as
1328   //   if the name was used in a member function of X.
1329   // C++0x [basic.lookup.unqual]p14:
1330   //   If a variable member of a namespace is defined outside of the
1331   //   scope of its namespace then any name used in the definition of
1332   //   the variable member (after the declarator-id) is looked up as
1333   //   if the definition of the variable member occurred in its
1334   //   namespace.
1335   // Both of these imply that we should push a scope whose context
1336   // is the semantic context of the declaration.  We can't use
1337   // PushDeclContext here because that context is not necessarily
1338   // lexically contained in the current context.  Fortunately,
1339   // the containing scope should have the appropriate information.
1340 
1341   assert(!S->getEntity() && "scope already has entity");
1342 
1343 #ifndef NDEBUG
1344   Scope *Ancestor = S->getParent();
1345   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1346   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1347 #endif
1348 
1349   CurContext = DC;
1350   S->setEntity(DC);
1351 }
1352 
1353 void Sema::ExitDeclaratorContext(Scope *S) {
1354   assert(S->getEntity() == CurContext && "Context imbalance!");
1355 
1356   // Switch back to the lexical context.  The safety of this is
1357   // enforced by an assert in EnterDeclaratorContext.
1358   Scope *Ancestor = S->getParent();
1359   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1360   CurContext = Ancestor->getEntity();
1361 
1362   // We don't need to do anything with the scope, which is going to
1363   // disappear.
1364 }
1365 
1366 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1367   // We assume that the caller has already called
1368   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1369   FunctionDecl *FD = D->getAsFunction();
1370   if (!FD)
1371     return;
1372 
1373   // Same implementation as PushDeclContext, but enters the context
1374   // from the lexical parent, rather than the top-level class.
1375   assert(CurContext == FD->getLexicalParent() &&
1376     "The next DeclContext should be lexically contained in the current one.");
1377   CurContext = FD;
1378   S->setEntity(CurContext);
1379 
1380   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1381     ParmVarDecl *Param = FD->getParamDecl(P);
1382     // If the parameter has an identifier, then add it to the scope
1383     if (Param->getIdentifier()) {
1384       S->AddDecl(Param);
1385       IdResolver.AddDecl(Param);
1386     }
1387   }
1388 }
1389 
1390 void Sema::ActOnExitFunctionContext() {
1391   // Same implementation as PopDeclContext, but returns to the lexical parent,
1392   // rather than the top-level class.
1393   assert(CurContext && "DeclContext imbalance!");
1394   CurContext = CurContext->getLexicalParent();
1395   assert(CurContext && "Popped translation unit!");
1396 }
1397 
1398 /// Determine whether we allow overloading of the function
1399 /// PrevDecl with another declaration.
1400 ///
1401 /// This routine determines whether overloading is possible, not
1402 /// whether some new function is actually an overload. It will return
1403 /// true in C++ (where we can always provide overloads) or, as an
1404 /// extension, in C when the previous function is already an
1405 /// overloaded function declaration or has the "overloadable"
1406 /// attribute.
1407 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1408                                        ASTContext &Context,
1409                                        const FunctionDecl *New) {
1410   if (Context.getLangOpts().CPlusPlus)
1411     return true;
1412 
1413   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1414     return true;
1415 
1416   return Previous.getResultKind() == LookupResult::Found &&
1417          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1418           New->hasAttr<OverloadableAttr>());
1419 }
1420 
1421 /// Add this decl to the scope shadowed decl chains.
1422 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1423   // Move up the scope chain until we find the nearest enclosing
1424   // non-transparent context. The declaration will be introduced into this
1425   // scope.
1426   while (S->getEntity() && S->getEntity()->isTransparentContext())
1427     S = S->getParent();
1428 
1429   // Add scoped declarations into their context, so that they can be
1430   // found later. Declarations without a context won't be inserted
1431   // into any context.
1432   if (AddToContext)
1433     CurContext->addDecl(D);
1434 
1435   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1436   // are function-local declarations.
1437   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1438       !D->getDeclContext()->getRedeclContext()->Equals(
1439         D->getLexicalDeclContext()->getRedeclContext()) &&
1440       !D->getLexicalDeclContext()->isFunctionOrMethod())
1441     return;
1442 
1443   // Template instantiations should also not be pushed into scope.
1444   if (isa<FunctionDecl>(D) &&
1445       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1446     return;
1447 
1448   // If this replaces anything in the current scope,
1449   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1450                                IEnd = IdResolver.end();
1451   for (; I != IEnd; ++I) {
1452     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1453       S->RemoveDecl(*I);
1454       IdResolver.RemoveDecl(*I);
1455 
1456       // Should only need to replace one decl.
1457       break;
1458     }
1459   }
1460 
1461   S->AddDecl(D);
1462 
1463   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1464     // Implicitly-generated labels may end up getting generated in an order that
1465     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1466     // the label at the appropriate place in the identifier chain.
1467     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1468       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1469       if (IDC == CurContext) {
1470         if (!S->isDeclScope(*I))
1471           continue;
1472       } else if (IDC->Encloses(CurContext))
1473         break;
1474     }
1475 
1476     IdResolver.InsertDeclAfter(I, D);
1477   } else {
1478     IdResolver.AddDecl(D);
1479   }
1480 }
1481 
1482 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1483                          bool AllowInlineNamespace) {
1484   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1485 }
1486 
1487 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1488   DeclContext *TargetDC = DC->getPrimaryContext();
1489   do {
1490     if (DeclContext *ScopeDC = S->getEntity())
1491       if (ScopeDC->getPrimaryContext() == TargetDC)
1492         return S;
1493   } while ((S = S->getParent()));
1494 
1495   return nullptr;
1496 }
1497 
1498 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1499                                             DeclContext*,
1500                                             ASTContext&);
1501 
1502 /// Filters out lookup results that don't fall within the given scope
1503 /// as determined by isDeclInScope.
1504 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1505                                 bool ConsiderLinkage,
1506                                 bool AllowInlineNamespace) {
1507   LookupResult::Filter F = R.makeFilter();
1508   while (F.hasNext()) {
1509     NamedDecl *D = F.next();
1510 
1511     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1512       continue;
1513 
1514     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1515       continue;
1516 
1517     F.erase();
1518   }
1519 
1520   F.done();
1521 }
1522 
1523 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1524 /// have compatible owning modules.
1525 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1526   // FIXME: The Modules TS is not clear about how friend declarations are
1527   // to be treated. It's not meaningful to have different owning modules for
1528   // linkage in redeclarations of the same entity, so for now allow the
1529   // redeclaration and change the owning modules to match.
1530   if (New->getFriendObjectKind() &&
1531       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1532     New->setLocalOwningModule(Old->getOwningModule());
1533     makeMergedDefinitionVisible(New);
1534     return false;
1535   }
1536 
1537   Module *NewM = New->getOwningModule();
1538   Module *OldM = Old->getOwningModule();
1539 
1540   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1541     NewM = NewM->Parent;
1542   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1543     OldM = OldM->Parent;
1544 
1545   if (NewM == OldM)
1546     return false;
1547 
1548   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1549   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1550   if (NewIsModuleInterface || OldIsModuleInterface) {
1551     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1552     //   if a declaration of D [...] appears in the purview of a module, all
1553     //   other such declarations shall appear in the purview of the same module
1554     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1555       << New
1556       << NewIsModuleInterface
1557       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1558       << OldIsModuleInterface
1559       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1560     Diag(Old->getLocation(), diag::note_previous_declaration);
1561     New->setInvalidDecl();
1562     return true;
1563   }
1564 
1565   return false;
1566 }
1567 
1568 static bool isUsingDecl(NamedDecl *D) {
1569   return isa<UsingShadowDecl>(D) ||
1570          isa<UnresolvedUsingTypenameDecl>(D) ||
1571          isa<UnresolvedUsingValueDecl>(D);
1572 }
1573 
1574 /// Removes using shadow declarations from the lookup results.
1575 static void RemoveUsingDecls(LookupResult &R) {
1576   LookupResult::Filter F = R.makeFilter();
1577   while (F.hasNext())
1578     if (isUsingDecl(F.next()))
1579       F.erase();
1580 
1581   F.done();
1582 }
1583 
1584 /// Check for this common pattern:
1585 /// @code
1586 /// class S {
1587 ///   S(const S&); // DO NOT IMPLEMENT
1588 ///   void operator=(const S&); // DO NOT IMPLEMENT
1589 /// };
1590 /// @endcode
1591 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1592   // FIXME: Should check for private access too but access is set after we get
1593   // the decl here.
1594   if (D->doesThisDeclarationHaveABody())
1595     return false;
1596 
1597   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1598     return CD->isCopyConstructor();
1599   return D->isCopyAssignmentOperator();
1600 }
1601 
1602 // We need this to handle
1603 //
1604 // typedef struct {
1605 //   void *foo() { return 0; }
1606 // } A;
1607 //
1608 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1609 // for example. If 'A', foo will have external linkage. If we have '*A',
1610 // foo will have no linkage. Since we can't know until we get to the end
1611 // of the typedef, this function finds out if D might have non-external linkage.
1612 // Callers should verify at the end of the TU if it D has external linkage or
1613 // not.
1614 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1615   const DeclContext *DC = D->getDeclContext();
1616   while (!DC->isTranslationUnit()) {
1617     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1618       if (!RD->hasNameForLinkage())
1619         return true;
1620     }
1621     DC = DC->getParent();
1622   }
1623 
1624   return !D->isExternallyVisible();
1625 }
1626 
1627 // FIXME: This needs to be refactored; some other isInMainFile users want
1628 // these semantics.
1629 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1630   if (S.TUKind != TU_Complete)
1631     return false;
1632   return S.SourceMgr.isInMainFile(Loc);
1633 }
1634 
1635 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1636   assert(D);
1637 
1638   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1639     return false;
1640 
1641   // Ignore all entities declared within templates, and out-of-line definitions
1642   // of members of class templates.
1643   if (D->getDeclContext()->isDependentContext() ||
1644       D->getLexicalDeclContext()->isDependentContext())
1645     return false;
1646 
1647   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1648     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1649       return false;
1650     // A non-out-of-line declaration of a member specialization was implicitly
1651     // instantiated; it's the out-of-line declaration that we're interested in.
1652     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1653         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1654       return false;
1655 
1656     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1657       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1658         return false;
1659     } else {
1660       // 'static inline' functions are defined in headers; don't warn.
1661       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1662         return false;
1663     }
1664 
1665     if (FD->doesThisDeclarationHaveABody() &&
1666         Context.DeclMustBeEmitted(FD))
1667       return false;
1668   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1669     // Constants and utility variables are defined in headers with internal
1670     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1671     // like "inline".)
1672     if (!isMainFileLoc(*this, VD->getLocation()))
1673       return false;
1674 
1675     if (Context.DeclMustBeEmitted(VD))
1676       return false;
1677 
1678     if (VD->isStaticDataMember() &&
1679         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1680       return false;
1681     if (VD->isStaticDataMember() &&
1682         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1683         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1684       return false;
1685 
1686     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1687       return false;
1688   } else {
1689     return false;
1690   }
1691 
1692   // Only warn for unused decls internal to the translation unit.
1693   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1694   // for inline functions defined in the main source file, for instance.
1695   return mightHaveNonExternalLinkage(D);
1696 }
1697 
1698 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1699   if (!D)
1700     return;
1701 
1702   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1703     const FunctionDecl *First = FD->getFirstDecl();
1704     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1705       return; // First should already be in the vector.
1706   }
1707 
1708   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1709     const VarDecl *First = VD->getFirstDecl();
1710     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1711       return; // First should already be in the vector.
1712   }
1713 
1714   if (ShouldWarnIfUnusedFileScopedDecl(D))
1715     UnusedFileScopedDecls.push_back(D);
1716 }
1717 
1718 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1719   if (D->isInvalidDecl())
1720     return false;
1721 
1722   bool Referenced = false;
1723   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1724     // For a decomposition declaration, warn if none of the bindings are
1725     // referenced, instead of if the variable itself is referenced (which
1726     // it is, by the bindings' expressions).
1727     for (auto *BD : DD->bindings()) {
1728       if (BD->isReferenced()) {
1729         Referenced = true;
1730         break;
1731       }
1732     }
1733   } else if (!D->getDeclName()) {
1734     return false;
1735   } else if (D->isReferenced() || D->isUsed()) {
1736     Referenced = true;
1737   }
1738 
1739   if (Referenced || D->hasAttr<UnusedAttr>() ||
1740       D->hasAttr<ObjCPreciseLifetimeAttr>())
1741     return false;
1742 
1743   if (isa<LabelDecl>(D))
1744     return true;
1745 
1746   // Except for labels, we only care about unused decls that are local to
1747   // functions.
1748   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1749   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1750     // For dependent types, the diagnostic is deferred.
1751     WithinFunction =
1752         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1753   if (!WithinFunction)
1754     return false;
1755 
1756   if (isa<TypedefNameDecl>(D))
1757     return true;
1758 
1759   // White-list anything that isn't a local variable.
1760   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1761     return false;
1762 
1763   // Types of valid local variables should be complete, so this should succeed.
1764   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1765 
1766     // White-list anything with an __attribute__((unused)) type.
1767     const auto *Ty = VD->getType().getTypePtr();
1768 
1769     // Only look at the outermost level of typedef.
1770     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1771       if (TT->getDecl()->hasAttr<UnusedAttr>())
1772         return false;
1773     }
1774 
1775     // If we failed to complete the type for some reason, or if the type is
1776     // dependent, don't diagnose the variable.
1777     if (Ty->isIncompleteType() || Ty->isDependentType())
1778       return false;
1779 
1780     // Look at the element type to ensure that the warning behaviour is
1781     // consistent for both scalars and arrays.
1782     Ty = Ty->getBaseElementTypeUnsafe();
1783 
1784     if (const TagType *TT = Ty->getAs<TagType>()) {
1785       const TagDecl *Tag = TT->getDecl();
1786       if (Tag->hasAttr<UnusedAttr>())
1787         return false;
1788 
1789       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1790         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1791           return false;
1792 
1793         if (const Expr *Init = VD->getInit()) {
1794           if (const ExprWithCleanups *Cleanups =
1795                   dyn_cast<ExprWithCleanups>(Init))
1796             Init = Cleanups->getSubExpr();
1797           const CXXConstructExpr *Construct =
1798             dyn_cast<CXXConstructExpr>(Init);
1799           if (Construct && !Construct->isElidable()) {
1800             CXXConstructorDecl *CD = Construct->getConstructor();
1801             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1802                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1803               return false;
1804           }
1805         }
1806       }
1807     }
1808 
1809     // TODO: __attribute__((unused)) templates?
1810   }
1811 
1812   return true;
1813 }
1814 
1815 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1816                                      FixItHint &Hint) {
1817   if (isa<LabelDecl>(D)) {
1818     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1819         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1820         true);
1821     if (AfterColon.isInvalid())
1822       return;
1823     Hint = FixItHint::CreateRemoval(
1824         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1825   }
1826 }
1827 
1828 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1829   if (D->getTypeForDecl()->isDependentType())
1830     return;
1831 
1832   for (auto *TmpD : D->decls()) {
1833     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1834       DiagnoseUnusedDecl(T);
1835     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1836       DiagnoseUnusedNestedTypedefs(R);
1837   }
1838 }
1839 
1840 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1841 /// unless they are marked attr(unused).
1842 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1843   if (!ShouldDiagnoseUnusedDecl(D))
1844     return;
1845 
1846   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1847     // typedefs can be referenced later on, so the diagnostics are emitted
1848     // at end-of-translation-unit.
1849     UnusedLocalTypedefNameCandidates.insert(TD);
1850     return;
1851   }
1852 
1853   FixItHint Hint;
1854   GenerateFixForUnusedDecl(D, Context, Hint);
1855 
1856   unsigned DiagID;
1857   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1858     DiagID = diag::warn_unused_exception_param;
1859   else if (isa<LabelDecl>(D))
1860     DiagID = diag::warn_unused_label;
1861   else
1862     DiagID = diag::warn_unused_variable;
1863 
1864   Diag(D->getLocation(), DiagID) << D << Hint;
1865 }
1866 
1867 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1868   // Verify that we have no forward references left.  If so, there was a goto
1869   // or address of a label taken, but no definition of it.  Label fwd
1870   // definitions are indicated with a null substmt which is also not a resolved
1871   // MS inline assembly label name.
1872   bool Diagnose = false;
1873   if (L->isMSAsmLabel())
1874     Diagnose = !L->isResolvedMSAsmLabel();
1875   else
1876     Diagnose = L->getStmt() == nullptr;
1877   if (Diagnose)
1878     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1879 }
1880 
1881 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1882   S->mergeNRVOIntoParent();
1883 
1884   if (S->decl_empty()) return;
1885   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1886          "Scope shouldn't contain decls!");
1887 
1888   for (auto *TmpD : S->decls()) {
1889     assert(TmpD && "This decl didn't get pushed??");
1890 
1891     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1892     NamedDecl *D = cast<NamedDecl>(TmpD);
1893 
1894     // Diagnose unused variables in this scope.
1895     if (!S->hasUnrecoverableErrorOccurred()) {
1896       DiagnoseUnusedDecl(D);
1897       if (const auto *RD = dyn_cast<RecordDecl>(D))
1898         DiagnoseUnusedNestedTypedefs(RD);
1899     }
1900 
1901     if (!D->getDeclName()) continue;
1902 
1903     // If this was a forward reference to a label, verify it was defined.
1904     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1905       CheckPoppedLabel(LD, *this);
1906 
1907     // Remove this name from our lexical scope, and warn on it if we haven't
1908     // already.
1909     IdResolver.RemoveDecl(D);
1910     auto ShadowI = ShadowingDecls.find(D);
1911     if (ShadowI != ShadowingDecls.end()) {
1912       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1913         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1914             << D << FD << FD->getParent();
1915         Diag(FD->getLocation(), diag::note_previous_declaration);
1916       }
1917       ShadowingDecls.erase(ShadowI);
1918     }
1919   }
1920 }
1921 
1922 /// Look for an Objective-C class in the translation unit.
1923 ///
1924 /// \param Id The name of the Objective-C class we're looking for. If
1925 /// typo-correction fixes this name, the Id will be updated
1926 /// to the fixed name.
1927 ///
1928 /// \param IdLoc The location of the name in the translation unit.
1929 ///
1930 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1931 /// if there is no class with the given name.
1932 ///
1933 /// \returns The declaration of the named Objective-C class, or NULL if the
1934 /// class could not be found.
1935 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1936                                               SourceLocation IdLoc,
1937                                               bool DoTypoCorrection) {
1938   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1939   // creation from this context.
1940   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1941 
1942   if (!IDecl && DoTypoCorrection) {
1943     // Perform typo correction at the given location, but only if we
1944     // find an Objective-C class name.
1945     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1946     if (TypoCorrection C =
1947             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1948                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1949       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1950       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1951       Id = IDecl->getIdentifier();
1952     }
1953   }
1954   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1955   // This routine must always return a class definition, if any.
1956   if (Def && Def->getDefinition())
1957       Def = Def->getDefinition();
1958   return Def;
1959 }
1960 
1961 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1962 /// from S, where a non-field would be declared. This routine copes
1963 /// with the difference between C and C++ scoping rules in structs and
1964 /// unions. For example, the following code is well-formed in C but
1965 /// ill-formed in C++:
1966 /// @code
1967 /// struct S6 {
1968 ///   enum { BAR } e;
1969 /// };
1970 ///
1971 /// void test_S6() {
1972 ///   struct S6 a;
1973 ///   a.e = BAR;
1974 /// }
1975 /// @endcode
1976 /// For the declaration of BAR, this routine will return a different
1977 /// scope. The scope S will be the scope of the unnamed enumeration
1978 /// within S6. In C++, this routine will return the scope associated
1979 /// with S6, because the enumeration's scope is a transparent
1980 /// context but structures can contain non-field names. In C, this
1981 /// routine will return the translation unit scope, since the
1982 /// enumeration's scope is a transparent context and structures cannot
1983 /// contain non-field names.
1984 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1985   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1986          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1987          (S->isClassScope() && !getLangOpts().CPlusPlus))
1988     S = S->getParent();
1989   return S;
1990 }
1991 
1992 /// Looks up the declaration of "struct objc_super" and
1993 /// saves it for later use in building builtin declaration of
1994 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1995 /// pre-existing declaration exists no action takes place.
1996 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1997                                         IdentifierInfo *II) {
1998   if (!II->isStr("objc_msgSendSuper"))
1999     return;
2000   ASTContext &Context = ThisSema.Context;
2001 
2002   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2003                       SourceLocation(), Sema::LookupTagName);
2004   ThisSema.LookupName(Result, S);
2005   if (Result.getResultKind() == LookupResult::Found)
2006     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2007       Context.setObjCSuperType(Context.getTagDeclType(TD));
2008 }
2009 
2010 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2011                                ASTContext::GetBuiltinTypeError Error) {
2012   switch (Error) {
2013   case ASTContext::GE_None:
2014     return "";
2015   case ASTContext::GE_Missing_type:
2016     return BuiltinInfo.getHeaderName(ID);
2017   case ASTContext::GE_Missing_stdio:
2018     return "stdio.h";
2019   case ASTContext::GE_Missing_setjmp:
2020     return "setjmp.h";
2021   case ASTContext::GE_Missing_ucontext:
2022     return "ucontext.h";
2023   }
2024   llvm_unreachable("unhandled error kind");
2025 }
2026 
2027 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2028 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2029 /// if we're creating this built-in in anticipation of redeclaring the
2030 /// built-in.
2031 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2032                                      Scope *S, bool ForRedeclaration,
2033                                      SourceLocation Loc) {
2034   LookupPredefedObjCSuperType(*this, S, II);
2035 
2036   ASTContext::GetBuiltinTypeError Error;
2037   QualType R = Context.GetBuiltinType(ID, Error);
2038   if (Error) {
2039     if (!ForRedeclaration)
2040       return nullptr;
2041 
2042     // If we have a builtin without an associated type we should not emit a
2043     // warning when we were not able to find a type for it.
2044     if (Error == ASTContext::GE_Missing_type)
2045       return nullptr;
2046 
2047     // If we could not find a type for setjmp it is because the jmp_buf type was
2048     // not defined prior to the setjmp declaration.
2049     if (Error == ASTContext::GE_Missing_setjmp) {
2050       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2051           << Context.BuiltinInfo.getName(ID);
2052       return nullptr;
2053     }
2054 
2055     // Generally, we emit a warning that the declaration requires the
2056     // appropriate header.
2057     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2058         << getHeaderName(Context.BuiltinInfo, ID, Error)
2059         << Context.BuiltinInfo.getName(ID);
2060     return nullptr;
2061   }
2062 
2063   if (!ForRedeclaration &&
2064       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2065        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2066     Diag(Loc, diag::ext_implicit_lib_function_decl)
2067         << Context.BuiltinInfo.getName(ID) << R;
2068     if (Context.BuiltinInfo.getHeaderName(ID) &&
2069         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2070       Diag(Loc, diag::note_include_header_or_declare)
2071           << Context.BuiltinInfo.getHeaderName(ID)
2072           << Context.BuiltinInfo.getName(ID);
2073   }
2074 
2075   if (R.isNull())
2076     return nullptr;
2077 
2078   DeclContext *Parent = Context.getTranslationUnitDecl();
2079   if (getLangOpts().CPlusPlus) {
2080     LinkageSpecDecl *CLinkageDecl =
2081         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2082                                 LinkageSpecDecl::lang_c, false);
2083     CLinkageDecl->setImplicit();
2084     Parent->addDecl(CLinkageDecl);
2085     Parent = CLinkageDecl;
2086   }
2087 
2088   FunctionDecl *New = FunctionDecl::Create(Context,
2089                                            Parent,
2090                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2091                                            SC_Extern,
2092                                            false,
2093                                            R->isFunctionProtoType());
2094   New->setImplicit();
2095 
2096   // Create Decl objects for each parameter, adding them to the
2097   // FunctionDecl.
2098   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2099     SmallVector<ParmVarDecl*, 16> Params;
2100     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2101       ParmVarDecl *parm =
2102           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2103                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2104                               SC_None, nullptr);
2105       parm->setScopeInfo(0, i);
2106       Params.push_back(parm);
2107     }
2108     New->setParams(Params);
2109   }
2110 
2111   AddKnownFunctionAttributes(New);
2112   RegisterLocallyScopedExternCDecl(New, S);
2113 
2114   // TUScope is the translation-unit scope to insert this function into.
2115   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2116   // relate Scopes to DeclContexts, and probably eliminate CurContext
2117   // entirely, but we're not there yet.
2118   DeclContext *SavedContext = CurContext;
2119   CurContext = Parent;
2120   PushOnScopeChains(New, TUScope);
2121   CurContext = SavedContext;
2122   return New;
2123 }
2124 
2125 /// Typedef declarations don't have linkage, but they still denote the same
2126 /// entity if their types are the same.
2127 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2128 /// isSameEntity.
2129 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2130                                                      TypedefNameDecl *Decl,
2131                                                      LookupResult &Previous) {
2132   // This is only interesting when modules are enabled.
2133   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2134     return;
2135 
2136   // Empty sets are uninteresting.
2137   if (Previous.empty())
2138     return;
2139 
2140   LookupResult::Filter Filter = Previous.makeFilter();
2141   while (Filter.hasNext()) {
2142     NamedDecl *Old = Filter.next();
2143 
2144     // Non-hidden declarations are never ignored.
2145     if (S.isVisible(Old))
2146       continue;
2147 
2148     // Declarations of the same entity are not ignored, even if they have
2149     // different linkages.
2150     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2151       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2152                                 Decl->getUnderlyingType()))
2153         continue;
2154 
2155       // If both declarations give a tag declaration a typedef name for linkage
2156       // purposes, then they declare the same entity.
2157       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2158           Decl->getAnonDeclWithTypedefName())
2159         continue;
2160     }
2161 
2162     Filter.erase();
2163   }
2164 
2165   Filter.done();
2166 }
2167 
2168 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2169   QualType OldType;
2170   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2171     OldType = OldTypedef->getUnderlyingType();
2172   else
2173     OldType = Context.getTypeDeclType(Old);
2174   QualType NewType = New->getUnderlyingType();
2175 
2176   if (NewType->isVariablyModifiedType()) {
2177     // Must not redefine a typedef with a variably-modified type.
2178     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2179     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2180       << Kind << NewType;
2181     if (Old->getLocation().isValid())
2182       notePreviousDefinition(Old, New->getLocation());
2183     New->setInvalidDecl();
2184     return true;
2185   }
2186 
2187   if (OldType != NewType &&
2188       !OldType->isDependentType() &&
2189       !NewType->isDependentType() &&
2190       !Context.hasSameType(OldType, NewType)) {
2191     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2192     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2193       << Kind << NewType << OldType;
2194     if (Old->getLocation().isValid())
2195       notePreviousDefinition(Old, New->getLocation());
2196     New->setInvalidDecl();
2197     return true;
2198   }
2199   return false;
2200 }
2201 
2202 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2203 /// same name and scope as a previous declaration 'Old'.  Figure out
2204 /// how to resolve this situation, merging decls or emitting
2205 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2206 ///
2207 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2208                                 LookupResult &OldDecls) {
2209   // If the new decl is known invalid already, don't bother doing any
2210   // merging checks.
2211   if (New->isInvalidDecl()) return;
2212 
2213   // Allow multiple definitions for ObjC built-in typedefs.
2214   // FIXME: Verify the underlying types are equivalent!
2215   if (getLangOpts().ObjC) {
2216     const IdentifierInfo *TypeID = New->getIdentifier();
2217     switch (TypeID->getLength()) {
2218     default: break;
2219     case 2:
2220       {
2221         if (!TypeID->isStr("id"))
2222           break;
2223         QualType T = New->getUnderlyingType();
2224         if (!T->isPointerType())
2225           break;
2226         if (!T->isVoidPointerType()) {
2227           QualType PT = T->castAs<PointerType>()->getPointeeType();
2228           if (!PT->isStructureType())
2229             break;
2230         }
2231         Context.setObjCIdRedefinitionType(T);
2232         // Install the built-in type for 'id', ignoring the current definition.
2233         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2234         return;
2235       }
2236     case 5:
2237       if (!TypeID->isStr("Class"))
2238         break;
2239       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2240       // Install the built-in type for 'Class', ignoring the current definition.
2241       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2242       return;
2243     case 3:
2244       if (!TypeID->isStr("SEL"))
2245         break;
2246       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2247       // Install the built-in type for 'SEL', ignoring the current definition.
2248       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2249       return;
2250     }
2251     // Fall through - the typedef name was not a builtin type.
2252   }
2253 
2254   // Verify the old decl was also a type.
2255   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2256   if (!Old) {
2257     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2258       << New->getDeclName();
2259 
2260     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2261     if (OldD->getLocation().isValid())
2262       notePreviousDefinition(OldD, New->getLocation());
2263 
2264     return New->setInvalidDecl();
2265   }
2266 
2267   // If the old declaration is invalid, just give up here.
2268   if (Old->isInvalidDecl())
2269     return New->setInvalidDecl();
2270 
2271   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2272     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2273     auto *NewTag = New->getAnonDeclWithTypedefName();
2274     NamedDecl *Hidden = nullptr;
2275     if (OldTag && NewTag &&
2276         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2277         !hasVisibleDefinition(OldTag, &Hidden)) {
2278       // There is a definition of this tag, but it is not visible. Use it
2279       // instead of our tag.
2280       New->setTypeForDecl(OldTD->getTypeForDecl());
2281       if (OldTD->isModed())
2282         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2283                                     OldTD->getUnderlyingType());
2284       else
2285         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2286 
2287       // Make the old tag definition visible.
2288       makeMergedDefinitionVisible(Hidden);
2289 
2290       // If this was an unscoped enumeration, yank all of its enumerators
2291       // out of the scope.
2292       if (isa<EnumDecl>(NewTag)) {
2293         Scope *EnumScope = getNonFieldDeclScope(S);
2294         for (auto *D : NewTag->decls()) {
2295           auto *ED = cast<EnumConstantDecl>(D);
2296           assert(EnumScope->isDeclScope(ED));
2297           EnumScope->RemoveDecl(ED);
2298           IdResolver.RemoveDecl(ED);
2299           ED->getLexicalDeclContext()->removeDecl(ED);
2300         }
2301       }
2302     }
2303   }
2304 
2305   // If the typedef types are not identical, reject them in all languages and
2306   // with any extensions enabled.
2307   if (isIncompatibleTypedef(Old, New))
2308     return;
2309 
2310   // The types match.  Link up the redeclaration chain and merge attributes if
2311   // the old declaration was a typedef.
2312   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2313     New->setPreviousDecl(Typedef);
2314     mergeDeclAttributes(New, Old);
2315   }
2316 
2317   if (getLangOpts().MicrosoftExt)
2318     return;
2319 
2320   if (getLangOpts().CPlusPlus) {
2321     // C++ [dcl.typedef]p2:
2322     //   In a given non-class scope, a typedef specifier can be used to
2323     //   redefine the name of any type declared in that scope to refer
2324     //   to the type to which it already refers.
2325     if (!isa<CXXRecordDecl>(CurContext))
2326       return;
2327 
2328     // C++0x [dcl.typedef]p4:
2329     //   In a given class scope, a typedef specifier can be used to redefine
2330     //   any class-name declared in that scope that is not also a typedef-name
2331     //   to refer to the type to which it already refers.
2332     //
2333     // This wording came in via DR424, which was a correction to the
2334     // wording in DR56, which accidentally banned code like:
2335     //
2336     //   struct S {
2337     //     typedef struct A { } A;
2338     //   };
2339     //
2340     // in the C++03 standard. We implement the C++0x semantics, which
2341     // allow the above but disallow
2342     //
2343     //   struct S {
2344     //     typedef int I;
2345     //     typedef int I;
2346     //   };
2347     //
2348     // since that was the intent of DR56.
2349     if (!isa<TypedefNameDecl>(Old))
2350       return;
2351 
2352     Diag(New->getLocation(), diag::err_redefinition)
2353       << New->getDeclName();
2354     notePreviousDefinition(Old, New->getLocation());
2355     return New->setInvalidDecl();
2356   }
2357 
2358   // Modules always permit redefinition of typedefs, as does C11.
2359   if (getLangOpts().Modules || getLangOpts().C11)
2360     return;
2361 
2362   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2363   // is normally mapped to an error, but can be controlled with
2364   // -Wtypedef-redefinition.  If either the original or the redefinition is
2365   // in a system header, don't emit this for compatibility with GCC.
2366   if (getDiagnostics().getSuppressSystemWarnings() &&
2367       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2368       (Old->isImplicit() ||
2369        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2370        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2371     return;
2372 
2373   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2374     << New->getDeclName();
2375   notePreviousDefinition(Old, New->getLocation());
2376 }
2377 
2378 /// DeclhasAttr - returns true if decl Declaration already has the target
2379 /// attribute.
2380 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2381   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2382   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2383   for (const auto *i : D->attrs())
2384     if (i->getKind() == A->getKind()) {
2385       if (Ann) {
2386         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2387           return true;
2388         continue;
2389       }
2390       // FIXME: Don't hardcode this check
2391       if (OA && isa<OwnershipAttr>(i))
2392         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2393       return true;
2394     }
2395 
2396   return false;
2397 }
2398 
2399 static bool isAttributeTargetADefinition(Decl *D) {
2400   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2401     return VD->isThisDeclarationADefinition();
2402   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2403     return TD->isCompleteDefinition() || TD->isBeingDefined();
2404   return true;
2405 }
2406 
2407 /// Merge alignment attributes from \p Old to \p New, taking into account the
2408 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2409 ///
2410 /// \return \c true if any attributes were added to \p New.
2411 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2412   // Look for alignas attributes on Old, and pick out whichever attribute
2413   // specifies the strictest alignment requirement.
2414   AlignedAttr *OldAlignasAttr = nullptr;
2415   AlignedAttr *OldStrictestAlignAttr = nullptr;
2416   unsigned OldAlign = 0;
2417   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2418     // FIXME: We have no way of representing inherited dependent alignments
2419     // in a case like:
2420     //   template<int A, int B> struct alignas(A) X;
2421     //   template<int A, int B> struct alignas(B) X {};
2422     // For now, we just ignore any alignas attributes which are not on the
2423     // definition in such a case.
2424     if (I->isAlignmentDependent())
2425       return false;
2426 
2427     if (I->isAlignas())
2428       OldAlignasAttr = I;
2429 
2430     unsigned Align = I->getAlignment(S.Context);
2431     if (Align > OldAlign) {
2432       OldAlign = Align;
2433       OldStrictestAlignAttr = I;
2434     }
2435   }
2436 
2437   // Look for alignas attributes on New.
2438   AlignedAttr *NewAlignasAttr = nullptr;
2439   unsigned NewAlign = 0;
2440   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2441     if (I->isAlignmentDependent())
2442       return false;
2443 
2444     if (I->isAlignas())
2445       NewAlignasAttr = I;
2446 
2447     unsigned Align = I->getAlignment(S.Context);
2448     if (Align > NewAlign)
2449       NewAlign = Align;
2450   }
2451 
2452   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2453     // Both declarations have 'alignas' attributes. We require them to match.
2454     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2455     // fall short. (If two declarations both have alignas, they must both match
2456     // every definition, and so must match each other if there is a definition.)
2457 
2458     // If either declaration only contains 'alignas(0)' specifiers, then it
2459     // specifies the natural alignment for the type.
2460     if (OldAlign == 0 || NewAlign == 0) {
2461       QualType Ty;
2462       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2463         Ty = VD->getType();
2464       else
2465         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2466 
2467       if (OldAlign == 0)
2468         OldAlign = S.Context.getTypeAlign(Ty);
2469       if (NewAlign == 0)
2470         NewAlign = S.Context.getTypeAlign(Ty);
2471     }
2472 
2473     if (OldAlign != NewAlign) {
2474       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2475         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2476         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2477       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2478     }
2479   }
2480 
2481   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2482     // C++11 [dcl.align]p6:
2483     //   if any declaration of an entity has an alignment-specifier,
2484     //   every defining declaration of that entity shall specify an
2485     //   equivalent alignment.
2486     // C11 6.7.5/7:
2487     //   If the definition of an object does not have an alignment
2488     //   specifier, any other declaration of that object shall also
2489     //   have no alignment specifier.
2490     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2491       << OldAlignasAttr;
2492     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2493       << OldAlignasAttr;
2494   }
2495 
2496   bool AnyAdded = false;
2497 
2498   // Ensure we have an attribute representing the strictest alignment.
2499   if (OldAlign > NewAlign) {
2500     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2501     Clone->setInherited(true);
2502     New->addAttr(Clone);
2503     AnyAdded = true;
2504   }
2505 
2506   // Ensure we have an alignas attribute if the old declaration had one.
2507   if (OldAlignasAttr && !NewAlignasAttr &&
2508       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2509     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2510     Clone->setInherited(true);
2511     New->addAttr(Clone);
2512     AnyAdded = true;
2513   }
2514 
2515   return AnyAdded;
2516 }
2517 
2518 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2519                                const InheritableAttr *Attr,
2520                                Sema::AvailabilityMergeKind AMK) {
2521   // This function copies an attribute Attr from a previous declaration to the
2522   // new declaration D if the new declaration doesn't itself have that attribute
2523   // yet or if that attribute allows duplicates.
2524   // If you're adding a new attribute that requires logic different from
2525   // "use explicit attribute on decl if present, else use attribute from
2526   // previous decl", for example if the attribute needs to be consistent
2527   // between redeclarations, you need to call a custom merge function here.
2528   InheritableAttr *NewAttr = nullptr;
2529   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2530     NewAttr = S.mergeAvailabilityAttr(
2531         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2532         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2533         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2534         AA->getPriority());
2535   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2536     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2537   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2538     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2539   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2540     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2541   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2542     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2543   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2544     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2545                                 FA->getFirstArg());
2546   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2547     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2548   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2549     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2550   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2551     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2552                                        IA->getInheritanceModel());
2553   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2554     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2555                                       &S.Context.Idents.get(AA->getSpelling()));
2556   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2557            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2558             isa<CUDAGlobalAttr>(Attr))) {
2559     // CUDA target attributes are part of function signature for
2560     // overloading purposes and must not be merged.
2561     return false;
2562   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2563     NewAttr = S.mergeMinSizeAttr(D, *MA);
2564   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2565     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2566   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2567     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2568   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2569     NewAttr = S.mergeCommonAttr(D, *CommonA);
2570   else if (isa<AlignedAttr>(Attr))
2571     // AlignedAttrs are handled separately, because we need to handle all
2572     // such attributes on a declaration at the same time.
2573     NewAttr = nullptr;
2574   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2575            (AMK == Sema::AMK_Override ||
2576             AMK == Sema::AMK_ProtocolImplementation))
2577     NewAttr = nullptr;
2578   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2579     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2580   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2581     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2582   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2583     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2584   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2585     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2586 
2587   if (NewAttr) {
2588     NewAttr->setInherited(true);
2589     D->addAttr(NewAttr);
2590     if (isa<MSInheritanceAttr>(NewAttr))
2591       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2592     return true;
2593   }
2594 
2595   return false;
2596 }
2597 
2598 static const NamedDecl *getDefinition(const Decl *D) {
2599   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2600     return TD->getDefinition();
2601   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2602     const VarDecl *Def = VD->getDefinition();
2603     if (Def)
2604       return Def;
2605     return VD->getActingDefinition();
2606   }
2607   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2608     return FD->getDefinition();
2609   return nullptr;
2610 }
2611 
2612 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2613   for (const auto *Attribute : D->attrs())
2614     if (Attribute->getKind() == Kind)
2615       return true;
2616   return false;
2617 }
2618 
2619 /// checkNewAttributesAfterDef - If we already have a definition, check that
2620 /// there are no new attributes in this declaration.
2621 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2622   if (!New->hasAttrs())
2623     return;
2624 
2625   const NamedDecl *Def = getDefinition(Old);
2626   if (!Def || Def == New)
2627     return;
2628 
2629   AttrVec &NewAttributes = New->getAttrs();
2630   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2631     const Attr *NewAttribute = NewAttributes[I];
2632 
2633     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2634       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2635         Sema::SkipBodyInfo SkipBody;
2636         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2637 
2638         // If we're skipping this definition, drop the "alias" attribute.
2639         if (SkipBody.ShouldSkip) {
2640           NewAttributes.erase(NewAttributes.begin() + I);
2641           --E;
2642           continue;
2643         }
2644       } else {
2645         VarDecl *VD = cast<VarDecl>(New);
2646         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2647                                 VarDecl::TentativeDefinition
2648                             ? diag::err_alias_after_tentative
2649                             : diag::err_redefinition;
2650         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2651         if (Diag == diag::err_redefinition)
2652           S.notePreviousDefinition(Def, VD->getLocation());
2653         else
2654           S.Diag(Def->getLocation(), diag::note_previous_definition);
2655         VD->setInvalidDecl();
2656       }
2657       ++I;
2658       continue;
2659     }
2660 
2661     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2662       // Tentative definitions are only interesting for the alias check above.
2663       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2664         ++I;
2665         continue;
2666       }
2667     }
2668 
2669     if (hasAttribute(Def, NewAttribute->getKind())) {
2670       ++I;
2671       continue; // regular attr merging will take care of validating this.
2672     }
2673 
2674     if (isa<C11NoReturnAttr>(NewAttribute)) {
2675       // C's _Noreturn is allowed to be added to a function after it is defined.
2676       ++I;
2677       continue;
2678     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2679       if (AA->isAlignas()) {
2680         // C++11 [dcl.align]p6:
2681         //   if any declaration of an entity has an alignment-specifier,
2682         //   every defining declaration of that entity shall specify an
2683         //   equivalent alignment.
2684         // C11 6.7.5/7:
2685         //   If the definition of an object does not have an alignment
2686         //   specifier, any other declaration of that object shall also
2687         //   have no alignment specifier.
2688         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2689           << AA;
2690         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2691           << AA;
2692         NewAttributes.erase(NewAttributes.begin() + I);
2693         --E;
2694         continue;
2695       }
2696     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2697                cast<VarDecl>(New)->isInline() &&
2698                !cast<VarDecl>(New)->isInlineSpecified()) {
2699       // Don't warn about applying selectany to implicitly inline variables.
2700       // Older compilers and language modes would require the use of selectany
2701       // to make such variables inline, and it would have no effect if we
2702       // honored it.
2703       ++I;
2704       continue;
2705     }
2706 
2707     S.Diag(NewAttribute->getLocation(),
2708            diag::warn_attribute_precede_definition);
2709     S.Diag(Def->getLocation(), diag::note_previous_definition);
2710     NewAttributes.erase(NewAttributes.begin() + I);
2711     --E;
2712   }
2713 }
2714 
2715 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2716                                      const ConstInitAttr *CIAttr,
2717                                      bool AttrBeforeInit) {
2718   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2719 
2720   // Figure out a good way to write this specifier on the old declaration.
2721   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2722   // enough of the attribute list spelling information to extract that without
2723   // heroics.
2724   std::string SuitableSpelling;
2725   if (S.getLangOpts().CPlusPlus2a)
2726     SuitableSpelling =
2727         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2728   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2729     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2730         InsertLoc,
2731         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2732          tok::coloncolon,
2733          S.PP.getIdentifierInfo("require_constant_initialization"),
2734          tok::r_square, tok::r_square});
2735   if (SuitableSpelling.empty())
2736     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2737         InsertLoc,
2738         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2739          S.PP.getIdentifierInfo("require_constant_initialization"),
2740          tok::r_paren, tok::r_paren});
2741   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2742     SuitableSpelling = "constinit";
2743   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2744     SuitableSpelling = "[[clang::require_constant_initialization]]";
2745   if (SuitableSpelling.empty())
2746     SuitableSpelling = "__attribute__((require_constant_initialization))";
2747   SuitableSpelling += " ";
2748 
2749   if (AttrBeforeInit) {
2750     // extern constinit int a;
2751     // int a = 0; // error (missing 'constinit'), accepted as extension
2752     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2753     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2754         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2755     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2756   } else {
2757     // int a = 0;
2758     // constinit extern int a; // error (missing 'constinit')
2759     S.Diag(CIAttr->getLocation(),
2760            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2761                                  : diag::warn_require_const_init_added_too_late)
2762         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2763     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2764         << CIAttr->isConstinit()
2765         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2766   }
2767 }
2768 
2769 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2770 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2771                                AvailabilityMergeKind AMK) {
2772   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2773     UsedAttr *NewAttr = OldAttr->clone(Context);
2774     NewAttr->setInherited(true);
2775     New->addAttr(NewAttr);
2776   }
2777 
2778   if (!Old->hasAttrs() && !New->hasAttrs())
2779     return;
2780 
2781   // [dcl.constinit]p1:
2782   //   If the [constinit] specifier is applied to any declaration of a
2783   //   variable, it shall be applied to the initializing declaration.
2784   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2785   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2786   if (bool(OldConstInit) != bool(NewConstInit)) {
2787     const auto *OldVD = cast<VarDecl>(Old);
2788     auto *NewVD = cast<VarDecl>(New);
2789 
2790     // Find the initializing declaration. Note that we might not have linked
2791     // the new declaration into the redeclaration chain yet.
2792     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2793     if (!InitDecl &&
2794         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2795       InitDecl = NewVD;
2796 
2797     if (InitDecl == NewVD) {
2798       // This is the initializing declaration. If it would inherit 'constinit',
2799       // that's ill-formed. (Note that we do not apply this to the attribute
2800       // form).
2801       if (OldConstInit && OldConstInit->isConstinit())
2802         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2803                                  /*AttrBeforeInit=*/true);
2804     } else if (NewConstInit) {
2805       // This is the first time we've been told that this declaration should
2806       // have a constant initializer. If we already saw the initializing
2807       // declaration, this is too late.
2808       if (InitDecl && InitDecl != NewVD) {
2809         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2810                                  /*AttrBeforeInit=*/false);
2811         NewVD->dropAttr<ConstInitAttr>();
2812       }
2813     }
2814   }
2815 
2816   // Attributes declared post-definition are currently ignored.
2817   checkNewAttributesAfterDef(*this, New, Old);
2818 
2819   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2820     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2821       if (!OldA->isEquivalent(NewA)) {
2822         // This redeclaration changes __asm__ label.
2823         Diag(New->getLocation(), diag::err_different_asm_label);
2824         Diag(OldA->getLocation(), diag::note_previous_declaration);
2825       }
2826     } else if (Old->isUsed()) {
2827       // This redeclaration adds an __asm__ label to a declaration that has
2828       // already been ODR-used.
2829       Diag(New->getLocation(), diag::err_late_asm_label_name)
2830         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2831     }
2832   }
2833 
2834   // Re-declaration cannot add abi_tag's.
2835   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2836     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2837       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2838         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2839                       NewTag) == OldAbiTagAttr->tags_end()) {
2840           Diag(NewAbiTagAttr->getLocation(),
2841                diag::err_new_abi_tag_on_redeclaration)
2842               << NewTag;
2843           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2844         }
2845       }
2846     } else {
2847       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2848       Diag(Old->getLocation(), diag::note_previous_declaration);
2849     }
2850   }
2851 
2852   // This redeclaration adds a section attribute.
2853   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2854     if (auto *VD = dyn_cast<VarDecl>(New)) {
2855       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2856         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2857         Diag(Old->getLocation(), diag::note_previous_declaration);
2858       }
2859     }
2860   }
2861 
2862   // Redeclaration adds code-seg attribute.
2863   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2864   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2865       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2866     Diag(New->getLocation(), diag::warn_mismatched_section)
2867          << 0 /*codeseg*/;
2868     Diag(Old->getLocation(), diag::note_previous_declaration);
2869   }
2870 
2871   if (!Old->hasAttrs())
2872     return;
2873 
2874   bool foundAny = New->hasAttrs();
2875 
2876   // Ensure that any moving of objects within the allocated map is done before
2877   // we process them.
2878   if (!foundAny) New->setAttrs(AttrVec());
2879 
2880   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2881     // Ignore deprecated/unavailable/availability attributes if requested.
2882     AvailabilityMergeKind LocalAMK = AMK_None;
2883     if (isa<DeprecatedAttr>(I) ||
2884         isa<UnavailableAttr>(I) ||
2885         isa<AvailabilityAttr>(I)) {
2886       switch (AMK) {
2887       case AMK_None:
2888         continue;
2889 
2890       case AMK_Redeclaration:
2891       case AMK_Override:
2892       case AMK_ProtocolImplementation:
2893         LocalAMK = AMK;
2894         break;
2895       }
2896     }
2897 
2898     // Already handled.
2899     if (isa<UsedAttr>(I))
2900       continue;
2901 
2902     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2903       foundAny = true;
2904   }
2905 
2906   if (mergeAlignedAttrs(*this, New, Old))
2907     foundAny = true;
2908 
2909   if (!foundAny) New->dropAttrs();
2910 }
2911 
2912 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2913 /// to the new one.
2914 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2915                                      const ParmVarDecl *oldDecl,
2916                                      Sema &S) {
2917   // C++11 [dcl.attr.depend]p2:
2918   //   The first declaration of a function shall specify the
2919   //   carries_dependency attribute for its declarator-id if any declaration
2920   //   of the function specifies the carries_dependency attribute.
2921   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2922   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2923     S.Diag(CDA->getLocation(),
2924            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2925     // Find the first declaration of the parameter.
2926     // FIXME: Should we build redeclaration chains for function parameters?
2927     const FunctionDecl *FirstFD =
2928       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2929     const ParmVarDecl *FirstVD =
2930       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2931     S.Diag(FirstVD->getLocation(),
2932            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2933   }
2934 
2935   if (!oldDecl->hasAttrs())
2936     return;
2937 
2938   bool foundAny = newDecl->hasAttrs();
2939 
2940   // Ensure that any moving of objects within the allocated map is
2941   // done before we process them.
2942   if (!foundAny) newDecl->setAttrs(AttrVec());
2943 
2944   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2945     if (!DeclHasAttr(newDecl, I)) {
2946       InheritableAttr *newAttr =
2947         cast<InheritableParamAttr>(I->clone(S.Context));
2948       newAttr->setInherited(true);
2949       newDecl->addAttr(newAttr);
2950       foundAny = true;
2951     }
2952   }
2953 
2954   if (!foundAny) newDecl->dropAttrs();
2955 }
2956 
2957 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2958                                 const ParmVarDecl *OldParam,
2959                                 Sema &S) {
2960   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2961     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2962       if (*Oldnullability != *Newnullability) {
2963         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2964           << DiagNullabilityKind(
2965                *Newnullability,
2966                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2967                 != 0))
2968           << DiagNullabilityKind(
2969                *Oldnullability,
2970                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2971                 != 0));
2972         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2973       }
2974     } else {
2975       QualType NewT = NewParam->getType();
2976       NewT = S.Context.getAttributedType(
2977                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2978                          NewT, NewT);
2979       NewParam->setType(NewT);
2980     }
2981   }
2982 }
2983 
2984 namespace {
2985 
2986 /// Used in MergeFunctionDecl to keep track of function parameters in
2987 /// C.
2988 struct GNUCompatibleParamWarning {
2989   ParmVarDecl *OldParm;
2990   ParmVarDecl *NewParm;
2991   QualType PromotedType;
2992 };
2993 
2994 } // end anonymous namespace
2995 
2996 // Determine whether the previous declaration was a definition, implicit
2997 // declaration, or a declaration.
2998 template <typename T>
2999 static std::pair<diag::kind, SourceLocation>
3000 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3001   diag::kind PrevDiag;
3002   SourceLocation OldLocation = Old->getLocation();
3003   if (Old->isThisDeclarationADefinition())
3004     PrevDiag = diag::note_previous_definition;
3005   else if (Old->isImplicit()) {
3006     PrevDiag = diag::note_previous_implicit_declaration;
3007     if (OldLocation.isInvalid())
3008       OldLocation = New->getLocation();
3009   } else
3010     PrevDiag = diag::note_previous_declaration;
3011   return std::make_pair(PrevDiag, OldLocation);
3012 }
3013 
3014 /// canRedefineFunction - checks if a function can be redefined. Currently,
3015 /// only extern inline functions can be redefined, and even then only in
3016 /// GNU89 mode.
3017 static bool canRedefineFunction(const FunctionDecl *FD,
3018                                 const LangOptions& LangOpts) {
3019   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3020           !LangOpts.CPlusPlus &&
3021           FD->isInlineSpecified() &&
3022           FD->getStorageClass() == SC_Extern);
3023 }
3024 
3025 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3026   const AttributedType *AT = T->getAs<AttributedType>();
3027   while (AT && !AT->isCallingConv())
3028     AT = AT->getModifiedType()->getAs<AttributedType>();
3029   return AT;
3030 }
3031 
3032 template <typename T>
3033 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3034   const DeclContext *DC = Old->getDeclContext();
3035   if (DC->isRecord())
3036     return false;
3037 
3038   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3039   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3040     return true;
3041   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3042     return true;
3043   return false;
3044 }
3045 
3046 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3047 static bool isExternC(VarTemplateDecl *) { return false; }
3048 
3049 /// Check whether a redeclaration of an entity introduced by a
3050 /// using-declaration is valid, given that we know it's not an overload
3051 /// (nor a hidden tag declaration).
3052 template<typename ExpectedDecl>
3053 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3054                                    ExpectedDecl *New) {
3055   // C++11 [basic.scope.declarative]p4:
3056   //   Given a set of declarations in a single declarative region, each of
3057   //   which specifies the same unqualified name,
3058   //   -- they shall all refer to the same entity, or all refer to functions
3059   //      and function templates; or
3060   //   -- exactly one declaration shall declare a class name or enumeration
3061   //      name that is not a typedef name and the other declarations shall all
3062   //      refer to the same variable or enumerator, or all refer to functions
3063   //      and function templates; in this case the class name or enumeration
3064   //      name is hidden (3.3.10).
3065 
3066   // C++11 [namespace.udecl]p14:
3067   //   If a function declaration in namespace scope or block scope has the
3068   //   same name and the same parameter-type-list as a function introduced
3069   //   by a using-declaration, and the declarations do not declare the same
3070   //   function, the program is ill-formed.
3071 
3072   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3073   if (Old &&
3074       !Old->getDeclContext()->getRedeclContext()->Equals(
3075           New->getDeclContext()->getRedeclContext()) &&
3076       !(isExternC(Old) && isExternC(New)))
3077     Old = nullptr;
3078 
3079   if (!Old) {
3080     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3081     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3082     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3083     return true;
3084   }
3085   return false;
3086 }
3087 
3088 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3089                                             const FunctionDecl *B) {
3090   assert(A->getNumParams() == B->getNumParams());
3091 
3092   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3093     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3094     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3095     if (AttrA == AttrB)
3096       return true;
3097     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3098            AttrA->isDynamic() == AttrB->isDynamic();
3099   };
3100 
3101   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3102 }
3103 
3104 /// If necessary, adjust the semantic declaration context for a qualified
3105 /// declaration to name the correct inline namespace within the qualifier.
3106 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3107                                                DeclaratorDecl *OldD) {
3108   // The only case where we need to update the DeclContext is when
3109   // redeclaration lookup for a qualified name finds a declaration
3110   // in an inline namespace within the context named by the qualifier:
3111   //
3112   //   inline namespace N { int f(); }
3113   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3114   //
3115   // For unqualified declarations, the semantic context *can* change
3116   // along the redeclaration chain (for local extern declarations,
3117   // extern "C" declarations, and friend declarations in particular).
3118   if (!NewD->getQualifier())
3119     return;
3120 
3121   // NewD is probably already in the right context.
3122   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3123   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3124   if (NamedDC->Equals(SemaDC))
3125     return;
3126 
3127   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3128           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3129          "unexpected context for redeclaration");
3130 
3131   auto *LexDC = NewD->getLexicalDeclContext();
3132   auto FixSemaDC = [=](NamedDecl *D) {
3133     if (!D)
3134       return;
3135     D->setDeclContext(SemaDC);
3136     D->setLexicalDeclContext(LexDC);
3137   };
3138 
3139   FixSemaDC(NewD);
3140   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3141     FixSemaDC(FD->getDescribedFunctionTemplate());
3142   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3143     FixSemaDC(VD->getDescribedVarTemplate());
3144 }
3145 
3146 /// MergeFunctionDecl - We just parsed a function 'New' from
3147 /// declarator D which has the same name and scope as a previous
3148 /// declaration 'Old'.  Figure out how to resolve this situation,
3149 /// merging decls or emitting diagnostics as appropriate.
3150 ///
3151 /// In C++, New and Old must be declarations that are not
3152 /// overloaded. Use IsOverload to determine whether New and Old are
3153 /// overloaded, and to select the Old declaration that New should be
3154 /// merged with.
3155 ///
3156 /// Returns true if there was an error, false otherwise.
3157 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3158                              Scope *S, bool MergeTypeWithOld) {
3159   // Verify the old decl was also a function.
3160   FunctionDecl *Old = OldD->getAsFunction();
3161   if (!Old) {
3162     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3163       if (New->getFriendObjectKind()) {
3164         Diag(New->getLocation(), diag::err_using_decl_friend);
3165         Diag(Shadow->getTargetDecl()->getLocation(),
3166              diag::note_using_decl_target);
3167         Diag(Shadow->getUsingDecl()->getLocation(),
3168              diag::note_using_decl) << 0;
3169         return true;
3170       }
3171 
3172       // Check whether the two declarations might declare the same function.
3173       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3174         return true;
3175       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3176     } else {
3177       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3178         << New->getDeclName();
3179       notePreviousDefinition(OldD, New->getLocation());
3180       return true;
3181     }
3182   }
3183 
3184   // If the old declaration is invalid, just give up here.
3185   if (Old->isInvalidDecl())
3186     return true;
3187 
3188   // Disallow redeclaration of some builtins.
3189   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3190     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3191     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3192         << Old << Old->getType();
3193     return true;
3194   }
3195 
3196   diag::kind PrevDiag;
3197   SourceLocation OldLocation;
3198   std::tie(PrevDiag, OldLocation) =
3199       getNoteDiagForInvalidRedeclaration(Old, New);
3200 
3201   // Don't complain about this if we're in GNU89 mode and the old function
3202   // is an extern inline function.
3203   // Don't complain about specializations. They are not supposed to have
3204   // storage classes.
3205   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3206       New->getStorageClass() == SC_Static &&
3207       Old->hasExternalFormalLinkage() &&
3208       !New->getTemplateSpecializationInfo() &&
3209       !canRedefineFunction(Old, getLangOpts())) {
3210     if (getLangOpts().MicrosoftExt) {
3211       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3212       Diag(OldLocation, PrevDiag);
3213     } else {
3214       Diag(New->getLocation(), diag::err_static_non_static) << New;
3215       Diag(OldLocation, PrevDiag);
3216       return true;
3217     }
3218   }
3219 
3220   if (New->hasAttr<InternalLinkageAttr>() &&
3221       !Old->hasAttr<InternalLinkageAttr>()) {
3222     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3223         << New->getDeclName();
3224     notePreviousDefinition(Old, New->getLocation());
3225     New->dropAttr<InternalLinkageAttr>();
3226   }
3227 
3228   if (CheckRedeclarationModuleOwnership(New, Old))
3229     return true;
3230 
3231   if (!getLangOpts().CPlusPlus) {
3232     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3233     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3234       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3235         << New << OldOvl;
3236 
3237       // Try our best to find a decl that actually has the overloadable
3238       // attribute for the note. In most cases (e.g. programs with only one
3239       // broken declaration/definition), this won't matter.
3240       //
3241       // FIXME: We could do this if we juggled some extra state in
3242       // OverloadableAttr, rather than just removing it.
3243       const Decl *DiagOld = Old;
3244       if (OldOvl) {
3245         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3246           const auto *A = D->getAttr<OverloadableAttr>();
3247           return A && !A->isImplicit();
3248         });
3249         // If we've implicitly added *all* of the overloadable attrs to this
3250         // chain, emitting a "previous redecl" note is pointless.
3251         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3252       }
3253 
3254       if (DiagOld)
3255         Diag(DiagOld->getLocation(),
3256              diag::note_attribute_overloadable_prev_overload)
3257           << OldOvl;
3258 
3259       if (OldOvl)
3260         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3261       else
3262         New->dropAttr<OverloadableAttr>();
3263     }
3264   }
3265 
3266   // If a function is first declared with a calling convention, but is later
3267   // declared or defined without one, all following decls assume the calling
3268   // convention of the first.
3269   //
3270   // It's OK if a function is first declared without a calling convention,
3271   // but is later declared or defined with the default calling convention.
3272   //
3273   // To test if either decl has an explicit calling convention, we look for
3274   // AttributedType sugar nodes on the type as written.  If they are missing or
3275   // were canonicalized away, we assume the calling convention was implicit.
3276   //
3277   // Note also that we DO NOT return at this point, because we still have
3278   // other tests to run.
3279   QualType OldQType = Context.getCanonicalType(Old->getType());
3280   QualType NewQType = Context.getCanonicalType(New->getType());
3281   const FunctionType *OldType = cast<FunctionType>(OldQType);
3282   const FunctionType *NewType = cast<FunctionType>(NewQType);
3283   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3284   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3285   bool RequiresAdjustment = false;
3286 
3287   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3288     FunctionDecl *First = Old->getFirstDecl();
3289     const FunctionType *FT =
3290         First->getType().getCanonicalType()->castAs<FunctionType>();
3291     FunctionType::ExtInfo FI = FT->getExtInfo();
3292     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3293     if (!NewCCExplicit) {
3294       // Inherit the CC from the previous declaration if it was specified
3295       // there but not here.
3296       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3297       RequiresAdjustment = true;
3298     } else if (New->getBuiltinID()) {
3299       // Calling Conventions on a Builtin aren't really useful and setting a
3300       // default calling convention and cdecl'ing some builtin redeclarations is
3301       // common, so warn and ignore the calling convention on the redeclaration.
3302       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3303           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3304           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3305       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3306       RequiresAdjustment = true;
3307     } else {
3308       // Calling conventions aren't compatible, so complain.
3309       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3310       Diag(New->getLocation(), diag::err_cconv_change)
3311         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3312         << !FirstCCExplicit
3313         << (!FirstCCExplicit ? "" :
3314             FunctionType::getNameForCallConv(FI.getCC()));
3315 
3316       // Put the note on the first decl, since it is the one that matters.
3317       Diag(First->getLocation(), diag::note_previous_declaration);
3318       return true;
3319     }
3320   }
3321 
3322   // FIXME: diagnose the other way around?
3323   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3324     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3325     RequiresAdjustment = true;
3326   }
3327 
3328   // Merge regparm attribute.
3329   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3330       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3331     if (NewTypeInfo.getHasRegParm()) {
3332       Diag(New->getLocation(), diag::err_regparm_mismatch)
3333         << NewType->getRegParmType()
3334         << OldType->getRegParmType();
3335       Diag(OldLocation, diag::note_previous_declaration);
3336       return true;
3337     }
3338 
3339     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3340     RequiresAdjustment = true;
3341   }
3342 
3343   // Merge ns_returns_retained attribute.
3344   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3345     if (NewTypeInfo.getProducesResult()) {
3346       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3347           << "'ns_returns_retained'";
3348       Diag(OldLocation, diag::note_previous_declaration);
3349       return true;
3350     }
3351 
3352     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3353     RequiresAdjustment = true;
3354   }
3355 
3356   if (OldTypeInfo.getNoCallerSavedRegs() !=
3357       NewTypeInfo.getNoCallerSavedRegs()) {
3358     if (NewTypeInfo.getNoCallerSavedRegs()) {
3359       AnyX86NoCallerSavedRegistersAttr *Attr =
3360         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3361       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3362       Diag(OldLocation, diag::note_previous_declaration);
3363       return true;
3364     }
3365 
3366     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3367     RequiresAdjustment = true;
3368   }
3369 
3370   if (RequiresAdjustment) {
3371     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3372     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3373     New->setType(QualType(AdjustedType, 0));
3374     NewQType = Context.getCanonicalType(New->getType());
3375   }
3376 
3377   // If this redeclaration makes the function inline, we may need to add it to
3378   // UndefinedButUsed.
3379   if (!Old->isInlined() && New->isInlined() &&
3380       !New->hasAttr<GNUInlineAttr>() &&
3381       !getLangOpts().GNUInline &&
3382       Old->isUsed(false) &&
3383       !Old->isDefined() && !New->isThisDeclarationADefinition())
3384     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3385                                            SourceLocation()));
3386 
3387   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3388   // about it.
3389   if (New->hasAttr<GNUInlineAttr>() &&
3390       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3391     UndefinedButUsed.erase(Old->getCanonicalDecl());
3392   }
3393 
3394   // If pass_object_size params don't match up perfectly, this isn't a valid
3395   // redeclaration.
3396   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3397       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3398     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3399         << New->getDeclName();
3400     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3401     return true;
3402   }
3403 
3404   if (getLangOpts().CPlusPlus) {
3405     // C++1z [over.load]p2
3406     //   Certain function declarations cannot be overloaded:
3407     //     -- Function declarations that differ only in the return type,
3408     //        the exception specification, or both cannot be overloaded.
3409 
3410     // Check the exception specifications match. This may recompute the type of
3411     // both Old and New if it resolved exception specifications, so grab the
3412     // types again after this. Because this updates the type, we do this before
3413     // any of the other checks below, which may update the "de facto" NewQType
3414     // but do not necessarily update the type of New.
3415     if (CheckEquivalentExceptionSpec(Old, New))
3416       return true;
3417     OldQType = Context.getCanonicalType(Old->getType());
3418     NewQType = Context.getCanonicalType(New->getType());
3419 
3420     // Go back to the type source info to compare the declared return types,
3421     // per C++1y [dcl.type.auto]p13:
3422     //   Redeclarations or specializations of a function or function template
3423     //   with a declared return type that uses a placeholder type shall also
3424     //   use that placeholder, not a deduced type.
3425     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3426     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3427     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3428         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3429                                        OldDeclaredReturnType)) {
3430       QualType ResQT;
3431       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3432           OldDeclaredReturnType->isObjCObjectPointerType())
3433         // FIXME: This does the wrong thing for a deduced return type.
3434         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3435       if (ResQT.isNull()) {
3436         if (New->isCXXClassMember() && New->isOutOfLine())
3437           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3438               << New << New->getReturnTypeSourceRange();
3439         else
3440           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3441               << New->getReturnTypeSourceRange();
3442         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3443                                     << Old->getReturnTypeSourceRange();
3444         return true;
3445       }
3446       else
3447         NewQType = ResQT;
3448     }
3449 
3450     QualType OldReturnType = OldType->getReturnType();
3451     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3452     if (OldReturnType != NewReturnType) {
3453       // If this function has a deduced return type and has already been
3454       // defined, copy the deduced value from the old declaration.
3455       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3456       if (OldAT && OldAT->isDeduced()) {
3457         New->setType(
3458             SubstAutoType(New->getType(),
3459                           OldAT->isDependentType() ? Context.DependentTy
3460                                                    : OldAT->getDeducedType()));
3461         NewQType = Context.getCanonicalType(
3462             SubstAutoType(NewQType,
3463                           OldAT->isDependentType() ? Context.DependentTy
3464                                                    : OldAT->getDeducedType()));
3465       }
3466     }
3467 
3468     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3469     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3470     if (OldMethod && NewMethod) {
3471       // Preserve triviality.
3472       NewMethod->setTrivial(OldMethod->isTrivial());
3473 
3474       // MSVC allows explicit template specialization at class scope:
3475       // 2 CXXMethodDecls referring to the same function will be injected.
3476       // We don't want a redeclaration error.
3477       bool IsClassScopeExplicitSpecialization =
3478                               OldMethod->isFunctionTemplateSpecialization() &&
3479                               NewMethod->isFunctionTemplateSpecialization();
3480       bool isFriend = NewMethod->getFriendObjectKind();
3481 
3482       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3483           !IsClassScopeExplicitSpecialization) {
3484         //    -- Member function declarations with the same name and the
3485         //       same parameter types cannot be overloaded if any of them
3486         //       is a static member function declaration.
3487         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3488           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3489           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3490           return true;
3491         }
3492 
3493         // C++ [class.mem]p1:
3494         //   [...] A member shall not be declared twice in the
3495         //   member-specification, except that a nested class or member
3496         //   class template can be declared and then later defined.
3497         if (!inTemplateInstantiation()) {
3498           unsigned NewDiag;
3499           if (isa<CXXConstructorDecl>(OldMethod))
3500             NewDiag = diag::err_constructor_redeclared;
3501           else if (isa<CXXDestructorDecl>(NewMethod))
3502             NewDiag = diag::err_destructor_redeclared;
3503           else if (isa<CXXConversionDecl>(NewMethod))
3504             NewDiag = diag::err_conv_function_redeclared;
3505           else
3506             NewDiag = diag::err_member_redeclared;
3507 
3508           Diag(New->getLocation(), NewDiag);
3509         } else {
3510           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3511             << New << New->getType();
3512         }
3513         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3514         return true;
3515 
3516       // Complain if this is an explicit declaration of a special
3517       // member that was initially declared implicitly.
3518       //
3519       // As an exception, it's okay to befriend such methods in order
3520       // to permit the implicit constructor/destructor/operator calls.
3521       } else if (OldMethod->isImplicit()) {
3522         if (isFriend) {
3523           NewMethod->setImplicit();
3524         } else {
3525           Diag(NewMethod->getLocation(),
3526                diag::err_definition_of_implicitly_declared_member)
3527             << New << getSpecialMember(OldMethod);
3528           return true;
3529         }
3530       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3531         Diag(NewMethod->getLocation(),
3532              diag::err_definition_of_explicitly_defaulted_member)
3533           << getSpecialMember(OldMethod);
3534         return true;
3535       }
3536     }
3537 
3538     // C++11 [dcl.attr.noreturn]p1:
3539     //   The first declaration of a function shall specify the noreturn
3540     //   attribute if any declaration of that function specifies the noreturn
3541     //   attribute.
3542     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3543     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3544       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3545       Diag(Old->getFirstDecl()->getLocation(),
3546            diag::note_noreturn_missing_first_decl);
3547     }
3548 
3549     // C++11 [dcl.attr.depend]p2:
3550     //   The first declaration of a function shall specify the
3551     //   carries_dependency attribute for its declarator-id if any declaration
3552     //   of the function specifies the carries_dependency attribute.
3553     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3554     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3555       Diag(CDA->getLocation(),
3556            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3557       Diag(Old->getFirstDecl()->getLocation(),
3558            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3559     }
3560 
3561     // (C++98 8.3.5p3):
3562     //   All declarations for a function shall agree exactly in both the
3563     //   return type and the parameter-type-list.
3564     // We also want to respect all the extended bits except noreturn.
3565 
3566     // noreturn should now match unless the old type info didn't have it.
3567     QualType OldQTypeForComparison = OldQType;
3568     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3569       auto *OldType = OldQType->castAs<FunctionProtoType>();
3570       const FunctionType *OldTypeForComparison
3571         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3572       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3573       assert(OldQTypeForComparison.isCanonical());
3574     }
3575 
3576     if (haveIncompatibleLanguageLinkages(Old, New)) {
3577       // As a special case, retain the language linkage from previous
3578       // declarations of a friend function as an extension.
3579       //
3580       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3581       // and is useful because there's otherwise no way to specify language
3582       // linkage within class scope.
3583       //
3584       // Check cautiously as the friend object kind isn't yet complete.
3585       if (New->getFriendObjectKind() != Decl::FOK_None) {
3586         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3587         Diag(OldLocation, PrevDiag);
3588       } else {
3589         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3590         Diag(OldLocation, PrevDiag);
3591         return true;
3592       }
3593     }
3594 
3595     // If the function types are compatible, merge the declarations. Ignore the
3596     // exception specifier because it was already checked above in
3597     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3598     // about incompatible types under -fms-compatibility.
3599     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3600                                                          NewQType))
3601       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3602 
3603     // If the types are imprecise (due to dependent constructs in friends or
3604     // local extern declarations), it's OK if they differ. We'll check again
3605     // during instantiation.
3606     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3607       return false;
3608 
3609     // Fall through for conflicting redeclarations and redefinitions.
3610   }
3611 
3612   // C: Function types need to be compatible, not identical. This handles
3613   // duplicate function decls like "void f(int); void f(enum X);" properly.
3614   if (!getLangOpts().CPlusPlus &&
3615       Context.typesAreCompatible(OldQType, NewQType)) {
3616     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3617     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3618     const FunctionProtoType *OldProto = nullptr;
3619     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3620         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3621       // The old declaration provided a function prototype, but the
3622       // new declaration does not. Merge in the prototype.
3623       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3624       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3625       NewQType =
3626           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3627                                   OldProto->getExtProtoInfo());
3628       New->setType(NewQType);
3629       New->setHasInheritedPrototype();
3630 
3631       // Synthesize parameters with the same types.
3632       SmallVector<ParmVarDecl*, 16> Params;
3633       for (const auto &ParamType : OldProto->param_types()) {
3634         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3635                                                  SourceLocation(), nullptr,
3636                                                  ParamType, /*TInfo=*/nullptr,
3637                                                  SC_None, nullptr);
3638         Param->setScopeInfo(0, Params.size());
3639         Param->setImplicit();
3640         Params.push_back(Param);
3641       }
3642 
3643       New->setParams(Params);
3644     }
3645 
3646     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3647   }
3648 
3649   // GNU C permits a K&R definition to follow a prototype declaration
3650   // if the declared types of the parameters in the K&R definition
3651   // match the types in the prototype declaration, even when the
3652   // promoted types of the parameters from the K&R definition differ
3653   // from the types in the prototype. GCC then keeps the types from
3654   // the prototype.
3655   //
3656   // If a variadic prototype is followed by a non-variadic K&R definition,
3657   // the K&R definition becomes variadic.  This is sort of an edge case, but
3658   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3659   // C99 6.9.1p8.
3660   if (!getLangOpts().CPlusPlus &&
3661       Old->hasPrototype() && !New->hasPrototype() &&
3662       New->getType()->getAs<FunctionProtoType>() &&
3663       Old->getNumParams() == New->getNumParams()) {
3664     SmallVector<QualType, 16> ArgTypes;
3665     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3666     const FunctionProtoType *OldProto
3667       = Old->getType()->getAs<FunctionProtoType>();
3668     const FunctionProtoType *NewProto
3669       = New->getType()->getAs<FunctionProtoType>();
3670 
3671     // Determine whether this is the GNU C extension.
3672     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3673                                                NewProto->getReturnType());
3674     bool LooseCompatible = !MergedReturn.isNull();
3675     for (unsigned Idx = 0, End = Old->getNumParams();
3676          LooseCompatible && Idx != End; ++Idx) {
3677       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3678       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3679       if (Context.typesAreCompatible(OldParm->getType(),
3680                                      NewProto->getParamType(Idx))) {
3681         ArgTypes.push_back(NewParm->getType());
3682       } else if (Context.typesAreCompatible(OldParm->getType(),
3683                                             NewParm->getType(),
3684                                             /*CompareUnqualified=*/true)) {
3685         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3686                                            NewProto->getParamType(Idx) };
3687         Warnings.push_back(Warn);
3688         ArgTypes.push_back(NewParm->getType());
3689       } else
3690         LooseCompatible = false;
3691     }
3692 
3693     if (LooseCompatible) {
3694       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3695         Diag(Warnings[Warn].NewParm->getLocation(),
3696              diag::ext_param_promoted_not_compatible_with_prototype)
3697           << Warnings[Warn].PromotedType
3698           << Warnings[Warn].OldParm->getType();
3699         if (Warnings[Warn].OldParm->getLocation().isValid())
3700           Diag(Warnings[Warn].OldParm->getLocation(),
3701                diag::note_previous_declaration);
3702       }
3703 
3704       if (MergeTypeWithOld)
3705         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3706                                              OldProto->getExtProtoInfo()));
3707       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3708     }
3709 
3710     // Fall through to diagnose conflicting types.
3711   }
3712 
3713   // A function that has already been declared has been redeclared or
3714   // defined with a different type; show an appropriate diagnostic.
3715 
3716   // If the previous declaration was an implicitly-generated builtin
3717   // declaration, then at the very least we should use a specialized note.
3718   unsigned BuiltinID;
3719   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3720     // If it's actually a library-defined builtin function like 'malloc'
3721     // or 'printf', just warn about the incompatible redeclaration.
3722     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3723       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3724       Diag(OldLocation, diag::note_previous_builtin_declaration)
3725         << Old << Old->getType();
3726 
3727       // If this is a global redeclaration, just forget hereafter
3728       // about the "builtin-ness" of the function.
3729       //
3730       // Doing this for local extern declarations is problematic.  If
3731       // the builtin declaration remains visible, a second invalid
3732       // local declaration will produce a hard error; if it doesn't
3733       // remain visible, a single bogus local redeclaration (which is
3734       // actually only a warning) could break all the downstream code.
3735       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3736         New->getIdentifier()->revertBuiltin();
3737 
3738       return false;
3739     }
3740 
3741     PrevDiag = diag::note_previous_builtin_declaration;
3742   }
3743 
3744   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3745   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3746   return true;
3747 }
3748 
3749 /// Completes the merge of two function declarations that are
3750 /// known to be compatible.
3751 ///
3752 /// This routine handles the merging of attributes and other
3753 /// properties of function declarations from the old declaration to
3754 /// the new declaration, once we know that New is in fact a
3755 /// redeclaration of Old.
3756 ///
3757 /// \returns false
3758 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3759                                         Scope *S, bool MergeTypeWithOld) {
3760   // Merge the attributes
3761   mergeDeclAttributes(New, Old);
3762 
3763   // Merge "pure" flag.
3764   if (Old->isPure())
3765     New->setPure();
3766 
3767   // Merge "used" flag.
3768   if (Old->getMostRecentDecl()->isUsed(false))
3769     New->setIsUsed();
3770 
3771   // Merge attributes from the parameters.  These can mismatch with K&R
3772   // declarations.
3773   if (New->getNumParams() == Old->getNumParams())
3774       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3775         ParmVarDecl *NewParam = New->getParamDecl(i);
3776         ParmVarDecl *OldParam = Old->getParamDecl(i);
3777         mergeParamDeclAttributes(NewParam, OldParam, *this);
3778         mergeParamDeclTypes(NewParam, OldParam, *this);
3779       }
3780 
3781   if (getLangOpts().CPlusPlus)
3782     return MergeCXXFunctionDecl(New, Old, S);
3783 
3784   // Merge the function types so the we get the composite types for the return
3785   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3786   // was visible.
3787   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3788   if (!Merged.isNull() && MergeTypeWithOld)
3789     New->setType(Merged);
3790 
3791   return false;
3792 }
3793 
3794 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3795                                 ObjCMethodDecl *oldMethod) {
3796   // Merge the attributes, including deprecated/unavailable
3797   AvailabilityMergeKind MergeKind =
3798     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3799       ? AMK_ProtocolImplementation
3800       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3801                                                        : AMK_Override;
3802 
3803   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3804 
3805   // Merge attributes from the parameters.
3806   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3807                                        oe = oldMethod->param_end();
3808   for (ObjCMethodDecl::param_iterator
3809          ni = newMethod->param_begin(), ne = newMethod->param_end();
3810        ni != ne && oi != oe; ++ni, ++oi)
3811     mergeParamDeclAttributes(*ni, *oi, *this);
3812 
3813   CheckObjCMethodOverride(newMethod, oldMethod);
3814 }
3815 
3816 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3817   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3818 
3819   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3820          ? diag::err_redefinition_different_type
3821          : diag::err_redeclaration_different_type)
3822     << New->getDeclName() << New->getType() << Old->getType();
3823 
3824   diag::kind PrevDiag;
3825   SourceLocation OldLocation;
3826   std::tie(PrevDiag, OldLocation)
3827     = getNoteDiagForInvalidRedeclaration(Old, New);
3828   S.Diag(OldLocation, PrevDiag);
3829   New->setInvalidDecl();
3830 }
3831 
3832 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3833 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3834 /// emitting diagnostics as appropriate.
3835 ///
3836 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3837 /// to here in AddInitializerToDecl. We can't check them before the initializer
3838 /// is attached.
3839 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3840                              bool MergeTypeWithOld) {
3841   if (New->isInvalidDecl() || Old->isInvalidDecl())
3842     return;
3843 
3844   QualType MergedT;
3845   if (getLangOpts().CPlusPlus) {
3846     if (New->getType()->isUndeducedType()) {
3847       // We don't know what the new type is until the initializer is attached.
3848       return;
3849     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3850       // These could still be something that needs exception specs checked.
3851       return MergeVarDeclExceptionSpecs(New, Old);
3852     }
3853     // C++ [basic.link]p10:
3854     //   [...] the types specified by all declarations referring to a given
3855     //   object or function shall be identical, except that declarations for an
3856     //   array object can specify array types that differ by the presence or
3857     //   absence of a major array bound (8.3.4).
3858     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3859       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3860       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3861 
3862       // We are merging a variable declaration New into Old. If it has an array
3863       // bound, and that bound differs from Old's bound, we should diagnose the
3864       // mismatch.
3865       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3866         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3867              PrevVD = PrevVD->getPreviousDecl()) {
3868           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3869           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3870             continue;
3871 
3872           if (!Context.hasSameType(NewArray, PrevVDTy))
3873             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3874         }
3875       }
3876 
3877       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3878         if (Context.hasSameType(OldArray->getElementType(),
3879                                 NewArray->getElementType()))
3880           MergedT = New->getType();
3881       }
3882       // FIXME: Check visibility. New is hidden but has a complete type. If New
3883       // has no array bound, it should not inherit one from Old, if Old is not
3884       // visible.
3885       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3886         if (Context.hasSameType(OldArray->getElementType(),
3887                                 NewArray->getElementType()))
3888           MergedT = Old->getType();
3889       }
3890     }
3891     else if (New->getType()->isObjCObjectPointerType() &&
3892                Old->getType()->isObjCObjectPointerType()) {
3893       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3894                                               Old->getType());
3895     }
3896   } else {
3897     // C 6.2.7p2:
3898     //   All declarations that refer to the same object or function shall have
3899     //   compatible type.
3900     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3901   }
3902   if (MergedT.isNull()) {
3903     // It's OK if we couldn't merge types if either type is dependent, for a
3904     // block-scope variable. In other cases (static data members of class
3905     // templates, variable templates, ...), we require the types to be
3906     // equivalent.
3907     // FIXME: The C++ standard doesn't say anything about this.
3908     if ((New->getType()->isDependentType() ||
3909          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3910       // If the old type was dependent, we can't merge with it, so the new type
3911       // becomes dependent for now. We'll reproduce the original type when we
3912       // instantiate the TypeSourceInfo for the variable.
3913       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3914         New->setType(Context.DependentTy);
3915       return;
3916     }
3917     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3918   }
3919 
3920   // Don't actually update the type on the new declaration if the old
3921   // declaration was an extern declaration in a different scope.
3922   if (MergeTypeWithOld)
3923     New->setType(MergedT);
3924 }
3925 
3926 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3927                                   LookupResult &Previous) {
3928   // C11 6.2.7p4:
3929   //   For an identifier with internal or external linkage declared
3930   //   in a scope in which a prior declaration of that identifier is
3931   //   visible, if the prior declaration specifies internal or
3932   //   external linkage, the type of the identifier at the later
3933   //   declaration becomes the composite type.
3934   //
3935   // If the variable isn't visible, we do not merge with its type.
3936   if (Previous.isShadowed())
3937     return false;
3938 
3939   if (S.getLangOpts().CPlusPlus) {
3940     // C++11 [dcl.array]p3:
3941     //   If there is a preceding declaration of the entity in the same
3942     //   scope in which the bound was specified, an omitted array bound
3943     //   is taken to be the same as in that earlier declaration.
3944     return NewVD->isPreviousDeclInSameBlockScope() ||
3945            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3946             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3947   } else {
3948     // If the old declaration was function-local, don't merge with its
3949     // type unless we're in the same function.
3950     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3951            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3952   }
3953 }
3954 
3955 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3956 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3957 /// situation, merging decls or emitting diagnostics as appropriate.
3958 ///
3959 /// Tentative definition rules (C99 6.9.2p2) are checked by
3960 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3961 /// definitions here, since the initializer hasn't been attached.
3962 ///
3963 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3964   // If the new decl is already invalid, don't do any other checking.
3965   if (New->isInvalidDecl())
3966     return;
3967 
3968   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3969     return;
3970 
3971   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3972 
3973   // Verify the old decl was also a variable or variable template.
3974   VarDecl *Old = nullptr;
3975   VarTemplateDecl *OldTemplate = nullptr;
3976   if (Previous.isSingleResult()) {
3977     if (NewTemplate) {
3978       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3979       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3980 
3981       if (auto *Shadow =
3982               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3983         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3984           return New->setInvalidDecl();
3985     } else {
3986       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3987 
3988       if (auto *Shadow =
3989               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3990         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3991           return New->setInvalidDecl();
3992     }
3993   }
3994   if (!Old) {
3995     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3996         << New->getDeclName();
3997     notePreviousDefinition(Previous.getRepresentativeDecl(),
3998                            New->getLocation());
3999     return New->setInvalidDecl();
4000   }
4001 
4002   // Ensure the template parameters are compatible.
4003   if (NewTemplate &&
4004       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4005                                       OldTemplate->getTemplateParameters(),
4006                                       /*Complain=*/true, TPL_TemplateMatch))
4007     return New->setInvalidDecl();
4008 
4009   // C++ [class.mem]p1:
4010   //   A member shall not be declared twice in the member-specification [...]
4011   //
4012   // Here, we need only consider static data members.
4013   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4014     Diag(New->getLocation(), diag::err_duplicate_member)
4015       << New->getIdentifier();
4016     Diag(Old->getLocation(), diag::note_previous_declaration);
4017     New->setInvalidDecl();
4018   }
4019 
4020   mergeDeclAttributes(New, Old);
4021   // Warn if an already-declared variable is made a weak_import in a subsequent
4022   // declaration
4023   if (New->hasAttr<WeakImportAttr>() &&
4024       Old->getStorageClass() == SC_None &&
4025       !Old->hasAttr<WeakImportAttr>()) {
4026     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4027     notePreviousDefinition(Old, New->getLocation());
4028     // Remove weak_import attribute on new declaration.
4029     New->dropAttr<WeakImportAttr>();
4030   }
4031 
4032   if (New->hasAttr<InternalLinkageAttr>() &&
4033       !Old->hasAttr<InternalLinkageAttr>()) {
4034     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4035         << New->getDeclName();
4036     notePreviousDefinition(Old, New->getLocation());
4037     New->dropAttr<InternalLinkageAttr>();
4038   }
4039 
4040   // Merge the types.
4041   VarDecl *MostRecent = Old->getMostRecentDecl();
4042   if (MostRecent != Old) {
4043     MergeVarDeclTypes(New, MostRecent,
4044                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4045     if (New->isInvalidDecl())
4046       return;
4047   }
4048 
4049   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4050   if (New->isInvalidDecl())
4051     return;
4052 
4053   diag::kind PrevDiag;
4054   SourceLocation OldLocation;
4055   std::tie(PrevDiag, OldLocation) =
4056       getNoteDiagForInvalidRedeclaration(Old, New);
4057 
4058   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4059   if (New->getStorageClass() == SC_Static &&
4060       !New->isStaticDataMember() &&
4061       Old->hasExternalFormalLinkage()) {
4062     if (getLangOpts().MicrosoftExt) {
4063       Diag(New->getLocation(), diag::ext_static_non_static)
4064           << New->getDeclName();
4065       Diag(OldLocation, PrevDiag);
4066     } else {
4067       Diag(New->getLocation(), diag::err_static_non_static)
4068           << New->getDeclName();
4069       Diag(OldLocation, PrevDiag);
4070       return New->setInvalidDecl();
4071     }
4072   }
4073   // C99 6.2.2p4:
4074   //   For an identifier declared with the storage-class specifier
4075   //   extern in a scope in which a prior declaration of that
4076   //   identifier is visible,23) if the prior declaration specifies
4077   //   internal or external linkage, the linkage of the identifier at
4078   //   the later declaration is the same as the linkage specified at
4079   //   the prior declaration. If no prior declaration is visible, or
4080   //   if the prior declaration specifies no linkage, then the
4081   //   identifier has external linkage.
4082   if (New->hasExternalStorage() && Old->hasLinkage())
4083     /* Okay */;
4084   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4085            !New->isStaticDataMember() &&
4086            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4087     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4088     Diag(OldLocation, PrevDiag);
4089     return New->setInvalidDecl();
4090   }
4091 
4092   // Check if extern is followed by non-extern and vice-versa.
4093   if (New->hasExternalStorage() &&
4094       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4095     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4096     Diag(OldLocation, PrevDiag);
4097     return New->setInvalidDecl();
4098   }
4099   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4100       !New->hasExternalStorage()) {
4101     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4102     Diag(OldLocation, PrevDiag);
4103     return New->setInvalidDecl();
4104   }
4105 
4106   if (CheckRedeclarationModuleOwnership(New, Old))
4107     return;
4108 
4109   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4110 
4111   // FIXME: The test for external storage here seems wrong? We still
4112   // need to check for mismatches.
4113   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4114       // Don't complain about out-of-line definitions of static members.
4115       !(Old->getLexicalDeclContext()->isRecord() &&
4116         !New->getLexicalDeclContext()->isRecord())) {
4117     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4118     Diag(OldLocation, PrevDiag);
4119     return New->setInvalidDecl();
4120   }
4121 
4122   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4123     if (VarDecl *Def = Old->getDefinition()) {
4124       // C++1z [dcl.fcn.spec]p4:
4125       //   If the definition of a variable appears in a translation unit before
4126       //   its first declaration as inline, the program is ill-formed.
4127       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4128       Diag(Def->getLocation(), diag::note_previous_definition);
4129     }
4130   }
4131 
4132   // If this redeclaration makes the variable inline, we may need to add it to
4133   // UndefinedButUsed.
4134   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4135       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4136     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4137                                            SourceLocation()));
4138 
4139   if (New->getTLSKind() != Old->getTLSKind()) {
4140     if (!Old->getTLSKind()) {
4141       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4142       Diag(OldLocation, PrevDiag);
4143     } else if (!New->getTLSKind()) {
4144       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4145       Diag(OldLocation, PrevDiag);
4146     } else {
4147       // Do not allow redeclaration to change the variable between requiring
4148       // static and dynamic initialization.
4149       // FIXME: GCC allows this, but uses the TLS keyword on the first
4150       // declaration to determine the kind. Do we need to be compatible here?
4151       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4152         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4153       Diag(OldLocation, PrevDiag);
4154     }
4155   }
4156 
4157   // C++ doesn't have tentative definitions, so go right ahead and check here.
4158   if (getLangOpts().CPlusPlus &&
4159       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4160     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4161         Old->getCanonicalDecl()->isConstexpr()) {
4162       // This definition won't be a definition any more once it's been merged.
4163       Diag(New->getLocation(),
4164            diag::warn_deprecated_redundant_constexpr_static_def);
4165     } else if (VarDecl *Def = Old->getDefinition()) {
4166       if (checkVarDeclRedefinition(Def, New))
4167         return;
4168     }
4169   }
4170 
4171   if (haveIncompatibleLanguageLinkages(Old, New)) {
4172     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4173     Diag(OldLocation, PrevDiag);
4174     New->setInvalidDecl();
4175     return;
4176   }
4177 
4178   // Merge "used" flag.
4179   if (Old->getMostRecentDecl()->isUsed(false))
4180     New->setIsUsed();
4181 
4182   // Keep a chain of previous declarations.
4183   New->setPreviousDecl(Old);
4184   if (NewTemplate)
4185     NewTemplate->setPreviousDecl(OldTemplate);
4186   adjustDeclContextForDeclaratorDecl(New, Old);
4187 
4188   // Inherit access appropriately.
4189   New->setAccess(Old->getAccess());
4190   if (NewTemplate)
4191     NewTemplate->setAccess(New->getAccess());
4192 
4193   if (Old->isInline())
4194     New->setImplicitlyInline();
4195 }
4196 
4197 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4198   SourceManager &SrcMgr = getSourceManager();
4199   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4200   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4201   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4202   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4203   auto &HSI = PP.getHeaderSearchInfo();
4204   StringRef HdrFilename =
4205       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4206 
4207   auto noteFromModuleOrInclude = [&](Module *Mod,
4208                                      SourceLocation IncLoc) -> bool {
4209     // Redefinition errors with modules are common with non modular mapped
4210     // headers, example: a non-modular header H in module A that also gets
4211     // included directly in a TU. Pointing twice to the same header/definition
4212     // is confusing, try to get better diagnostics when modules is on.
4213     if (IncLoc.isValid()) {
4214       if (Mod) {
4215         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4216             << HdrFilename.str() << Mod->getFullModuleName();
4217         if (!Mod->DefinitionLoc.isInvalid())
4218           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4219               << Mod->getFullModuleName();
4220       } else {
4221         Diag(IncLoc, diag::note_redefinition_include_same_file)
4222             << HdrFilename.str();
4223       }
4224       return true;
4225     }
4226 
4227     return false;
4228   };
4229 
4230   // Is it the same file and same offset? Provide more information on why
4231   // this leads to a redefinition error.
4232   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4233     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4234     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4235     bool EmittedDiag =
4236         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4237     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4238 
4239     // If the header has no guards, emit a note suggesting one.
4240     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4241       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4242 
4243     if (EmittedDiag)
4244       return;
4245   }
4246 
4247   // Redefinition coming from different files or couldn't do better above.
4248   if (Old->getLocation().isValid())
4249     Diag(Old->getLocation(), diag::note_previous_definition);
4250 }
4251 
4252 /// We've just determined that \p Old and \p New both appear to be definitions
4253 /// of the same variable. Either diagnose or fix the problem.
4254 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4255   if (!hasVisibleDefinition(Old) &&
4256       (New->getFormalLinkage() == InternalLinkage ||
4257        New->isInline() ||
4258        New->getDescribedVarTemplate() ||
4259        New->getNumTemplateParameterLists() ||
4260        New->getDeclContext()->isDependentContext())) {
4261     // The previous definition is hidden, and multiple definitions are
4262     // permitted (in separate TUs). Demote this to a declaration.
4263     New->demoteThisDefinitionToDeclaration();
4264 
4265     // Make the canonical definition visible.
4266     if (auto *OldTD = Old->getDescribedVarTemplate())
4267       makeMergedDefinitionVisible(OldTD);
4268     makeMergedDefinitionVisible(Old);
4269     return false;
4270   } else {
4271     Diag(New->getLocation(), diag::err_redefinition) << New;
4272     notePreviousDefinition(Old, New->getLocation());
4273     New->setInvalidDecl();
4274     return true;
4275   }
4276 }
4277 
4278 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4279 /// no declarator (e.g. "struct foo;") is parsed.
4280 Decl *
4281 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4282                                  RecordDecl *&AnonRecord) {
4283   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4284                                     AnonRecord);
4285 }
4286 
4287 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4288 // disambiguate entities defined in different scopes.
4289 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4290 // compatibility.
4291 // We will pick our mangling number depending on which version of MSVC is being
4292 // targeted.
4293 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4294   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4295              ? S->getMSCurManglingNumber()
4296              : S->getMSLastManglingNumber();
4297 }
4298 
4299 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4300   if (!Context.getLangOpts().CPlusPlus)
4301     return;
4302 
4303   if (isa<CXXRecordDecl>(Tag->getParent())) {
4304     // If this tag is the direct child of a class, number it if
4305     // it is anonymous.
4306     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4307       return;
4308     MangleNumberingContext &MCtx =
4309         Context.getManglingNumberContext(Tag->getParent());
4310     Context.setManglingNumber(
4311         Tag, MCtx.getManglingNumber(
4312                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4313     return;
4314   }
4315 
4316   // If this tag isn't a direct child of a class, number it if it is local.
4317   MangleNumberingContext *MCtx;
4318   Decl *ManglingContextDecl;
4319   std::tie(MCtx, ManglingContextDecl) =
4320       getCurrentMangleNumberContext(Tag->getDeclContext());
4321   if (MCtx) {
4322     Context.setManglingNumber(
4323         Tag, MCtx->getManglingNumber(
4324                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4325   }
4326 }
4327 
4328 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4329                                         TypedefNameDecl *NewTD) {
4330   if (TagFromDeclSpec->isInvalidDecl())
4331     return;
4332 
4333   // Do nothing if the tag already has a name for linkage purposes.
4334   if (TagFromDeclSpec->hasNameForLinkage())
4335     return;
4336 
4337   // A well-formed anonymous tag must always be a TUK_Definition.
4338   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4339 
4340   // The type must match the tag exactly;  no qualifiers allowed.
4341   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4342                            Context.getTagDeclType(TagFromDeclSpec))) {
4343     if (getLangOpts().CPlusPlus)
4344       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4345     return;
4346   }
4347 
4348   // If we've already computed linkage for the anonymous tag, then
4349   // adding a typedef name for the anonymous decl can change that
4350   // linkage, which might be a serious problem.  Diagnose this as
4351   // unsupported and ignore the typedef name.  TODO: we should
4352   // pursue this as a language defect and establish a formal rule
4353   // for how to handle it.
4354   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4355     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4356 
4357     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4358     tagLoc = getLocForEndOfToken(tagLoc);
4359 
4360     llvm::SmallString<40> textToInsert;
4361     textToInsert += ' ';
4362     textToInsert += NewTD->getIdentifier()->getName();
4363     Diag(tagLoc, diag::note_typedef_changes_linkage)
4364         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4365     return;
4366   }
4367 
4368   // Otherwise, set this is the anon-decl typedef for the tag.
4369   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4370 }
4371 
4372 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4373   switch (T) {
4374   case DeclSpec::TST_class:
4375     return 0;
4376   case DeclSpec::TST_struct:
4377     return 1;
4378   case DeclSpec::TST_interface:
4379     return 2;
4380   case DeclSpec::TST_union:
4381     return 3;
4382   case DeclSpec::TST_enum:
4383     return 4;
4384   default:
4385     llvm_unreachable("unexpected type specifier");
4386   }
4387 }
4388 
4389 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4390 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4391 /// parameters to cope with template friend declarations.
4392 Decl *
4393 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4394                                  MultiTemplateParamsArg TemplateParams,
4395                                  bool IsExplicitInstantiation,
4396                                  RecordDecl *&AnonRecord) {
4397   Decl *TagD = nullptr;
4398   TagDecl *Tag = nullptr;
4399   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4400       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4401       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4402       DS.getTypeSpecType() == DeclSpec::TST_union ||
4403       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4404     TagD = DS.getRepAsDecl();
4405 
4406     if (!TagD) // We probably had an error
4407       return nullptr;
4408 
4409     // Note that the above type specs guarantee that the
4410     // type rep is a Decl, whereas in many of the others
4411     // it's a Type.
4412     if (isa<TagDecl>(TagD))
4413       Tag = cast<TagDecl>(TagD);
4414     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4415       Tag = CTD->getTemplatedDecl();
4416   }
4417 
4418   if (Tag) {
4419     handleTagNumbering(Tag, S);
4420     Tag->setFreeStanding();
4421     if (Tag->isInvalidDecl())
4422       return Tag;
4423   }
4424 
4425   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4426     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4427     // or incomplete types shall not be restrict-qualified."
4428     if (TypeQuals & DeclSpec::TQ_restrict)
4429       Diag(DS.getRestrictSpecLoc(),
4430            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4431            << DS.getSourceRange();
4432   }
4433 
4434   if (DS.isInlineSpecified())
4435     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4436         << getLangOpts().CPlusPlus17;
4437 
4438   if (DS.hasConstexprSpecifier()) {
4439     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4440     // and definitions of functions and variables.
4441     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4442     // the declaration of a function or function template
4443     if (Tag)
4444       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4445           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4446           << DS.getConstexprSpecifier();
4447     else
4448       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4449           << DS.getConstexprSpecifier();
4450     // Don't emit warnings after this error.
4451     return TagD;
4452   }
4453 
4454   DiagnoseFunctionSpecifiers(DS);
4455 
4456   if (DS.isFriendSpecified()) {
4457     // If we're dealing with a decl but not a TagDecl, assume that
4458     // whatever routines created it handled the friendship aspect.
4459     if (TagD && !Tag)
4460       return nullptr;
4461     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4462   }
4463 
4464   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4465   bool IsExplicitSpecialization =
4466     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4467   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4468       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4469       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4470     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4471     // nested-name-specifier unless it is an explicit instantiation
4472     // or an explicit specialization.
4473     //
4474     // FIXME: We allow class template partial specializations here too, per the
4475     // obvious intent of DR1819.
4476     //
4477     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4478     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4479         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4480     return nullptr;
4481   }
4482 
4483   // Track whether this decl-specifier declares anything.
4484   bool DeclaresAnything = true;
4485 
4486   // Handle anonymous struct definitions.
4487   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4488     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4489         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4490       if (getLangOpts().CPlusPlus ||
4491           Record->getDeclContext()->isRecord()) {
4492         // If CurContext is a DeclContext that can contain statements,
4493         // RecursiveASTVisitor won't visit the decls that
4494         // BuildAnonymousStructOrUnion() will put into CurContext.
4495         // Also store them here so that they can be part of the
4496         // DeclStmt that gets created in this case.
4497         // FIXME: Also return the IndirectFieldDecls created by
4498         // BuildAnonymousStructOr union, for the same reason?
4499         if (CurContext->isFunctionOrMethod())
4500           AnonRecord = Record;
4501         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4502                                            Context.getPrintingPolicy());
4503       }
4504 
4505       DeclaresAnything = false;
4506     }
4507   }
4508 
4509   // C11 6.7.2.1p2:
4510   //   A struct-declaration that does not declare an anonymous structure or
4511   //   anonymous union shall contain a struct-declarator-list.
4512   //
4513   // This rule also existed in C89 and C99; the grammar for struct-declaration
4514   // did not permit a struct-declaration without a struct-declarator-list.
4515   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4516       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4517     // Check for Microsoft C extension: anonymous struct/union member.
4518     // Handle 2 kinds of anonymous struct/union:
4519     //   struct STRUCT;
4520     //   union UNION;
4521     // and
4522     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4523     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4524     if ((Tag && Tag->getDeclName()) ||
4525         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4526       RecordDecl *Record = nullptr;
4527       if (Tag)
4528         Record = dyn_cast<RecordDecl>(Tag);
4529       else if (const RecordType *RT =
4530                    DS.getRepAsType().get()->getAsStructureType())
4531         Record = RT->getDecl();
4532       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4533         Record = UT->getDecl();
4534 
4535       if (Record && getLangOpts().MicrosoftExt) {
4536         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4537             << Record->isUnion() << DS.getSourceRange();
4538         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4539       }
4540 
4541       DeclaresAnything = false;
4542     }
4543   }
4544 
4545   // Skip all the checks below if we have a type error.
4546   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4547       (TagD && TagD->isInvalidDecl()))
4548     return TagD;
4549 
4550   if (getLangOpts().CPlusPlus &&
4551       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4552     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4553       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4554           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4555         DeclaresAnything = false;
4556 
4557   if (!DS.isMissingDeclaratorOk()) {
4558     // Customize diagnostic for a typedef missing a name.
4559     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4560       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4561           << DS.getSourceRange();
4562     else
4563       DeclaresAnything = false;
4564   }
4565 
4566   if (DS.isModulePrivateSpecified() &&
4567       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4568     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4569       << Tag->getTagKind()
4570       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4571 
4572   ActOnDocumentableDecl(TagD);
4573 
4574   // C 6.7/2:
4575   //   A declaration [...] shall declare at least a declarator [...], a tag,
4576   //   or the members of an enumeration.
4577   // C++ [dcl.dcl]p3:
4578   //   [If there are no declarators], and except for the declaration of an
4579   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4580   //   names into the program, or shall redeclare a name introduced by a
4581   //   previous declaration.
4582   if (!DeclaresAnything) {
4583     // In C, we allow this as a (popular) extension / bug. Don't bother
4584     // producing further diagnostics for redundant qualifiers after this.
4585     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4586     return TagD;
4587   }
4588 
4589   // C++ [dcl.stc]p1:
4590   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4591   //   init-declarator-list of the declaration shall not be empty.
4592   // C++ [dcl.fct.spec]p1:
4593   //   If a cv-qualifier appears in a decl-specifier-seq, the
4594   //   init-declarator-list of the declaration shall not be empty.
4595   //
4596   // Spurious qualifiers here appear to be valid in C.
4597   unsigned DiagID = diag::warn_standalone_specifier;
4598   if (getLangOpts().CPlusPlus)
4599     DiagID = diag::ext_standalone_specifier;
4600 
4601   // Note that a linkage-specification sets a storage class, but
4602   // 'extern "C" struct foo;' is actually valid and not theoretically
4603   // useless.
4604   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4605     if (SCS == DeclSpec::SCS_mutable)
4606       // Since mutable is not a viable storage class specifier in C, there is
4607       // no reason to treat it as an extension. Instead, diagnose as an error.
4608       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4609     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4610       Diag(DS.getStorageClassSpecLoc(), DiagID)
4611         << DeclSpec::getSpecifierName(SCS);
4612   }
4613 
4614   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4615     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4616       << DeclSpec::getSpecifierName(TSCS);
4617   if (DS.getTypeQualifiers()) {
4618     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4619       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4620     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4621       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4622     // Restrict is covered above.
4623     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4624       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4625     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4626       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4627   }
4628 
4629   // Warn about ignored type attributes, for example:
4630   // __attribute__((aligned)) struct A;
4631   // Attributes should be placed after tag to apply to type declaration.
4632   if (!DS.getAttributes().empty()) {
4633     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4634     if (TypeSpecType == DeclSpec::TST_class ||
4635         TypeSpecType == DeclSpec::TST_struct ||
4636         TypeSpecType == DeclSpec::TST_interface ||
4637         TypeSpecType == DeclSpec::TST_union ||
4638         TypeSpecType == DeclSpec::TST_enum) {
4639       for (const ParsedAttr &AL : DS.getAttributes())
4640         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4641             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4642     }
4643   }
4644 
4645   return TagD;
4646 }
4647 
4648 /// We are trying to inject an anonymous member into the given scope;
4649 /// check if there's an existing declaration that can't be overloaded.
4650 ///
4651 /// \return true if this is a forbidden redeclaration
4652 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4653                                          Scope *S,
4654                                          DeclContext *Owner,
4655                                          DeclarationName Name,
4656                                          SourceLocation NameLoc,
4657                                          bool IsUnion) {
4658   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4659                  Sema::ForVisibleRedeclaration);
4660   if (!SemaRef.LookupName(R, S)) return false;
4661 
4662   // Pick a representative declaration.
4663   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4664   assert(PrevDecl && "Expected a non-null Decl");
4665 
4666   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4667     return false;
4668 
4669   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4670     << IsUnion << Name;
4671   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4672 
4673   return true;
4674 }
4675 
4676 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4677 /// anonymous struct or union AnonRecord into the owning context Owner
4678 /// and scope S. This routine will be invoked just after we realize
4679 /// that an unnamed union or struct is actually an anonymous union or
4680 /// struct, e.g.,
4681 ///
4682 /// @code
4683 /// union {
4684 ///   int i;
4685 ///   float f;
4686 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4687 ///    // f into the surrounding scope.x
4688 /// @endcode
4689 ///
4690 /// This routine is recursive, injecting the names of nested anonymous
4691 /// structs/unions into the owning context and scope as well.
4692 static bool
4693 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4694                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4695                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4696   bool Invalid = false;
4697 
4698   // Look every FieldDecl and IndirectFieldDecl with a name.
4699   for (auto *D : AnonRecord->decls()) {
4700     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4701         cast<NamedDecl>(D)->getDeclName()) {
4702       ValueDecl *VD = cast<ValueDecl>(D);
4703       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4704                                        VD->getLocation(),
4705                                        AnonRecord->isUnion())) {
4706         // C++ [class.union]p2:
4707         //   The names of the members of an anonymous union shall be
4708         //   distinct from the names of any other entity in the
4709         //   scope in which the anonymous union is declared.
4710         Invalid = true;
4711       } else {
4712         // C++ [class.union]p2:
4713         //   For the purpose of name lookup, after the anonymous union
4714         //   definition, the members of the anonymous union are
4715         //   considered to have been defined in the scope in which the
4716         //   anonymous union is declared.
4717         unsigned OldChainingSize = Chaining.size();
4718         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4719           Chaining.append(IF->chain_begin(), IF->chain_end());
4720         else
4721           Chaining.push_back(VD);
4722 
4723         assert(Chaining.size() >= 2);
4724         NamedDecl **NamedChain =
4725           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4726         for (unsigned i = 0; i < Chaining.size(); i++)
4727           NamedChain[i] = Chaining[i];
4728 
4729         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4730             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4731             VD->getType(), {NamedChain, Chaining.size()});
4732 
4733         for (const auto *Attr : VD->attrs())
4734           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4735 
4736         IndirectField->setAccess(AS);
4737         IndirectField->setImplicit();
4738         SemaRef.PushOnScopeChains(IndirectField, S);
4739 
4740         // That includes picking up the appropriate access specifier.
4741         if (AS != AS_none) IndirectField->setAccess(AS);
4742 
4743         Chaining.resize(OldChainingSize);
4744       }
4745     }
4746   }
4747 
4748   return Invalid;
4749 }
4750 
4751 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4752 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4753 /// illegal input values are mapped to SC_None.
4754 static StorageClass
4755 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4756   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4757   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4758          "Parser allowed 'typedef' as storage class VarDecl.");
4759   switch (StorageClassSpec) {
4760   case DeclSpec::SCS_unspecified:    return SC_None;
4761   case DeclSpec::SCS_extern:
4762     if (DS.isExternInLinkageSpec())
4763       return SC_None;
4764     return SC_Extern;
4765   case DeclSpec::SCS_static:         return SC_Static;
4766   case DeclSpec::SCS_auto:           return SC_Auto;
4767   case DeclSpec::SCS_register:       return SC_Register;
4768   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4769     // Illegal SCSs map to None: error reporting is up to the caller.
4770   case DeclSpec::SCS_mutable:        // Fall through.
4771   case DeclSpec::SCS_typedef:        return SC_None;
4772   }
4773   llvm_unreachable("unknown storage class specifier");
4774 }
4775 
4776 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4777   assert(Record->hasInClassInitializer());
4778 
4779   for (const auto *I : Record->decls()) {
4780     const auto *FD = dyn_cast<FieldDecl>(I);
4781     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4782       FD = IFD->getAnonField();
4783     if (FD && FD->hasInClassInitializer())
4784       return FD->getLocation();
4785   }
4786 
4787   llvm_unreachable("couldn't find in-class initializer");
4788 }
4789 
4790 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4791                                       SourceLocation DefaultInitLoc) {
4792   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4793     return;
4794 
4795   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4796   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4797 }
4798 
4799 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4800                                       CXXRecordDecl *AnonUnion) {
4801   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4802     return;
4803 
4804   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4805 }
4806 
4807 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4808 /// anonymous structure or union. Anonymous unions are a C++ feature
4809 /// (C++ [class.union]) and a C11 feature; anonymous structures
4810 /// are a C11 feature and GNU C++ extension.
4811 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4812                                         AccessSpecifier AS,
4813                                         RecordDecl *Record,
4814                                         const PrintingPolicy &Policy) {
4815   DeclContext *Owner = Record->getDeclContext();
4816 
4817   // Diagnose whether this anonymous struct/union is an extension.
4818   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4819     Diag(Record->getLocation(), diag::ext_anonymous_union);
4820   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4821     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4822   else if (!Record->isUnion() && !getLangOpts().C11)
4823     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4824 
4825   // C and C++ require different kinds of checks for anonymous
4826   // structs/unions.
4827   bool Invalid = false;
4828   if (getLangOpts().CPlusPlus) {
4829     const char *PrevSpec = nullptr;
4830     if (Record->isUnion()) {
4831       // C++ [class.union]p6:
4832       // C++17 [class.union.anon]p2:
4833       //   Anonymous unions declared in a named namespace or in the
4834       //   global namespace shall be declared static.
4835       unsigned DiagID;
4836       DeclContext *OwnerScope = Owner->getRedeclContext();
4837       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4838           (OwnerScope->isTranslationUnit() ||
4839            (OwnerScope->isNamespace() &&
4840             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4841         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4842           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4843 
4844         // Recover by adding 'static'.
4845         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4846                                PrevSpec, DiagID, Policy);
4847       }
4848       // C++ [class.union]p6:
4849       //   A storage class is not allowed in a declaration of an
4850       //   anonymous union in a class scope.
4851       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4852                isa<RecordDecl>(Owner)) {
4853         Diag(DS.getStorageClassSpecLoc(),
4854              diag::err_anonymous_union_with_storage_spec)
4855           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4856 
4857         // Recover by removing the storage specifier.
4858         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4859                                SourceLocation(),
4860                                PrevSpec, DiagID, Context.getPrintingPolicy());
4861       }
4862     }
4863 
4864     // Ignore const/volatile/restrict qualifiers.
4865     if (DS.getTypeQualifiers()) {
4866       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4867         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4868           << Record->isUnion() << "const"
4869           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4870       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4871         Diag(DS.getVolatileSpecLoc(),
4872              diag::ext_anonymous_struct_union_qualified)
4873           << Record->isUnion() << "volatile"
4874           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4875       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4876         Diag(DS.getRestrictSpecLoc(),
4877              diag::ext_anonymous_struct_union_qualified)
4878           << Record->isUnion() << "restrict"
4879           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4880       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4881         Diag(DS.getAtomicSpecLoc(),
4882              diag::ext_anonymous_struct_union_qualified)
4883           << Record->isUnion() << "_Atomic"
4884           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4885       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4886         Diag(DS.getUnalignedSpecLoc(),
4887              diag::ext_anonymous_struct_union_qualified)
4888           << Record->isUnion() << "__unaligned"
4889           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4890 
4891       DS.ClearTypeQualifiers();
4892     }
4893 
4894     // C++ [class.union]p2:
4895     //   The member-specification of an anonymous union shall only
4896     //   define non-static data members. [Note: nested types and
4897     //   functions cannot be declared within an anonymous union. ]
4898     for (auto *Mem : Record->decls()) {
4899       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4900         // C++ [class.union]p3:
4901         //   An anonymous union shall not have private or protected
4902         //   members (clause 11).
4903         assert(FD->getAccess() != AS_none);
4904         if (FD->getAccess() != AS_public) {
4905           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4906             << Record->isUnion() << (FD->getAccess() == AS_protected);
4907           Invalid = true;
4908         }
4909 
4910         // C++ [class.union]p1
4911         //   An object of a class with a non-trivial constructor, a non-trivial
4912         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4913         //   assignment operator cannot be a member of a union, nor can an
4914         //   array of such objects.
4915         if (CheckNontrivialField(FD))
4916           Invalid = true;
4917       } else if (Mem->isImplicit()) {
4918         // Any implicit members are fine.
4919       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4920         // This is a type that showed up in an
4921         // elaborated-type-specifier inside the anonymous struct or
4922         // union, but which actually declares a type outside of the
4923         // anonymous struct or union. It's okay.
4924       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4925         if (!MemRecord->isAnonymousStructOrUnion() &&
4926             MemRecord->getDeclName()) {
4927           // Visual C++ allows type definition in anonymous struct or union.
4928           if (getLangOpts().MicrosoftExt)
4929             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4930               << Record->isUnion();
4931           else {
4932             // This is a nested type declaration.
4933             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4934               << Record->isUnion();
4935             Invalid = true;
4936           }
4937         } else {
4938           // This is an anonymous type definition within another anonymous type.
4939           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4940           // not part of standard C++.
4941           Diag(MemRecord->getLocation(),
4942                diag::ext_anonymous_record_with_anonymous_type)
4943             << Record->isUnion();
4944         }
4945       } else if (isa<AccessSpecDecl>(Mem)) {
4946         // Any access specifier is fine.
4947       } else if (isa<StaticAssertDecl>(Mem)) {
4948         // In C++1z, static_assert declarations are also fine.
4949       } else {
4950         // We have something that isn't a non-static data
4951         // member. Complain about it.
4952         unsigned DK = diag::err_anonymous_record_bad_member;
4953         if (isa<TypeDecl>(Mem))
4954           DK = diag::err_anonymous_record_with_type;
4955         else if (isa<FunctionDecl>(Mem))
4956           DK = diag::err_anonymous_record_with_function;
4957         else if (isa<VarDecl>(Mem))
4958           DK = diag::err_anonymous_record_with_static;
4959 
4960         // Visual C++ allows type definition in anonymous struct or union.
4961         if (getLangOpts().MicrosoftExt &&
4962             DK == diag::err_anonymous_record_with_type)
4963           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4964             << Record->isUnion();
4965         else {
4966           Diag(Mem->getLocation(), DK) << Record->isUnion();
4967           Invalid = true;
4968         }
4969       }
4970     }
4971 
4972     // C++11 [class.union]p8 (DR1460):
4973     //   At most one variant member of a union may have a
4974     //   brace-or-equal-initializer.
4975     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4976         Owner->isRecord())
4977       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4978                                 cast<CXXRecordDecl>(Record));
4979   }
4980 
4981   if (!Record->isUnion() && !Owner->isRecord()) {
4982     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4983       << getLangOpts().CPlusPlus;
4984     Invalid = true;
4985   }
4986 
4987   // C++ [dcl.dcl]p3:
4988   //   [If there are no declarators], and except for the declaration of an
4989   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4990   //   names into the program
4991   // C++ [class.mem]p2:
4992   //   each such member-declaration shall either declare at least one member
4993   //   name of the class or declare at least one unnamed bit-field
4994   //
4995   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4996   if (getLangOpts().CPlusPlus && Record->field_empty())
4997     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4998 
4999   // Mock up a declarator.
5000   Declarator Dc(DS, DeclaratorContext::MemberContext);
5001   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5002   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5003 
5004   // Create a declaration for this anonymous struct/union.
5005   NamedDecl *Anon = nullptr;
5006   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5007     Anon = FieldDecl::Create(
5008         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5009         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5010         /*BitWidth=*/nullptr, /*Mutable=*/false,
5011         /*InitStyle=*/ICIS_NoInit);
5012     Anon->setAccess(AS);
5013     if (getLangOpts().CPlusPlus)
5014       FieldCollector->Add(cast<FieldDecl>(Anon));
5015   } else {
5016     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5017     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5018     if (SCSpec == DeclSpec::SCS_mutable) {
5019       // mutable can only appear on non-static class members, so it's always
5020       // an error here
5021       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5022       Invalid = true;
5023       SC = SC_None;
5024     }
5025 
5026     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5027                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5028                            Context.getTypeDeclType(Record), TInfo, SC);
5029 
5030     // Default-initialize the implicit variable. This initialization will be
5031     // trivial in almost all cases, except if a union member has an in-class
5032     // initializer:
5033     //   union { int n = 0; };
5034     ActOnUninitializedDecl(Anon);
5035   }
5036   Anon->setImplicit();
5037 
5038   // Mark this as an anonymous struct/union type.
5039   Record->setAnonymousStructOrUnion(true);
5040 
5041   // Add the anonymous struct/union object to the current
5042   // context. We'll be referencing this object when we refer to one of
5043   // its members.
5044   Owner->addDecl(Anon);
5045 
5046   // Inject the members of the anonymous struct/union into the owning
5047   // context and into the identifier resolver chain for name lookup
5048   // purposes.
5049   SmallVector<NamedDecl*, 2> Chain;
5050   Chain.push_back(Anon);
5051 
5052   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5053     Invalid = true;
5054 
5055   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5056     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5057       MangleNumberingContext *MCtx;
5058       Decl *ManglingContextDecl;
5059       std::tie(MCtx, ManglingContextDecl) =
5060           getCurrentMangleNumberContext(NewVD->getDeclContext());
5061       if (MCtx) {
5062         Context.setManglingNumber(
5063             NewVD, MCtx->getManglingNumber(
5064                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5065         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5066       }
5067     }
5068   }
5069 
5070   if (Invalid)
5071     Anon->setInvalidDecl();
5072 
5073   return Anon;
5074 }
5075 
5076 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5077 /// Microsoft C anonymous structure.
5078 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5079 /// Example:
5080 ///
5081 /// struct A { int a; };
5082 /// struct B { struct A; int b; };
5083 ///
5084 /// void foo() {
5085 ///   B var;
5086 ///   var.a = 3;
5087 /// }
5088 ///
5089 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5090                                            RecordDecl *Record) {
5091   assert(Record && "expected a record!");
5092 
5093   // Mock up a declarator.
5094   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5095   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5096   assert(TInfo && "couldn't build declarator info for anonymous struct");
5097 
5098   auto *ParentDecl = cast<RecordDecl>(CurContext);
5099   QualType RecTy = Context.getTypeDeclType(Record);
5100 
5101   // Create a declaration for this anonymous struct.
5102   NamedDecl *Anon =
5103       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5104                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5105                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5106                         /*InitStyle=*/ICIS_NoInit);
5107   Anon->setImplicit();
5108 
5109   // Add the anonymous struct object to the current context.
5110   CurContext->addDecl(Anon);
5111 
5112   // Inject the members of the anonymous struct into the current
5113   // context and into the identifier resolver chain for name lookup
5114   // purposes.
5115   SmallVector<NamedDecl*, 2> Chain;
5116   Chain.push_back(Anon);
5117 
5118   RecordDecl *RecordDef = Record->getDefinition();
5119   if (RequireCompleteType(Anon->getLocation(), RecTy,
5120                           diag::err_field_incomplete) ||
5121       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5122                                           AS_none, Chain)) {
5123     Anon->setInvalidDecl();
5124     ParentDecl->setInvalidDecl();
5125   }
5126 
5127   return Anon;
5128 }
5129 
5130 /// GetNameForDeclarator - Determine the full declaration name for the
5131 /// given Declarator.
5132 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5133   return GetNameFromUnqualifiedId(D.getName());
5134 }
5135 
5136 /// Retrieves the declaration name from a parsed unqualified-id.
5137 DeclarationNameInfo
5138 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5139   DeclarationNameInfo NameInfo;
5140   NameInfo.setLoc(Name.StartLocation);
5141 
5142   switch (Name.getKind()) {
5143 
5144   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5145   case UnqualifiedIdKind::IK_Identifier:
5146     NameInfo.setName(Name.Identifier);
5147     return NameInfo;
5148 
5149   case UnqualifiedIdKind::IK_DeductionGuideName: {
5150     // C++ [temp.deduct.guide]p3:
5151     //   The simple-template-id shall name a class template specialization.
5152     //   The template-name shall be the same identifier as the template-name
5153     //   of the simple-template-id.
5154     // These together intend to imply that the template-name shall name a
5155     // class template.
5156     // FIXME: template<typename T> struct X {};
5157     //        template<typename T> using Y = X<T>;
5158     //        Y(int) -> Y<int>;
5159     //   satisfies these rules but does not name a class template.
5160     TemplateName TN = Name.TemplateName.get().get();
5161     auto *Template = TN.getAsTemplateDecl();
5162     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5163       Diag(Name.StartLocation,
5164            diag::err_deduction_guide_name_not_class_template)
5165         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5166       if (Template)
5167         Diag(Template->getLocation(), diag::note_template_decl_here);
5168       return DeclarationNameInfo();
5169     }
5170 
5171     NameInfo.setName(
5172         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5173     return NameInfo;
5174   }
5175 
5176   case UnqualifiedIdKind::IK_OperatorFunctionId:
5177     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5178                                            Name.OperatorFunctionId.Operator));
5179     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5180       = Name.OperatorFunctionId.SymbolLocations[0];
5181     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5182       = Name.EndLocation.getRawEncoding();
5183     return NameInfo;
5184 
5185   case UnqualifiedIdKind::IK_LiteralOperatorId:
5186     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5187                                                            Name.Identifier));
5188     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5189     return NameInfo;
5190 
5191   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5192     TypeSourceInfo *TInfo;
5193     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5194     if (Ty.isNull())
5195       return DeclarationNameInfo();
5196     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5197                                                Context.getCanonicalType(Ty)));
5198     NameInfo.setNamedTypeInfo(TInfo);
5199     return NameInfo;
5200   }
5201 
5202   case UnqualifiedIdKind::IK_ConstructorName: {
5203     TypeSourceInfo *TInfo;
5204     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5205     if (Ty.isNull())
5206       return DeclarationNameInfo();
5207     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5208                                               Context.getCanonicalType(Ty)));
5209     NameInfo.setNamedTypeInfo(TInfo);
5210     return NameInfo;
5211   }
5212 
5213   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5214     // In well-formed code, we can only have a constructor
5215     // template-id that refers to the current context, so go there
5216     // to find the actual type being constructed.
5217     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5218     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5219       return DeclarationNameInfo();
5220 
5221     // Determine the type of the class being constructed.
5222     QualType CurClassType = Context.getTypeDeclType(CurClass);
5223 
5224     // FIXME: Check two things: that the template-id names the same type as
5225     // CurClassType, and that the template-id does not occur when the name
5226     // was qualified.
5227 
5228     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5229                                     Context.getCanonicalType(CurClassType)));
5230     // FIXME: should we retrieve TypeSourceInfo?
5231     NameInfo.setNamedTypeInfo(nullptr);
5232     return NameInfo;
5233   }
5234 
5235   case UnqualifiedIdKind::IK_DestructorName: {
5236     TypeSourceInfo *TInfo;
5237     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5238     if (Ty.isNull())
5239       return DeclarationNameInfo();
5240     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5241                                               Context.getCanonicalType(Ty)));
5242     NameInfo.setNamedTypeInfo(TInfo);
5243     return NameInfo;
5244   }
5245 
5246   case UnqualifiedIdKind::IK_TemplateId: {
5247     TemplateName TName = Name.TemplateId->Template.get();
5248     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5249     return Context.getNameForTemplate(TName, TNameLoc);
5250   }
5251 
5252   } // switch (Name.getKind())
5253 
5254   llvm_unreachable("Unknown name kind");
5255 }
5256 
5257 static QualType getCoreType(QualType Ty) {
5258   do {
5259     if (Ty->isPointerType() || Ty->isReferenceType())
5260       Ty = Ty->getPointeeType();
5261     else if (Ty->isArrayType())
5262       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5263     else
5264       return Ty.withoutLocalFastQualifiers();
5265   } while (true);
5266 }
5267 
5268 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5269 /// and Definition have "nearly" matching parameters. This heuristic is
5270 /// used to improve diagnostics in the case where an out-of-line function
5271 /// definition doesn't match any declaration within the class or namespace.
5272 /// Also sets Params to the list of indices to the parameters that differ
5273 /// between the declaration and the definition. If hasSimilarParameters
5274 /// returns true and Params is empty, then all of the parameters match.
5275 static bool hasSimilarParameters(ASTContext &Context,
5276                                      FunctionDecl *Declaration,
5277                                      FunctionDecl *Definition,
5278                                      SmallVectorImpl<unsigned> &Params) {
5279   Params.clear();
5280   if (Declaration->param_size() != Definition->param_size())
5281     return false;
5282   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5283     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5284     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5285 
5286     // The parameter types are identical
5287     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5288       continue;
5289 
5290     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5291     QualType DefParamBaseTy = getCoreType(DefParamTy);
5292     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5293     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5294 
5295     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5296         (DeclTyName && DeclTyName == DefTyName))
5297       Params.push_back(Idx);
5298     else  // The two parameters aren't even close
5299       return false;
5300   }
5301 
5302   return true;
5303 }
5304 
5305 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5306 /// declarator needs to be rebuilt in the current instantiation.
5307 /// Any bits of declarator which appear before the name are valid for
5308 /// consideration here.  That's specifically the type in the decl spec
5309 /// and the base type in any member-pointer chunks.
5310 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5311                                                     DeclarationName Name) {
5312   // The types we specifically need to rebuild are:
5313   //   - typenames, typeofs, and decltypes
5314   //   - types which will become injected class names
5315   // Of course, we also need to rebuild any type referencing such a
5316   // type.  It's safest to just say "dependent", but we call out a
5317   // few cases here.
5318 
5319   DeclSpec &DS = D.getMutableDeclSpec();
5320   switch (DS.getTypeSpecType()) {
5321   case DeclSpec::TST_typename:
5322   case DeclSpec::TST_typeofType:
5323   case DeclSpec::TST_underlyingType:
5324   case DeclSpec::TST_atomic: {
5325     // Grab the type from the parser.
5326     TypeSourceInfo *TSI = nullptr;
5327     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5328     if (T.isNull() || !T->isDependentType()) break;
5329 
5330     // Make sure there's a type source info.  This isn't really much
5331     // of a waste; most dependent types should have type source info
5332     // attached already.
5333     if (!TSI)
5334       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5335 
5336     // Rebuild the type in the current instantiation.
5337     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5338     if (!TSI) return true;
5339 
5340     // Store the new type back in the decl spec.
5341     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5342     DS.UpdateTypeRep(LocType);
5343     break;
5344   }
5345 
5346   case DeclSpec::TST_decltype:
5347   case DeclSpec::TST_typeofExpr: {
5348     Expr *E = DS.getRepAsExpr();
5349     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5350     if (Result.isInvalid()) return true;
5351     DS.UpdateExprRep(Result.get());
5352     break;
5353   }
5354 
5355   default:
5356     // Nothing to do for these decl specs.
5357     break;
5358   }
5359 
5360   // It doesn't matter what order we do this in.
5361   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5362     DeclaratorChunk &Chunk = D.getTypeObject(I);
5363 
5364     // The only type information in the declarator which can come
5365     // before the declaration name is the base type of a member
5366     // pointer.
5367     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5368       continue;
5369 
5370     // Rebuild the scope specifier in-place.
5371     CXXScopeSpec &SS = Chunk.Mem.Scope();
5372     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5373       return true;
5374   }
5375 
5376   return false;
5377 }
5378 
5379 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5380   D.setFunctionDefinitionKind(FDK_Declaration);
5381   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5382 
5383   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5384       Dcl && Dcl->getDeclContext()->isFileContext())
5385     Dcl->setTopLevelDeclInObjCContainer();
5386 
5387   if (getLangOpts().OpenCL)
5388     setCurrentOpenCLExtensionForDecl(Dcl);
5389 
5390   return Dcl;
5391 }
5392 
5393 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5394 ///   If T is the name of a class, then each of the following shall have a
5395 ///   name different from T:
5396 ///     - every static data member of class T;
5397 ///     - every member function of class T
5398 ///     - every member of class T that is itself a type;
5399 /// \returns true if the declaration name violates these rules.
5400 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5401                                    DeclarationNameInfo NameInfo) {
5402   DeclarationName Name = NameInfo.getName();
5403 
5404   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5405   while (Record && Record->isAnonymousStructOrUnion())
5406     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5407   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5408     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5409     return true;
5410   }
5411 
5412   return false;
5413 }
5414 
5415 /// Diagnose a declaration whose declarator-id has the given
5416 /// nested-name-specifier.
5417 ///
5418 /// \param SS The nested-name-specifier of the declarator-id.
5419 ///
5420 /// \param DC The declaration context to which the nested-name-specifier
5421 /// resolves.
5422 ///
5423 /// \param Name The name of the entity being declared.
5424 ///
5425 /// \param Loc The location of the name of the entity being declared.
5426 ///
5427 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5428 /// we're declaring an explicit / partial specialization / instantiation.
5429 ///
5430 /// \returns true if we cannot safely recover from this error, false otherwise.
5431 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5432                                         DeclarationName Name,
5433                                         SourceLocation Loc, bool IsTemplateId) {
5434   DeclContext *Cur = CurContext;
5435   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5436     Cur = Cur->getParent();
5437 
5438   // If the user provided a superfluous scope specifier that refers back to the
5439   // class in which the entity is already declared, diagnose and ignore it.
5440   //
5441   // class X {
5442   //   void X::f();
5443   // };
5444   //
5445   // Note, it was once ill-formed to give redundant qualification in all
5446   // contexts, but that rule was removed by DR482.
5447   if (Cur->Equals(DC)) {
5448     if (Cur->isRecord()) {
5449       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5450                                       : diag::err_member_extra_qualification)
5451         << Name << FixItHint::CreateRemoval(SS.getRange());
5452       SS.clear();
5453     } else {
5454       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5455     }
5456     return false;
5457   }
5458 
5459   // Check whether the qualifying scope encloses the scope of the original
5460   // declaration. For a template-id, we perform the checks in
5461   // CheckTemplateSpecializationScope.
5462   if (!Cur->Encloses(DC) && !IsTemplateId) {
5463     if (Cur->isRecord())
5464       Diag(Loc, diag::err_member_qualification)
5465         << Name << SS.getRange();
5466     else if (isa<TranslationUnitDecl>(DC))
5467       Diag(Loc, diag::err_invalid_declarator_global_scope)
5468         << Name << SS.getRange();
5469     else if (isa<FunctionDecl>(Cur))
5470       Diag(Loc, diag::err_invalid_declarator_in_function)
5471         << Name << SS.getRange();
5472     else if (isa<BlockDecl>(Cur))
5473       Diag(Loc, diag::err_invalid_declarator_in_block)
5474         << Name << SS.getRange();
5475     else
5476       Diag(Loc, diag::err_invalid_declarator_scope)
5477       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5478 
5479     return true;
5480   }
5481 
5482   if (Cur->isRecord()) {
5483     // Cannot qualify members within a class.
5484     Diag(Loc, diag::err_member_qualification)
5485       << Name << SS.getRange();
5486     SS.clear();
5487 
5488     // C++ constructors and destructors with incorrect scopes can break
5489     // our AST invariants by having the wrong underlying types. If
5490     // that's the case, then drop this declaration entirely.
5491     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5492          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5493         !Context.hasSameType(Name.getCXXNameType(),
5494                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5495       return true;
5496 
5497     return false;
5498   }
5499 
5500   // C++11 [dcl.meaning]p1:
5501   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5502   //   not begin with a decltype-specifer"
5503   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5504   while (SpecLoc.getPrefix())
5505     SpecLoc = SpecLoc.getPrefix();
5506   if (dyn_cast_or_null<DecltypeType>(
5507         SpecLoc.getNestedNameSpecifier()->getAsType()))
5508     Diag(Loc, diag::err_decltype_in_declarator)
5509       << SpecLoc.getTypeLoc().getSourceRange();
5510 
5511   return false;
5512 }
5513 
5514 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5515                                   MultiTemplateParamsArg TemplateParamLists) {
5516   // TODO: consider using NameInfo for diagnostic.
5517   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5518   DeclarationName Name = NameInfo.getName();
5519 
5520   // All of these full declarators require an identifier.  If it doesn't have
5521   // one, the ParsedFreeStandingDeclSpec action should be used.
5522   if (D.isDecompositionDeclarator()) {
5523     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5524   } else if (!Name) {
5525     if (!D.isInvalidType())  // Reject this if we think it is valid.
5526       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5527           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5528     return nullptr;
5529   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5530     return nullptr;
5531 
5532   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5533   // we find one that is.
5534   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5535          (S->getFlags() & Scope::TemplateParamScope) != 0)
5536     S = S->getParent();
5537 
5538   DeclContext *DC = CurContext;
5539   if (D.getCXXScopeSpec().isInvalid())
5540     D.setInvalidType();
5541   else if (D.getCXXScopeSpec().isSet()) {
5542     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5543                                         UPPC_DeclarationQualifier))
5544       return nullptr;
5545 
5546     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5547     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5548     if (!DC || isa<EnumDecl>(DC)) {
5549       // If we could not compute the declaration context, it's because the
5550       // declaration context is dependent but does not refer to a class,
5551       // class template, or class template partial specialization. Complain
5552       // and return early, to avoid the coming semantic disaster.
5553       Diag(D.getIdentifierLoc(),
5554            diag::err_template_qualified_declarator_no_match)
5555         << D.getCXXScopeSpec().getScopeRep()
5556         << D.getCXXScopeSpec().getRange();
5557       return nullptr;
5558     }
5559     bool IsDependentContext = DC->isDependentContext();
5560 
5561     if (!IsDependentContext &&
5562         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5563       return nullptr;
5564 
5565     // If a class is incomplete, do not parse entities inside it.
5566     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5567       Diag(D.getIdentifierLoc(),
5568            diag::err_member_def_undefined_record)
5569         << Name << DC << D.getCXXScopeSpec().getRange();
5570       return nullptr;
5571     }
5572     if (!D.getDeclSpec().isFriendSpecified()) {
5573       if (diagnoseQualifiedDeclaration(
5574               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5575               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5576         if (DC->isRecord())
5577           return nullptr;
5578 
5579         D.setInvalidType();
5580       }
5581     }
5582 
5583     // Check whether we need to rebuild the type of the given
5584     // declaration in the current instantiation.
5585     if (EnteringContext && IsDependentContext &&
5586         TemplateParamLists.size() != 0) {
5587       ContextRAII SavedContext(*this, DC);
5588       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5589         D.setInvalidType();
5590     }
5591   }
5592 
5593   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5594   QualType R = TInfo->getType();
5595 
5596   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5597                                       UPPC_DeclarationType))
5598     D.setInvalidType();
5599 
5600   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5601                         forRedeclarationInCurContext());
5602 
5603   // See if this is a redefinition of a variable in the same scope.
5604   if (!D.getCXXScopeSpec().isSet()) {
5605     bool IsLinkageLookup = false;
5606     bool CreateBuiltins = false;
5607 
5608     // If the declaration we're planning to build will be a function
5609     // or object with linkage, then look for another declaration with
5610     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5611     //
5612     // If the declaration we're planning to build will be declared with
5613     // external linkage in the translation unit, create any builtin with
5614     // the same name.
5615     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5616       /* Do nothing*/;
5617     else if (CurContext->isFunctionOrMethod() &&
5618              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5619               R->isFunctionType())) {
5620       IsLinkageLookup = true;
5621       CreateBuiltins =
5622           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5623     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5624                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5625       CreateBuiltins = true;
5626 
5627     if (IsLinkageLookup) {
5628       Previous.clear(LookupRedeclarationWithLinkage);
5629       Previous.setRedeclarationKind(ForExternalRedeclaration);
5630     }
5631 
5632     LookupName(Previous, S, CreateBuiltins);
5633   } else { // Something like "int foo::x;"
5634     LookupQualifiedName(Previous, DC);
5635 
5636     // C++ [dcl.meaning]p1:
5637     //   When the declarator-id is qualified, the declaration shall refer to a
5638     //  previously declared member of the class or namespace to which the
5639     //  qualifier refers (or, in the case of a namespace, of an element of the
5640     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5641     //  thereof; [...]
5642     //
5643     // Note that we already checked the context above, and that we do not have
5644     // enough information to make sure that Previous contains the declaration
5645     // we want to match. For example, given:
5646     //
5647     //   class X {
5648     //     void f();
5649     //     void f(float);
5650     //   };
5651     //
5652     //   void X::f(int) { } // ill-formed
5653     //
5654     // In this case, Previous will point to the overload set
5655     // containing the two f's declared in X, but neither of them
5656     // matches.
5657 
5658     // C++ [dcl.meaning]p1:
5659     //   [...] the member shall not merely have been introduced by a
5660     //   using-declaration in the scope of the class or namespace nominated by
5661     //   the nested-name-specifier of the declarator-id.
5662     RemoveUsingDecls(Previous);
5663   }
5664 
5665   if (Previous.isSingleResult() &&
5666       Previous.getFoundDecl()->isTemplateParameter()) {
5667     // Maybe we will complain about the shadowed template parameter.
5668     if (!D.isInvalidType())
5669       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5670                                       Previous.getFoundDecl());
5671 
5672     // Just pretend that we didn't see the previous declaration.
5673     Previous.clear();
5674   }
5675 
5676   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5677     // Forget that the previous declaration is the injected-class-name.
5678     Previous.clear();
5679 
5680   // In C++, the previous declaration we find might be a tag type
5681   // (class or enum). In this case, the new declaration will hide the
5682   // tag type. Note that this applies to functions, function templates, and
5683   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5684   if (Previous.isSingleTagDecl() &&
5685       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5686       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5687     Previous.clear();
5688 
5689   // Check that there are no default arguments other than in the parameters
5690   // of a function declaration (C++ only).
5691   if (getLangOpts().CPlusPlus)
5692     CheckExtraCXXDefaultArguments(D);
5693 
5694   NamedDecl *New;
5695 
5696   bool AddToScope = true;
5697   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5698     if (TemplateParamLists.size()) {
5699       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5700       return nullptr;
5701     }
5702 
5703     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5704   } else if (R->isFunctionType()) {
5705     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5706                                   TemplateParamLists,
5707                                   AddToScope);
5708   } else {
5709     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5710                                   AddToScope);
5711   }
5712 
5713   if (!New)
5714     return nullptr;
5715 
5716   // If this has an identifier and is not a function template specialization,
5717   // add it to the scope stack.
5718   if (New->getDeclName() && AddToScope)
5719     PushOnScopeChains(New, S);
5720 
5721   if (isInOpenMPDeclareTargetContext())
5722     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5723 
5724   return New;
5725 }
5726 
5727 /// Helper method to turn variable array types into constant array
5728 /// types in certain situations which would otherwise be errors (for
5729 /// GCC compatibility).
5730 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5731                                                     ASTContext &Context,
5732                                                     bool &SizeIsNegative,
5733                                                     llvm::APSInt &Oversized) {
5734   // This method tries to turn a variable array into a constant
5735   // array even when the size isn't an ICE.  This is necessary
5736   // for compatibility with code that depends on gcc's buggy
5737   // constant expression folding, like struct {char x[(int)(char*)2];}
5738   SizeIsNegative = false;
5739   Oversized = 0;
5740 
5741   if (T->isDependentType())
5742     return QualType();
5743 
5744   QualifierCollector Qs;
5745   const Type *Ty = Qs.strip(T);
5746 
5747   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5748     QualType Pointee = PTy->getPointeeType();
5749     QualType FixedType =
5750         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5751                                             Oversized);
5752     if (FixedType.isNull()) return FixedType;
5753     FixedType = Context.getPointerType(FixedType);
5754     return Qs.apply(Context, FixedType);
5755   }
5756   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5757     QualType Inner = PTy->getInnerType();
5758     QualType FixedType =
5759         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5760                                             Oversized);
5761     if (FixedType.isNull()) return FixedType;
5762     FixedType = Context.getParenType(FixedType);
5763     return Qs.apply(Context, FixedType);
5764   }
5765 
5766   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5767   if (!VLATy)
5768     return QualType();
5769   // FIXME: We should probably handle this case
5770   if (VLATy->getElementType()->isVariablyModifiedType())
5771     return QualType();
5772 
5773   Expr::EvalResult Result;
5774   if (!VLATy->getSizeExpr() ||
5775       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5776     return QualType();
5777 
5778   llvm::APSInt Res = Result.Val.getInt();
5779 
5780   // Check whether the array size is negative.
5781   if (Res.isSigned() && Res.isNegative()) {
5782     SizeIsNegative = true;
5783     return QualType();
5784   }
5785 
5786   // Check whether the array is too large to be addressed.
5787   unsigned ActiveSizeBits
5788     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5789                                               Res);
5790   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5791     Oversized = Res;
5792     return QualType();
5793   }
5794 
5795   return Context.getConstantArrayType(
5796       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5797 }
5798 
5799 static void
5800 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5801   SrcTL = SrcTL.getUnqualifiedLoc();
5802   DstTL = DstTL.getUnqualifiedLoc();
5803   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5804     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5805     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5806                                       DstPTL.getPointeeLoc());
5807     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5808     return;
5809   }
5810   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5811     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5812     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5813                                       DstPTL.getInnerLoc());
5814     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5815     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5816     return;
5817   }
5818   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5819   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5820   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5821   TypeLoc DstElemTL = DstATL.getElementLoc();
5822   DstElemTL.initializeFullCopy(SrcElemTL);
5823   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5824   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5825   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5826 }
5827 
5828 /// Helper method to turn variable array types into constant array
5829 /// types in certain situations which would otherwise be errors (for
5830 /// GCC compatibility).
5831 static TypeSourceInfo*
5832 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5833                                               ASTContext &Context,
5834                                               bool &SizeIsNegative,
5835                                               llvm::APSInt &Oversized) {
5836   QualType FixedTy
5837     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5838                                           SizeIsNegative, Oversized);
5839   if (FixedTy.isNull())
5840     return nullptr;
5841   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5842   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5843                                     FixedTInfo->getTypeLoc());
5844   return FixedTInfo;
5845 }
5846 
5847 /// Register the given locally-scoped extern "C" declaration so
5848 /// that it can be found later for redeclarations. We include any extern "C"
5849 /// declaration that is not visible in the translation unit here, not just
5850 /// function-scope declarations.
5851 void
5852 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5853   if (!getLangOpts().CPlusPlus &&
5854       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5855     // Don't need to track declarations in the TU in C.
5856     return;
5857 
5858   // Note that we have a locally-scoped external with this name.
5859   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5860 }
5861 
5862 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5863   // FIXME: We can have multiple results via __attribute__((overloadable)).
5864   auto Result = Context.getExternCContextDecl()->lookup(Name);
5865   return Result.empty() ? nullptr : *Result.begin();
5866 }
5867 
5868 /// Diagnose function specifiers on a declaration of an identifier that
5869 /// does not identify a function.
5870 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5871   // FIXME: We should probably indicate the identifier in question to avoid
5872   // confusion for constructs like "virtual int a(), b;"
5873   if (DS.isVirtualSpecified())
5874     Diag(DS.getVirtualSpecLoc(),
5875          diag::err_virtual_non_function);
5876 
5877   if (DS.hasExplicitSpecifier())
5878     Diag(DS.getExplicitSpecLoc(),
5879          diag::err_explicit_non_function);
5880 
5881   if (DS.isNoreturnSpecified())
5882     Diag(DS.getNoreturnSpecLoc(),
5883          diag::err_noreturn_non_function);
5884 }
5885 
5886 NamedDecl*
5887 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5888                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5889   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5890   if (D.getCXXScopeSpec().isSet()) {
5891     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5892       << D.getCXXScopeSpec().getRange();
5893     D.setInvalidType();
5894     // Pretend we didn't see the scope specifier.
5895     DC = CurContext;
5896     Previous.clear();
5897   }
5898 
5899   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5900 
5901   if (D.getDeclSpec().isInlineSpecified())
5902     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5903         << getLangOpts().CPlusPlus17;
5904   if (D.getDeclSpec().hasConstexprSpecifier())
5905     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5906         << 1 << D.getDeclSpec().getConstexprSpecifier();
5907 
5908   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5909     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5910       Diag(D.getName().StartLocation,
5911            diag::err_deduction_guide_invalid_specifier)
5912           << "typedef";
5913     else
5914       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5915           << D.getName().getSourceRange();
5916     return nullptr;
5917   }
5918 
5919   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5920   if (!NewTD) return nullptr;
5921 
5922   // Handle attributes prior to checking for duplicates in MergeVarDecl
5923   ProcessDeclAttributes(S, NewTD, D);
5924 
5925   CheckTypedefForVariablyModifiedType(S, NewTD);
5926 
5927   bool Redeclaration = D.isRedeclaration();
5928   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5929   D.setRedeclaration(Redeclaration);
5930   return ND;
5931 }
5932 
5933 void
5934 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5935   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5936   // then it shall have block scope.
5937   // Note that variably modified types must be fixed before merging the decl so
5938   // that redeclarations will match.
5939   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5940   QualType T = TInfo->getType();
5941   if (T->isVariablyModifiedType()) {
5942     setFunctionHasBranchProtectedScope();
5943 
5944     if (S->getFnParent() == nullptr) {
5945       bool SizeIsNegative;
5946       llvm::APSInt Oversized;
5947       TypeSourceInfo *FixedTInfo =
5948         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5949                                                       SizeIsNegative,
5950                                                       Oversized);
5951       if (FixedTInfo) {
5952         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5953         NewTD->setTypeSourceInfo(FixedTInfo);
5954       } else {
5955         if (SizeIsNegative)
5956           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5957         else if (T->isVariableArrayType())
5958           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5959         else if (Oversized.getBoolValue())
5960           Diag(NewTD->getLocation(), diag::err_array_too_large)
5961             << Oversized.toString(10);
5962         else
5963           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5964         NewTD->setInvalidDecl();
5965       }
5966     }
5967   }
5968 }
5969 
5970 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5971 /// declares a typedef-name, either using the 'typedef' type specifier or via
5972 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5973 NamedDecl*
5974 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5975                            LookupResult &Previous, bool &Redeclaration) {
5976 
5977   // Find the shadowed declaration before filtering for scope.
5978   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5979 
5980   // Merge the decl with the existing one if appropriate. If the decl is
5981   // in an outer scope, it isn't the same thing.
5982   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5983                        /*AllowInlineNamespace*/false);
5984   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5985   if (!Previous.empty()) {
5986     Redeclaration = true;
5987     MergeTypedefNameDecl(S, NewTD, Previous);
5988   } else {
5989     inferGslPointerAttribute(NewTD);
5990   }
5991 
5992   if (ShadowedDecl && !Redeclaration)
5993     CheckShadow(NewTD, ShadowedDecl, Previous);
5994 
5995   // If this is the C FILE type, notify the AST context.
5996   if (IdentifierInfo *II = NewTD->getIdentifier())
5997     if (!NewTD->isInvalidDecl() &&
5998         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5999       if (II->isStr("FILE"))
6000         Context.setFILEDecl(NewTD);
6001       else if (II->isStr("jmp_buf"))
6002         Context.setjmp_bufDecl(NewTD);
6003       else if (II->isStr("sigjmp_buf"))
6004         Context.setsigjmp_bufDecl(NewTD);
6005       else if (II->isStr("ucontext_t"))
6006         Context.setucontext_tDecl(NewTD);
6007     }
6008 
6009   return NewTD;
6010 }
6011 
6012 /// Determines whether the given declaration is an out-of-scope
6013 /// previous declaration.
6014 ///
6015 /// This routine should be invoked when name lookup has found a
6016 /// previous declaration (PrevDecl) that is not in the scope where a
6017 /// new declaration by the same name is being introduced. If the new
6018 /// declaration occurs in a local scope, previous declarations with
6019 /// linkage may still be considered previous declarations (C99
6020 /// 6.2.2p4-5, C++ [basic.link]p6).
6021 ///
6022 /// \param PrevDecl the previous declaration found by name
6023 /// lookup
6024 ///
6025 /// \param DC the context in which the new declaration is being
6026 /// declared.
6027 ///
6028 /// \returns true if PrevDecl is an out-of-scope previous declaration
6029 /// for a new delcaration with the same name.
6030 static bool
6031 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6032                                 ASTContext &Context) {
6033   if (!PrevDecl)
6034     return false;
6035 
6036   if (!PrevDecl->hasLinkage())
6037     return false;
6038 
6039   if (Context.getLangOpts().CPlusPlus) {
6040     // C++ [basic.link]p6:
6041     //   If there is a visible declaration of an entity with linkage
6042     //   having the same name and type, ignoring entities declared
6043     //   outside the innermost enclosing namespace scope, the block
6044     //   scope declaration declares that same entity and receives the
6045     //   linkage of the previous declaration.
6046     DeclContext *OuterContext = DC->getRedeclContext();
6047     if (!OuterContext->isFunctionOrMethod())
6048       // This rule only applies to block-scope declarations.
6049       return false;
6050 
6051     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6052     if (PrevOuterContext->isRecord())
6053       // We found a member function: ignore it.
6054       return false;
6055 
6056     // Find the innermost enclosing namespace for the new and
6057     // previous declarations.
6058     OuterContext = OuterContext->getEnclosingNamespaceContext();
6059     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6060 
6061     // The previous declaration is in a different namespace, so it
6062     // isn't the same function.
6063     if (!OuterContext->Equals(PrevOuterContext))
6064       return false;
6065   }
6066 
6067   return true;
6068 }
6069 
6070 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6071   CXXScopeSpec &SS = D.getCXXScopeSpec();
6072   if (!SS.isSet()) return;
6073   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6074 }
6075 
6076 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6077   QualType type = decl->getType();
6078   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6079   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6080     // Various kinds of declaration aren't allowed to be __autoreleasing.
6081     unsigned kind = -1U;
6082     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6083       if (var->hasAttr<BlocksAttr>())
6084         kind = 0; // __block
6085       else if (!var->hasLocalStorage())
6086         kind = 1; // global
6087     } else if (isa<ObjCIvarDecl>(decl)) {
6088       kind = 3; // ivar
6089     } else if (isa<FieldDecl>(decl)) {
6090       kind = 2; // field
6091     }
6092 
6093     if (kind != -1U) {
6094       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6095         << kind;
6096     }
6097   } else if (lifetime == Qualifiers::OCL_None) {
6098     // Try to infer lifetime.
6099     if (!type->isObjCLifetimeType())
6100       return false;
6101 
6102     lifetime = type->getObjCARCImplicitLifetime();
6103     type = Context.getLifetimeQualifiedType(type, lifetime);
6104     decl->setType(type);
6105   }
6106 
6107   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6108     // Thread-local variables cannot have lifetime.
6109     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6110         var->getTLSKind()) {
6111       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6112         << var->getType();
6113       return true;
6114     }
6115   }
6116 
6117   return false;
6118 }
6119 
6120 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6121   if (Decl->getType().getQualifiers().hasAddressSpace())
6122     return;
6123   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6124     QualType Type = Var->getType();
6125     if (Type->isSamplerT() || Type->isVoidType())
6126       return;
6127     LangAS ImplAS = LangAS::opencl_private;
6128     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6129         Var->hasGlobalStorage())
6130       ImplAS = LangAS::opencl_global;
6131     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6132     Decl->setType(Type);
6133   }
6134 }
6135 
6136 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6137   // Ensure that an auto decl is deduced otherwise the checks below might cache
6138   // the wrong linkage.
6139   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6140 
6141   // 'weak' only applies to declarations with external linkage.
6142   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6143     if (!ND.isExternallyVisible()) {
6144       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6145       ND.dropAttr<WeakAttr>();
6146     }
6147   }
6148   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6149     if (ND.isExternallyVisible()) {
6150       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6151       ND.dropAttr<WeakRefAttr>();
6152       ND.dropAttr<AliasAttr>();
6153     }
6154   }
6155 
6156   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6157     if (VD->hasInit()) {
6158       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6159         assert(VD->isThisDeclarationADefinition() &&
6160                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6161         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6162         VD->dropAttr<AliasAttr>();
6163       }
6164     }
6165   }
6166 
6167   // 'selectany' only applies to externally visible variable declarations.
6168   // It does not apply to functions.
6169   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6170     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6171       S.Diag(Attr->getLocation(),
6172              diag::err_attribute_selectany_non_extern_data);
6173       ND.dropAttr<SelectAnyAttr>();
6174     }
6175   }
6176 
6177   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6178     auto *VD = dyn_cast<VarDecl>(&ND);
6179     bool IsAnonymousNS = false;
6180     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6181     if (VD) {
6182       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6183       while (NS && !IsAnonymousNS) {
6184         IsAnonymousNS = NS->isAnonymousNamespace();
6185         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6186       }
6187     }
6188     // dll attributes require external linkage. Static locals may have external
6189     // linkage but still cannot be explicitly imported or exported.
6190     // In Microsoft mode, a variable defined in anonymous namespace must have
6191     // external linkage in order to be exported.
6192     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6193     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6194         (!AnonNSInMicrosoftMode &&
6195          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6196       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6197         << &ND << Attr;
6198       ND.setInvalidDecl();
6199     }
6200   }
6201 
6202   // Virtual functions cannot be marked as 'notail'.
6203   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6204     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6205       if (MD->isVirtual()) {
6206         S.Diag(ND.getLocation(),
6207                diag::err_invalid_attribute_on_virtual_function)
6208             << Attr;
6209         ND.dropAttr<NotTailCalledAttr>();
6210       }
6211 
6212   // Check the attributes on the function type, if any.
6213   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6214     // Don't declare this variable in the second operand of the for-statement;
6215     // GCC miscompiles that by ending its lifetime before evaluating the
6216     // third operand. See gcc.gnu.org/PR86769.
6217     AttributedTypeLoc ATL;
6218     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6219          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6220          TL = ATL.getModifiedLoc()) {
6221       // The [[lifetimebound]] attribute can be applied to the implicit object
6222       // parameter of a non-static member function (other than a ctor or dtor)
6223       // by applying it to the function type.
6224       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6225         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6226         if (!MD || MD->isStatic()) {
6227           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6228               << !MD << A->getRange();
6229         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6230           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6231               << isa<CXXDestructorDecl>(MD) << A->getRange();
6232         }
6233       }
6234     }
6235   }
6236 }
6237 
6238 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6239                                            NamedDecl *NewDecl,
6240                                            bool IsSpecialization,
6241                                            bool IsDefinition) {
6242   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6243     return;
6244 
6245   bool IsTemplate = false;
6246   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6247     OldDecl = OldTD->getTemplatedDecl();
6248     IsTemplate = true;
6249     if (!IsSpecialization)
6250       IsDefinition = false;
6251   }
6252   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6253     NewDecl = NewTD->getTemplatedDecl();
6254     IsTemplate = true;
6255   }
6256 
6257   if (!OldDecl || !NewDecl)
6258     return;
6259 
6260   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6261   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6262   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6263   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6264 
6265   // dllimport and dllexport are inheritable attributes so we have to exclude
6266   // inherited attribute instances.
6267   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6268                     (NewExportAttr && !NewExportAttr->isInherited());
6269 
6270   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6271   // the only exception being explicit specializations.
6272   // Implicitly generated declarations are also excluded for now because there
6273   // is no other way to switch these to use dllimport or dllexport.
6274   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6275 
6276   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6277     // Allow with a warning for free functions and global variables.
6278     bool JustWarn = false;
6279     if (!OldDecl->isCXXClassMember()) {
6280       auto *VD = dyn_cast<VarDecl>(OldDecl);
6281       if (VD && !VD->getDescribedVarTemplate())
6282         JustWarn = true;
6283       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6284       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6285         JustWarn = true;
6286     }
6287 
6288     // We cannot change a declaration that's been used because IR has already
6289     // been emitted. Dllimported functions will still work though (modulo
6290     // address equality) as they can use the thunk.
6291     if (OldDecl->isUsed())
6292       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6293         JustWarn = false;
6294 
6295     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6296                                : diag::err_attribute_dll_redeclaration;
6297     S.Diag(NewDecl->getLocation(), DiagID)
6298         << NewDecl
6299         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6300     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6301     if (!JustWarn) {
6302       NewDecl->setInvalidDecl();
6303       return;
6304     }
6305   }
6306 
6307   // A redeclaration is not allowed to drop a dllimport attribute, the only
6308   // exceptions being inline function definitions (except for function
6309   // templates), local extern declarations, qualified friend declarations or
6310   // special MSVC extension: in the last case, the declaration is treated as if
6311   // it were marked dllexport.
6312   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6313   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6314   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6315     // Ignore static data because out-of-line definitions are diagnosed
6316     // separately.
6317     IsStaticDataMember = VD->isStaticDataMember();
6318     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6319                    VarDecl::DeclarationOnly;
6320   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6321     IsInline = FD->isInlined();
6322     IsQualifiedFriend = FD->getQualifier() &&
6323                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6324   }
6325 
6326   if (OldImportAttr && !HasNewAttr &&
6327       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6328       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6329     if (IsMicrosoft && IsDefinition) {
6330       S.Diag(NewDecl->getLocation(),
6331              diag::warn_redeclaration_without_import_attribute)
6332           << NewDecl;
6333       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6334       NewDecl->dropAttr<DLLImportAttr>();
6335       NewDecl->addAttr(
6336           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6337     } else {
6338       S.Diag(NewDecl->getLocation(),
6339              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6340           << NewDecl << OldImportAttr;
6341       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6342       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6343       OldDecl->dropAttr<DLLImportAttr>();
6344       NewDecl->dropAttr<DLLImportAttr>();
6345     }
6346   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6347     // In MinGW, seeing a function declared inline drops the dllimport
6348     // attribute.
6349     OldDecl->dropAttr<DLLImportAttr>();
6350     NewDecl->dropAttr<DLLImportAttr>();
6351     S.Diag(NewDecl->getLocation(),
6352            diag::warn_dllimport_dropped_from_inline_function)
6353         << NewDecl << OldImportAttr;
6354   }
6355 
6356   // A specialization of a class template member function is processed here
6357   // since it's a redeclaration. If the parent class is dllexport, the
6358   // specialization inherits that attribute. This doesn't happen automatically
6359   // since the parent class isn't instantiated until later.
6360   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6361     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6362         !NewImportAttr && !NewExportAttr) {
6363       if (const DLLExportAttr *ParentExportAttr =
6364               MD->getParent()->getAttr<DLLExportAttr>()) {
6365         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6366         NewAttr->setInherited(true);
6367         NewDecl->addAttr(NewAttr);
6368       }
6369     }
6370   }
6371 }
6372 
6373 /// Given that we are within the definition of the given function,
6374 /// will that definition behave like C99's 'inline', where the
6375 /// definition is discarded except for optimization purposes?
6376 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6377   // Try to avoid calling GetGVALinkageForFunction.
6378 
6379   // All cases of this require the 'inline' keyword.
6380   if (!FD->isInlined()) return false;
6381 
6382   // This is only possible in C++ with the gnu_inline attribute.
6383   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6384     return false;
6385 
6386   // Okay, go ahead and call the relatively-more-expensive function.
6387   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6388 }
6389 
6390 /// Determine whether a variable is extern "C" prior to attaching
6391 /// an initializer. We can't just call isExternC() here, because that
6392 /// will also compute and cache whether the declaration is externally
6393 /// visible, which might change when we attach the initializer.
6394 ///
6395 /// This can only be used if the declaration is known to not be a
6396 /// redeclaration of an internal linkage declaration.
6397 ///
6398 /// For instance:
6399 ///
6400 ///   auto x = []{};
6401 ///
6402 /// Attaching the initializer here makes this declaration not externally
6403 /// visible, because its type has internal linkage.
6404 ///
6405 /// FIXME: This is a hack.
6406 template<typename T>
6407 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6408   if (S.getLangOpts().CPlusPlus) {
6409     // In C++, the overloadable attribute negates the effects of extern "C".
6410     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6411       return false;
6412 
6413     // So do CUDA's host/device attributes.
6414     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6415                                  D->template hasAttr<CUDAHostAttr>()))
6416       return false;
6417   }
6418   return D->isExternC();
6419 }
6420 
6421 static bool shouldConsiderLinkage(const VarDecl *VD) {
6422   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6423   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6424       isa<OMPDeclareMapperDecl>(DC))
6425     return VD->hasExternalStorage();
6426   if (DC->isFileContext())
6427     return true;
6428   if (DC->isRecord())
6429     return false;
6430   llvm_unreachable("Unexpected context");
6431 }
6432 
6433 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6434   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6435   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6436       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6437     return true;
6438   if (DC->isRecord())
6439     return false;
6440   llvm_unreachable("Unexpected context");
6441 }
6442 
6443 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6444                           ParsedAttr::Kind Kind) {
6445   // Check decl attributes on the DeclSpec.
6446   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6447     return true;
6448 
6449   // Walk the declarator structure, checking decl attributes that were in a type
6450   // position to the decl itself.
6451   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6452     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6453       return true;
6454   }
6455 
6456   // Finally, check attributes on the decl itself.
6457   return PD.getAttributes().hasAttribute(Kind);
6458 }
6459 
6460 /// Adjust the \c DeclContext for a function or variable that might be a
6461 /// function-local external declaration.
6462 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6463   if (!DC->isFunctionOrMethod())
6464     return false;
6465 
6466   // If this is a local extern function or variable declared within a function
6467   // template, don't add it into the enclosing namespace scope until it is
6468   // instantiated; it might have a dependent type right now.
6469   if (DC->isDependentContext())
6470     return true;
6471 
6472   // C++11 [basic.link]p7:
6473   //   When a block scope declaration of an entity with linkage is not found to
6474   //   refer to some other declaration, then that entity is a member of the
6475   //   innermost enclosing namespace.
6476   //
6477   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6478   // semantically-enclosing namespace, not a lexically-enclosing one.
6479   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6480     DC = DC->getParent();
6481   return true;
6482 }
6483 
6484 /// Returns true if given declaration has external C language linkage.
6485 static bool isDeclExternC(const Decl *D) {
6486   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6487     return FD->isExternC();
6488   if (const auto *VD = dyn_cast<VarDecl>(D))
6489     return VD->isExternC();
6490 
6491   llvm_unreachable("Unknown type of decl!");
6492 }
6493 /// Returns true if there hasn't been any invalid type diagnosed.
6494 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6495                                 DeclContext *DC, QualType R) {
6496   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6497   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6498   // argument.
6499   if (R->isImageType() || R->isPipeType()) {
6500     Se.Diag(D.getIdentifierLoc(),
6501             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6502         << R;
6503     D.setInvalidType();
6504     return false;
6505   }
6506 
6507   // OpenCL v1.2 s6.9.r:
6508   // The event type cannot be used to declare a program scope variable.
6509   // OpenCL v2.0 s6.9.q:
6510   // The clk_event_t and reserve_id_t types cannot be declared in program
6511   // scope.
6512   if (NULL == S->getParent()) {
6513     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6514       Se.Diag(D.getIdentifierLoc(),
6515               diag::err_invalid_type_for_program_scope_var)
6516           << R;
6517       D.setInvalidType();
6518       return false;
6519     }
6520   }
6521 
6522   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6523   QualType NR = R;
6524   while (NR->isPointerType()) {
6525     if (NR->isFunctionPointerType()) {
6526       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6527       D.setInvalidType();
6528       return false;
6529     }
6530     NR = NR->getPointeeType();
6531   }
6532 
6533   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6534     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6535     // half array type (unless the cl_khr_fp16 extension is enabled).
6536     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6537       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6538       D.setInvalidType();
6539       return false;
6540     }
6541   }
6542 
6543   // OpenCL v1.2 s6.9.r:
6544   // The event type cannot be used with the __local, __constant and __global
6545   // address space qualifiers.
6546   if (R->isEventT()) {
6547     if (R.getAddressSpace() != LangAS::opencl_private) {
6548       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6549       D.setInvalidType();
6550       return false;
6551     }
6552   }
6553 
6554   // C++ for OpenCL does not allow the thread_local storage qualifier.
6555   // OpenCL C does not support thread_local either, and
6556   // also reject all other thread storage class specifiers.
6557   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6558   if (TSC != TSCS_unspecified) {
6559     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6560     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6561             diag::err_opencl_unknown_type_specifier)
6562         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6563         << DeclSpec::getSpecifierName(TSC) << 1;
6564     D.setInvalidType();
6565     return false;
6566   }
6567 
6568   if (R->isSamplerT()) {
6569     // OpenCL v1.2 s6.9.b p4:
6570     // The sampler type cannot be used with the __local and __global address
6571     // space qualifiers.
6572     if (R.getAddressSpace() == LangAS::opencl_local ||
6573         R.getAddressSpace() == LangAS::opencl_global) {
6574       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6575       D.setInvalidType();
6576     }
6577 
6578     // OpenCL v1.2 s6.12.14.1:
6579     // A global sampler must be declared with either the constant address
6580     // space qualifier or with the const qualifier.
6581     if (DC->isTranslationUnit() &&
6582         !(R.getAddressSpace() == LangAS::opencl_constant ||
6583           R.isConstQualified())) {
6584       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6585       D.setInvalidType();
6586     }
6587     if (D.isInvalidType())
6588       return false;
6589   }
6590   return true;
6591 }
6592 
6593 NamedDecl *Sema::ActOnVariableDeclarator(
6594     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6595     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6596     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6597   QualType R = TInfo->getType();
6598   DeclarationName Name = GetNameForDeclarator(D).getName();
6599 
6600   IdentifierInfo *II = Name.getAsIdentifierInfo();
6601 
6602   if (D.isDecompositionDeclarator()) {
6603     // Take the name of the first declarator as our name for diagnostic
6604     // purposes.
6605     auto &Decomp = D.getDecompositionDeclarator();
6606     if (!Decomp.bindings().empty()) {
6607       II = Decomp.bindings()[0].Name;
6608       Name = II;
6609     }
6610   } else if (!II) {
6611     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6612     return nullptr;
6613   }
6614 
6615 
6616   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6617   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6618 
6619   // dllimport globals without explicit storage class are treated as extern. We
6620   // have to change the storage class this early to get the right DeclContext.
6621   if (SC == SC_None && !DC->isRecord() &&
6622       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6623       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6624     SC = SC_Extern;
6625 
6626   DeclContext *OriginalDC = DC;
6627   bool IsLocalExternDecl = SC == SC_Extern &&
6628                            adjustContextForLocalExternDecl(DC);
6629 
6630   if (SCSpec == DeclSpec::SCS_mutable) {
6631     // mutable can only appear on non-static class members, so it's always
6632     // an error here
6633     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6634     D.setInvalidType();
6635     SC = SC_None;
6636   }
6637 
6638   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6639       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6640                               D.getDeclSpec().getStorageClassSpecLoc())) {
6641     // In C++11, the 'register' storage class specifier is deprecated.
6642     // Suppress the warning in system macros, it's used in macros in some
6643     // popular C system headers, such as in glibc's htonl() macro.
6644     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6645          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6646                                    : diag::warn_deprecated_register)
6647       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6648   }
6649 
6650   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6651 
6652   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6653     // C99 6.9p2: The storage-class specifiers auto and register shall not
6654     // appear in the declaration specifiers in an external declaration.
6655     // Global Register+Asm is a GNU extension we support.
6656     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6657       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6658       D.setInvalidType();
6659     }
6660   }
6661 
6662   bool IsMemberSpecialization = false;
6663   bool IsVariableTemplateSpecialization = false;
6664   bool IsPartialSpecialization = false;
6665   bool IsVariableTemplate = false;
6666   VarDecl *NewVD = nullptr;
6667   VarTemplateDecl *NewTemplate = nullptr;
6668   TemplateParameterList *TemplateParams = nullptr;
6669   if (!getLangOpts().CPlusPlus) {
6670     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6671                             II, R, TInfo, SC);
6672 
6673     if (R->getContainedDeducedType())
6674       ParsingInitForAutoVars.insert(NewVD);
6675 
6676     if (D.isInvalidType())
6677       NewVD->setInvalidDecl();
6678 
6679     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6680         NewVD->hasLocalStorage())
6681       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6682                             NTCUC_AutoVar, NTCUK_Destruct);
6683   } else {
6684     bool Invalid = false;
6685 
6686     if (DC->isRecord() && !CurContext->isRecord()) {
6687       // This is an out-of-line definition of a static data member.
6688       switch (SC) {
6689       case SC_None:
6690         break;
6691       case SC_Static:
6692         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6693              diag::err_static_out_of_line)
6694           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6695         break;
6696       case SC_Auto:
6697       case SC_Register:
6698       case SC_Extern:
6699         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6700         // to names of variables declared in a block or to function parameters.
6701         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6702         // of class members
6703 
6704         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6705              diag::err_storage_class_for_static_member)
6706           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6707         break;
6708       case SC_PrivateExtern:
6709         llvm_unreachable("C storage class in c++!");
6710       }
6711     }
6712 
6713     if (SC == SC_Static && CurContext->isRecord()) {
6714       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6715         if (RD->isLocalClass())
6716           Diag(D.getIdentifierLoc(),
6717                diag::err_static_data_member_not_allowed_in_local_class)
6718             << Name << RD->getDeclName();
6719 
6720         // C++98 [class.union]p1: If a union contains a static data member,
6721         // the program is ill-formed. C++11 drops this restriction.
6722         if (RD->isUnion())
6723           Diag(D.getIdentifierLoc(),
6724                getLangOpts().CPlusPlus11
6725                  ? diag::warn_cxx98_compat_static_data_member_in_union
6726                  : diag::ext_static_data_member_in_union) << Name;
6727         // We conservatively disallow static data members in anonymous structs.
6728         else if (!RD->getDeclName())
6729           Diag(D.getIdentifierLoc(),
6730                diag::err_static_data_member_not_allowed_in_anon_struct)
6731             << Name << RD->isUnion();
6732       }
6733     }
6734 
6735     // Match up the template parameter lists with the scope specifier, then
6736     // determine whether we have a template or a template specialization.
6737     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6738         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6739         D.getCXXScopeSpec(),
6740         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6741             ? D.getName().TemplateId
6742             : nullptr,
6743         TemplateParamLists,
6744         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6745 
6746     if (TemplateParams) {
6747       if (!TemplateParams->size() &&
6748           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6749         // There is an extraneous 'template<>' for this variable. Complain
6750         // about it, but allow the declaration of the variable.
6751         Diag(TemplateParams->getTemplateLoc(),
6752              diag::err_template_variable_noparams)
6753           << II
6754           << SourceRange(TemplateParams->getTemplateLoc(),
6755                          TemplateParams->getRAngleLoc());
6756         TemplateParams = nullptr;
6757       } else {
6758         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6759           // This is an explicit specialization or a partial specialization.
6760           // FIXME: Check that we can declare a specialization here.
6761           IsVariableTemplateSpecialization = true;
6762           IsPartialSpecialization = TemplateParams->size() > 0;
6763         } else { // if (TemplateParams->size() > 0)
6764           // This is a template declaration.
6765           IsVariableTemplate = true;
6766 
6767           // Check that we can declare a template here.
6768           if (CheckTemplateDeclScope(S, TemplateParams))
6769             return nullptr;
6770 
6771           // Only C++1y supports variable templates (N3651).
6772           Diag(D.getIdentifierLoc(),
6773                getLangOpts().CPlusPlus14
6774                    ? diag::warn_cxx11_compat_variable_template
6775                    : diag::ext_variable_template);
6776         }
6777       }
6778     } else {
6779       assert((Invalid ||
6780               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6781              "should have a 'template<>' for this decl");
6782     }
6783 
6784     if (IsVariableTemplateSpecialization) {
6785       SourceLocation TemplateKWLoc =
6786           TemplateParamLists.size() > 0
6787               ? TemplateParamLists[0]->getTemplateLoc()
6788               : SourceLocation();
6789       DeclResult Res = ActOnVarTemplateSpecialization(
6790           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6791           IsPartialSpecialization);
6792       if (Res.isInvalid())
6793         return nullptr;
6794       NewVD = cast<VarDecl>(Res.get());
6795       AddToScope = false;
6796     } else if (D.isDecompositionDeclarator()) {
6797       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6798                                         D.getIdentifierLoc(), R, TInfo, SC,
6799                                         Bindings);
6800     } else
6801       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6802                               D.getIdentifierLoc(), II, R, TInfo, SC);
6803 
6804     // If this is supposed to be a variable template, create it as such.
6805     if (IsVariableTemplate) {
6806       NewTemplate =
6807           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6808                                   TemplateParams, NewVD);
6809       NewVD->setDescribedVarTemplate(NewTemplate);
6810     }
6811 
6812     // If this decl has an auto type in need of deduction, make a note of the
6813     // Decl so we can diagnose uses of it in its own initializer.
6814     if (R->getContainedDeducedType())
6815       ParsingInitForAutoVars.insert(NewVD);
6816 
6817     if (D.isInvalidType() || Invalid) {
6818       NewVD->setInvalidDecl();
6819       if (NewTemplate)
6820         NewTemplate->setInvalidDecl();
6821     }
6822 
6823     SetNestedNameSpecifier(*this, NewVD, D);
6824 
6825     // If we have any template parameter lists that don't directly belong to
6826     // the variable (matching the scope specifier), store them.
6827     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6828     if (TemplateParamLists.size() > VDTemplateParamLists)
6829       NewVD->setTemplateParameterListsInfo(
6830           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6831   }
6832 
6833   if (D.getDeclSpec().isInlineSpecified()) {
6834     if (!getLangOpts().CPlusPlus) {
6835       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6836           << 0;
6837     } else if (CurContext->isFunctionOrMethod()) {
6838       // 'inline' is not allowed on block scope variable declaration.
6839       Diag(D.getDeclSpec().getInlineSpecLoc(),
6840            diag::err_inline_declaration_block_scope) << Name
6841         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6842     } else {
6843       Diag(D.getDeclSpec().getInlineSpecLoc(),
6844            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6845                                      : diag::ext_inline_variable);
6846       NewVD->setInlineSpecified();
6847     }
6848   }
6849 
6850   // Set the lexical context. If the declarator has a C++ scope specifier, the
6851   // lexical context will be different from the semantic context.
6852   NewVD->setLexicalDeclContext(CurContext);
6853   if (NewTemplate)
6854     NewTemplate->setLexicalDeclContext(CurContext);
6855 
6856   if (IsLocalExternDecl) {
6857     if (D.isDecompositionDeclarator())
6858       for (auto *B : Bindings)
6859         B->setLocalExternDecl();
6860     else
6861       NewVD->setLocalExternDecl();
6862   }
6863 
6864   bool EmitTLSUnsupportedError = false;
6865   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6866     // C++11 [dcl.stc]p4:
6867     //   When thread_local is applied to a variable of block scope the
6868     //   storage-class-specifier static is implied if it does not appear
6869     //   explicitly.
6870     // Core issue: 'static' is not implied if the variable is declared
6871     //   'extern'.
6872     if (NewVD->hasLocalStorage() &&
6873         (SCSpec != DeclSpec::SCS_unspecified ||
6874          TSCS != DeclSpec::TSCS_thread_local ||
6875          !DC->isFunctionOrMethod()))
6876       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6877            diag::err_thread_non_global)
6878         << DeclSpec::getSpecifierName(TSCS);
6879     else if (!Context.getTargetInfo().isTLSSupported()) {
6880       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6881         // Postpone error emission until we've collected attributes required to
6882         // figure out whether it's a host or device variable and whether the
6883         // error should be ignored.
6884         EmitTLSUnsupportedError = true;
6885         // We still need to mark the variable as TLS so it shows up in AST with
6886         // proper storage class for other tools to use even if we're not going
6887         // to emit any code for it.
6888         NewVD->setTSCSpec(TSCS);
6889       } else
6890         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6891              diag::err_thread_unsupported);
6892     } else
6893       NewVD->setTSCSpec(TSCS);
6894   }
6895 
6896   switch (D.getDeclSpec().getConstexprSpecifier()) {
6897   case CSK_unspecified:
6898     break;
6899 
6900   case CSK_consteval:
6901     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6902         diag::err_constexpr_wrong_decl_kind)
6903       << D.getDeclSpec().getConstexprSpecifier();
6904     LLVM_FALLTHROUGH;
6905 
6906   case CSK_constexpr:
6907     NewVD->setConstexpr(true);
6908     // C++1z [dcl.spec.constexpr]p1:
6909     //   A static data member declared with the constexpr specifier is
6910     //   implicitly an inline variable.
6911     if (NewVD->isStaticDataMember() &&
6912         (getLangOpts().CPlusPlus17 ||
6913          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6914       NewVD->setImplicitlyInline();
6915     break;
6916 
6917   case CSK_constinit:
6918     if (!NewVD->hasGlobalStorage())
6919       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6920            diag::err_constinit_local_variable);
6921     else
6922       NewVD->addAttr(ConstInitAttr::Create(
6923           Context, D.getDeclSpec().getConstexprSpecLoc(),
6924           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6925     break;
6926   }
6927 
6928   // C99 6.7.4p3
6929   //   An inline definition of a function with external linkage shall
6930   //   not contain a definition of a modifiable object with static or
6931   //   thread storage duration...
6932   // We only apply this when the function is required to be defined
6933   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6934   // that a local variable with thread storage duration still has to
6935   // be marked 'static'.  Also note that it's possible to get these
6936   // semantics in C++ using __attribute__((gnu_inline)).
6937   if (SC == SC_Static && S->getFnParent() != nullptr &&
6938       !NewVD->getType().isConstQualified()) {
6939     FunctionDecl *CurFD = getCurFunctionDecl();
6940     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6941       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6942            diag::warn_static_local_in_extern_inline);
6943       MaybeSuggestAddingStaticToDecl(CurFD);
6944     }
6945   }
6946 
6947   if (D.getDeclSpec().isModulePrivateSpecified()) {
6948     if (IsVariableTemplateSpecialization)
6949       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6950           << (IsPartialSpecialization ? 1 : 0)
6951           << FixItHint::CreateRemoval(
6952                  D.getDeclSpec().getModulePrivateSpecLoc());
6953     else if (IsMemberSpecialization)
6954       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6955         << 2
6956         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6957     else if (NewVD->hasLocalStorage())
6958       Diag(NewVD->getLocation(), diag::err_module_private_local)
6959         << 0 << NewVD->getDeclName()
6960         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6961         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6962     else {
6963       NewVD->setModulePrivate();
6964       if (NewTemplate)
6965         NewTemplate->setModulePrivate();
6966       for (auto *B : Bindings)
6967         B->setModulePrivate();
6968     }
6969   }
6970 
6971   if (getLangOpts().OpenCL) {
6972 
6973     deduceOpenCLAddressSpace(NewVD);
6974 
6975     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
6976   }
6977 
6978   // Handle attributes prior to checking for duplicates in MergeVarDecl
6979   ProcessDeclAttributes(S, NewVD, D);
6980 
6981   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6982     if (EmitTLSUnsupportedError &&
6983         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6984          (getLangOpts().OpenMPIsDevice &&
6985           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
6986       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6987            diag::err_thread_unsupported);
6988     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6989     // storage [duration]."
6990     if (SC == SC_None && S->getFnParent() != nullptr &&
6991         (NewVD->hasAttr<CUDASharedAttr>() ||
6992          NewVD->hasAttr<CUDAConstantAttr>())) {
6993       NewVD->setStorageClass(SC_Static);
6994     }
6995   }
6996 
6997   // Ensure that dllimport globals without explicit storage class are treated as
6998   // extern. The storage class is set above using parsed attributes. Now we can
6999   // check the VarDecl itself.
7000   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7001          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7002          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7003 
7004   // In auto-retain/release, infer strong retension for variables of
7005   // retainable type.
7006   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7007     NewVD->setInvalidDecl();
7008 
7009   // Handle GNU asm-label extension (encoded as an attribute).
7010   if (Expr *E = (Expr*)D.getAsmLabel()) {
7011     // The parser guarantees this is a string.
7012     StringLiteral *SE = cast<StringLiteral>(E);
7013     StringRef Label = SE->getString();
7014     if (S->getFnParent() != nullptr) {
7015       switch (SC) {
7016       case SC_None:
7017       case SC_Auto:
7018         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7019         break;
7020       case SC_Register:
7021         // Local Named register
7022         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7023             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7024           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7025         break;
7026       case SC_Static:
7027       case SC_Extern:
7028       case SC_PrivateExtern:
7029         break;
7030       }
7031     } else if (SC == SC_Register) {
7032       // Global Named register
7033       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7034         const auto &TI = Context.getTargetInfo();
7035         bool HasSizeMismatch;
7036 
7037         if (!TI.isValidGCCRegisterName(Label))
7038           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7039         else if (!TI.validateGlobalRegisterVariable(Label,
7040                                                     Context.getTypeSize(R),
7041                                                     HasSizeMismatch))
7042           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7043         else if (HasSizeMismatch)
7044           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7045         else if (!TI.isRegisterReservedGlobally(Label))
7046           Diag(E->getExprLoc(), diag::err_asm_missing_fixed_reg_opt) << Label;
7047       }
7048 
7049       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7050         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7051         NewVD->setInvalidDecl(true);
7052       }
7053     }
7054 
7055     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7056                                         /*IsLiteralLabel=*/true,
7057                                         SE->getStrTokenLoc(0)));
7058   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7059     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7060       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7061     if (I != ExtnameUndeclaredIdentifiers.end()) {
7062       if (isDeclExternC(NewVD)) {
7063         NewVD->addAttr(I->second);
7064         ExtnameUndeclaredIdentifiers.erase(I);
7065       } else
7066         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7067             << /*Variable*/1 << NewVD;
7068     }
7069   }
7070 
7071   // Find the shadowed declaration before filtering for scope.
7072   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7073                                 ? getShadowedDeclaration(NewVD, Previous)
7074                                 : nullptr;
7075 
7076   // Don't consider existing declarations that are in a different
7077   // scope and are out-of-semantic-context declarations (if the new
7078   // declaration has linkage).
7079   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7080                        D.getCXXScopeSpec().isNotEmpty() ||
7081                        IsMemberSpecialization ||
7082                        IsVariableTemplateSpecialization);
7083 
7084   // Check whether the previous declaration is in the same block scope. This
7085   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7086   if (getLangOpts().CPlusPlus &&
7087       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7088     NewVD->setPreviousDeclInSameBlockScope(
7089         Previous.isSingleResult() && !Previous.isShadowed() &&
7090         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7091 
7092   if (!getLangOpts().CPlusPlus) {
7093     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7094   } else {
7095     // If this is an explicit specialization of a static data member, check it.
7096     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7097         CheckMemberSpecialization(NewVD, Previous))
7098       NewVD->setInvalidDecl();
7099 
7100     // Merge the decl with the existing one if appropriate.
7101     if (!Previous.empty()) {
7102       if (Previous.isSingleResult() &&
7103           isa<FieldDecl>(Previous.getFoundDecl()) &&
7104           D.getCXXScopeSpec().isSet()) {
7105         // The user tried to define a non-static data member
7106         // out-of-line (C++ [dcl.meaning]p1).
7107         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7108           << D.getCXXScopeSpec().getRange();
7109         Previous.clear();
7110         NewVD->setInvalidDecl();
7111       }
7112     } else if (D.getCXXScopeSpec().isSet()) {
7113       // No previous declaration in the qualifying scope.
7114       Diag(D.getIdentifierLoc(), diag::err_no_member)
7115         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7116         << D.getCXXScopeSpec().getRange();
7117       NewVD->setInvalidDecl();
7118     }
7119 
7120     if (!IsVariableTemplateSpecialization)
7121       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7122 
7123     if (NewTemplate) {
7124       VarTemplateDecl *PrevVarTemplate =
7125           NewVD->getPreviousDecl()
7126               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7127               : nullptr;
7128 
7129       // Check the template parameter list of this declaration, possibly
7130       // merging in the template parameter list from the previous variable
7131       // template declaration.
7132       if (CheckTemplateParameterList(
7133               TemplateParams,
7134               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7135                               : nullptr,
7136               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7137                DC->isDependentContext())
7138                   ? TPC_ClassTemplateMember
7139                   : TPC_VarTemplate))
7140         NewVD->setInvalidDecl();
7141 
7142       // If we are providing an explicit specialization of a static variable
7143       // template, make a note of that.
7144       if (PrevVarTemplate &&
7145           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7146         PrevVarTemplate->setMemberSpecialization();
7147     }
7148   }
7149 
7150   // Diagnose shadowed variables iff this isn't a redeclaration.
7151   if (ShadowedDecl && !D.isRedeclaration())
7152     CheckShadow(NewVD, ShadowedDecl, Previous);
7153 
7154   ProcessPragmaWeak(S, NewVD);
7155 
7156   // If this is the first declaration of an extern C variable, update
7157   // the map of such variables.
7158   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7159       isIncompleteDeclExternC(*this, NewVD))
7160     RegisterLocallyScopedExternCDecl(NewVD, S);
7161 
7162   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7163     MangleNumberingContext *MCtx;
7164     Decl *ManglingContextDecl;
7165     std::tie(MCtx, ManglingContextDecl) =
7166         getCurrentMangleNumberContext(NewVD->getDeclContext());
7167     if (MCtx) {
7168       Context.setManglingNumber(
7169           NewVD, MCtx->getManglingNumber(
7170                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7171       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7172     }
7173   }
7174 
7175   // Special handling of variable named 'main'.
7176   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7177       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7178       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7179 
7180     // C++ [basic.start.main]p3
7181     // A program that declares a variable main at global scope is ill-formed.
7182     if (getLangOpts().CPlusPlus)
7183       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7184 
7185     // In C, and external-linkage variable named main results in undefined
7186     // behavior.
7187     else if (NewVD->hasExternalFormalLinkage())
7188       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7189   }
7190 
7191   if (D.isRedeclaration() && !Previous.empty()) {
7192     NamedDecl *Prev = Previous.getRepresentativeDecl();
7193     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7194                                    D.isFunctionDefinition());
7195   }
7196 
7197   if (NewTemplate) {
7198     if (NewVD->isInvalidDecl())
7199       NewTemplate->setInvalidDecl();
7200     ActOnDocumentableDecl(NewTemplate);
7201     return NewTemplate;
7202   }
7203 
7204   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7205     CompleteMemberSpecialization(NewVD, Previous);
7206 
7207   return NewVD;
7208 }
7209 
7210 /// Enum describing the %select options in diag::warn_decl_shadow.
7211 enum ShadowedDeclKind {
7212   SDK_Local,
7213   SDK_Global,
7214   SDK_StaticMember,
7215   SDK_Field,
7216   SDK_Typedef,
7217   SDK_Using
7218 };
7219 
7220 /// Determine what kind of declaration we're shadowing.
7221 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7222                                                 const DeclContext *OldDC) {
7223   if (isa<TypeAliasDecl>(ShadowedDecl))
7224     return SDK_Using;
7225   else if (isa<TypedefDecl>(ShadowedDecl))
7226     return SDK_Typedef;
7227   else if (isa<RecordDecl>(OldDC))
7228     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7229 
7230   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7231 }
7232 
7233 /// Return the location of the capture if the given lambda captures the given
7234 /// variable \p VD, or an invalid source location otherwise.
7235 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7236                                          const VarDecl *VD) {
7237   for (const Capture &Capture : LSI->Captures) {
7238     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7239       return Capture.getLocation();
7240   }
7241   return SourceLocation();
7242 }
7243 
7244 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7245                                      const LookupResult &R) {
7246   // Only diagnose if we're shadowing an unambiguous field or variable.
7247   if (R.getResultKind() != LookupResult::Found)
7248     return false;
7249 
7250   // Return false if warning is ignored.
7251   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7252 }
7253 
7254 /// Return the declaration shadowed by the given variable \p D, or null
7255 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7256 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7257                                         const LookupResult &R) {
7258   if (!shouldWarnIfShadowedDecl(Diags, R))
7259     return nullptr;
7260 
7261   // Don't diagnose declarations at file scope.
7262   if (D->hasGlobalStorage())
7263     return nullptr;
7264 
7265   NamedDecl *ShadowedDecl = R.getFoundDecl();
7266   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7267              ? ShadowedDecl
7268              : nullptr;
7269 }
7270 
7271 /// Return the declaration shadowed by the given typedef \p D, or null
7272 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7273 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7274                                         const LookupResult &R) {
7275   // Don't warn if typedef declaration is part of a class
7276   if (D->getDeclContext()->isRecord())
7277     return nullptr;
7278 
7279   if (!shouldWarnIfShadowedDecl(Diags, R))
7280     return nullptr;
7281 
7282   NamedDecl *ShadowedDecl = R.getFoundDecl();
7283   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7284 }
7285 
7286 /// Diagnose variable or built-in function shadowing.  Implements
7287 /// -Wshadow.
7288 ///
7289 /// This method is called whenever a VarDecl is added to a "useful"
7290 /// scope.
7291 ///
7292 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7293 /// \param R the lookup of the name
7294 ///
7295 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7296                        const LookupResult &R) {
7297   DeclContext *NewDC = D->getDeclContext();
7298 
7299   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7300     // Fields are not shadowed by variables in C++ static methods.
7301     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7302       if (MD->isStatic())
7303         return;
7304 
7305     // Fields shadowed by constructor parameters are a special case. Usually
7306     // the constructor initializes the field with the parameter.
7307     if (isa<CXXConstructorDecl>(NewDC))
7308       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7309         // Remember that this was shadowed so we can either warn about its
7310         // modification or its existence depending on warning settings.
7311         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7312         return;
7313       }
7314   }
7315 
7316   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7317     if (shadowedVar->isExternC()) {
7318       // For shadowing external vars, make sure that we point to the global
7319       // declaration, not a locally scoped extern declaration.
7320       for (auto I : shadowedVar->redecls())
7321         if (I->isFileVarDecl()) {
7322           ShadowedDecl = I;
7323           break;
7324         }
7325     }
7326 
7327   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7328 
7329   unsigned WarningDiag = diag::warn_decl_shadow;
7330   SourceLocation CaptureLoc;
7331   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7332       isa<CXXMethodDecl>(NewDC)) {
7333     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7334       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7335         if (RD->getLambdaCaptureDefault() == LCD_None) {
7336           // Try to avoid warnings for lambdas with an explicit capture list.
7337           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7338           // Warn only when the lambda captures the shadowed decl explicitly.
7339           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7340           if (CaptureLoc.isInvalid())
7341             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7342         } else {
7343           // Remember that this was shadowed so we can avoid the warning if the
7344           // shadowed decl isn't captured and the warning settings allow it.
7345           cast<LambdaScopeInfo>(getCurFunction())
7346               ->ShadowingDecls.push_back(
7347                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7348           return;
7349         }
7350       }
7351 
7352       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7353         // A variable can't shadow a local variable in an enclosing scope, if
7354         // they are separated by a non-capturing declaration context.
7355         for (DeclContext *ParentDC = NewDC;
7356              ParentDC && !ParentDC->Equals(OldDC);
7357              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7358           // Only block literals, captured statements, and lambda expressions
7359           // can capture; other scopes don't.
7360           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7361               !isLambdaCallOperator(ParentDC)) {
7362             return;
7363           }
7364         }
7365       }
7366     }
7367   }
7368 
7369   // Only warn about certain kinds of shadowing for class members.
7370   if (NewDC && NewDC->isRecord()) {
7371     // In particular, don't warn about shadowing non-class members.
7372     if (!OldDC->isRecord())
7373       return;
7374 
7375     // TODO: should we warn about static data members shadowing
7376     // static data members from base classes?
7377 
7378     // TODO: don't diagnose for inaccessible shadowed members.
7379     // This is hard to do perfectly because we might friend the
7380     // shadowing context, but that's just a false negative.
7381   }
7382 
7383 
7384   DeclarationName Name = R.getLookupName();
7385 
7386   // Emit warning and note.
7387   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7388     return;
7389   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7390   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7391   if (!CaptureLoc.isInvalid())
7392     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7393         << Name << /*explicitly*/ 1;
7394   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7395 }
7396 
7397 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7398 /// when these variables are captured by the lambda.
7399 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7400   for (const auto &Shadow : LSI->ShadowingDecls) {
7401     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7402     // Try to avoid the warning when the shadowed decl isn't captured.
7403     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7404     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7405     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7406                                        ? diag::warn_decl_shadow_uncaptured_local
7407                                        : diag::warn_decl_shadow)
7408         << Shadow.VD->getDeclName()
7409         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7410     if (!CaptureLoc.isInvalid())
7411       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7412           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7413     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7414   }
7415 }
7416 
7417 /// Check -Wshadow without the advantage of a previous lookup.
7418 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7419   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7420     return;
7421 
7422   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7423                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7424   LookupName(R, S);
7425   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7426     CheckShadow(D, ShadowedDecl, R);
7427 }
7428 
7429 /// Check if 'E', which is an expression that is about to be modified, refers
7430 /// to a constructor parameter that shadows a field.
7431 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7432   // Quickly ignore expressions that can't be shadowing ctor parameters.
7433   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7434     return;
7435   E = E->IgnoreParenImpCasts();
7436   auto *DRE = dyn_cast<DeclRefExpr>(E);
7437   if (!DRE)
7438     return;
7439   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7440   auto I = ShadowingDecls.find(D);
7441   if (I == ShadowingDecls.end())
7442     return;
7443   const NamedDecl *ShadowedDecl = I->second;
7444   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7445   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7446   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7447   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7448 
7449   // Avoid issuing multiple warnings about the same decl.
7450   ShadowingDecls.erase(I);
7451 }
7452 
7453 /// Check for conflict between this global or extern "C" declaration and
7454 /// previous global or extern "C" declarations. This is only used in C++.
7455 template<typename T>
7456 static bool checkGlobalOrExternCConflict(
7457     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7458   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7459   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7460 
7461   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7462     // The common case: this global doesn't conflict with any extern "C"
7463     // declaration.
7464     return false;
7465   }
7466 
7467   if (Prev) {
7468     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7469       // Both the old and new declarations have C language linkage. This is a
7470       // redeclaration.
7471       Previous.clear();
7472       Previous.addDecl(Prev);
7473       return true;
7474     }
7475 
7476     // This is a global, non-extern "C" declaration, and there is a previous
7477     // non-global extern "C" declaration. Diagnose if this is a variable
7478     // declaration.
7479     if (!isa<VarDecl>(ND))
7480       return false;
7481   } else {
7482     // The declaration is extern "C". Check for any declaration in the
7483     // translation unit which might conflict.
7484     if (IsGlobal) {
7485       // We have already performed the lookup into the translation unit.
7486       IsGlobal = false;
7487       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7488            I != E; ++I) {
7489         if (isa<VarDecl>(*I)) {
7490           Prev = *I;
7491           break;
7492         }
7493       }
7494     } else {
7495       DeclContext::lookup_result R =
7496           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7497       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7498            I != E; ++I) {
7499         if (isa<VarDecl>(*I)) {
7500           Prev = *I;
7501           break;
7502         }
7503         // FIXME: If we have any other entity with this name in global scope,
7504         // the declaration is ill-formed, but that is a defect: it breaks the
7505         // 'stat' hack, for instance. Only variables can have mangled name
7506         // clashes with extern "C" declarations, so only they deserve a
7507         // diagnostic.
7508       }
7509     }
7510 
7511     if (!Prev)
7512       return false;
7513   }
7514 
7515   // Use the first declaration's location to ensure we point at something which
7516   // is lexically inside an extern "C" linkage-spec.
7517   assert(Prev && "should have found a previous declaration to diagnose");
7518   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7519     Prev = FD->getFirstDecl();
7520   else
7521     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7522 
7523   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7524     << IsGlobal << ND;
7525   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7526     << IsGlobal;
7527   return false;
7528 }
7529 
7530 /// Apply special rules for handling extern "C" declarations. Returns \c true
7531 /// if we have found that this is a redeclaration of some prior entity.
7532 ///
7533 /// Per C++ [dcl.link]p6:
7534 ///   Two declarations [for a function or variable] with C language linkage
7535 ///   with the same name that appear in different scopes refer to the same
7536 ///   [entity]. An entity with C language linkage shall not be declared with
7537 ///   the same name as an entity in global scope.
7538 template<typename T>
7539 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7540                                                   LookupResult &Previous) {
7541   if (!S.getLangOpts().CPlusPlus) {
7542     // In C, when declaring a global variable, look for a corresponding 'extern'
7543     // variable declared in function scope. We don't need this in C++, because
7544     // we find local extern decls in the surrounding file-scope DeclContext.
7545     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7546       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7547         Previous.clear();
7548         Previous.addDecl(Prev);
7549         return true;
7550       }
7551     }
7552     return false;
7553   }
7554 
7555   // A declaration in the translation unit can conflict with an extern "C"
7556   // declaration.
7557   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7558     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7559 
7560   // An extern "C" declaration can conflict with a declaration in the
7561   // translation unit or can be a redeclaration of an extern "C" declaration
7562   // in another scope.
7563   if (isIncompleteDeclExternC(S,ND))
7564     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7565 
7566   // Neither global nor extern "C": nothing to do.
7567   return false;
7568 }
7569 
7570 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7571   // If the decl is already known invalid, don't check it.
7572   if (NewVD->isInvalidDecl())
7573     return;
7574 
7575   QualType T = NewVD->getType();
7576 
7577   // Defer checking an 'auto' type until its initializer is attached.
7578   if (T->isUndeducedType())
7579     return;
7580 
7581   if (NewVD->hasAttrs())
7582     CheckAlignasUnderalignment(NewVD);
7583 
7584   if (T->isObjCObjectType()) {
7585     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7586       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7587     T = Context.getObjCObjectPointerType(T);
7588     NewVD->setType(T);
7589   }
7590 
7591   // Emit an error if an address space was applied to decl with local storage.
7592   // This includes arrays of objects with address space qualifiers, but not
7593   // automatic variables that point to other address spaces.
7594   // ISO/IEC TR 18037 S5.1.2
7595   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7596       T.getAddressSpace() != LangAS::Default) {
7597     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7598     NewVD->setInvalidDecl();
7599     return;
7600   }
7601 
7602   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7603   // scope.
7604   if (getLangOpts().OpenCLVersion == 120 &&
7605       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7606       NewVD->isStaticLocal()) {
7607     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7608     NewVD->setInvalidDecl();
7609     return;
7610   }
7611 
7612   if (getLangOpts().OpenCL) {
7613     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7614     if (NewVD->hasAttr<BlocksAttr>()) {
7615       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7616       return;
7617     }
7618 
7619     if (T->isBlockPointerType()) {
7620       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7621       // can't use 'extern' storage class.
7622       if (!T.isConstQualified()) {
7623         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7624             << 0 /*const*/;
7625         NewVD->setInvalidDecl();
7626         return;
7627       }
7628       if (NewVD->hasExternalStorage()) {
7629         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7630         NewVD->setInvalidDecl();
7631         return;
7632       }
7633     }
7634     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7635     // __constant address space.
7636     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7637     // variables inside a function can also be declared in the global
7638     // address space.
7639     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7640     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7641     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7642         NewVD->hasExternalStorage()) {
7643       if (!T->isSamplerT() &&
7644           !(T.getAddressSpace() == LangAS::opencl_constant ||
7645             (T.getAddressSpace() == LangAS::opencl_global &&
7646              (getLangOpts().OpenCLVersion == 200 ||
7647               getLangOpts().OpenCLCPlusPlus)))) {
7648         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7649         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7650           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7651               << Scope << "global or constant";
7652         else
7653           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7654               << Scope << "constant";
7655         NewVD->setInvalidDecl();
7656         return;
7657       }
7658     } else {
7659       if (T.getAddressSpace() == LangAS::opencl_global) {
7660         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7661             << 1 /*is any function*/ << "global";
7662         NewVD->setInvalidDecl();
7663         return;
7664       }
7665       if (T.getAddressSpace() == LangAS::opencl_constant ||
7666           T.getAddressSpace() == LangAS::opencl_local) {
7667         FunctionDecl *FD = getCurFunctionDecl();
7668         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7669         // in functions.
7670         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7671           if (T.getAddressSpace() == LangAS::opencl_constant)
7672             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7673                 << 0 /*non-kernel only*/ << "constant";
7674           else
7675             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7676                 << 0 /*non-kernel only*/ << "local";
7677           NewVD->setInvalidDecl();
7678           return;
7679         }
7680         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7681         // in the outermost scope of a kernel function.
7682         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7683           if (!getCurScope()->isFunctionScope()) {
7684             if (T.getAddressSpace() == LangAS::opencl_constant)
7685               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7686                   << "constant";
7687             else
7688               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7689                   << "local";
7690             NewVD->setInvalidDecl();
7691             return;
7692           }
7693         }
7694       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7695                  // If we are parsing a template we didn't deduce an addr
7696                  // space yet.
7697                  T.getAddressSpace() != LangAS::Default) {
7698         // Do not allow other address spaces on automatic variable.
7699         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7700         NewVD->setInvalidDecl();
7701         return;
7702       }
7703     }
7704   }
7705 
7706   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7707       && !NewVD->hasAttr<BlocksAttr>()) {
7708     if (getLangOpts().getGC() != LangOptions::NonGC)
7709       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7710     else {
7711       assert(!getLangOpts().ObjCAutoRefCount);
7712       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7713     }
7714   }
7715 
7716   bool isVM = T->isVariablyModifiedType();
7717   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7718       NewVD->hasAttr<BlocksAttr>())
7719     setFunctionHasBranchProtectedScope();
7720 
7721   if ((isVM && NewVD->hasLinkage()) ||
7722       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7723     bool SizeIsNegative;
7724     llvm::APSInt Oversized;
7725     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7726         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7727     QualType FixedT;
7728     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7729       FixedT = FixedTInfo->getType();
7730     else if (FixedTInfo) {
7731       // Type and type-as-written are canonically different. We need to fix up
7732       // both types separately.
7733       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7734                                                    Oversized);
7735     }
7736     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7737       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7738       // FIXME: This won't give the correct result for
7739       // int a[10][n];
7740       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7741 
7742       if (NewVD->isFileVarDecl())
7743         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7744         << SizeRange;
7745       else if (NewVD->isStaticLocal())
7746         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7747         << SizeRange;
7748       else
7749         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7750         << SizeRange;
7751       NewVD->setInvalidDecl();
7752       return;
7753     }
7754 
7755     if (!FixedTInfo) {
7756       if (NewVD->isFileVarDecl())
7757         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7758       else
7759         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7760       NewVD->setInvalidDecl();
7761       return;
7762     }
7763 
7764     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7765     NewVD->setType(FixedT);
7766     NewVD->setTypeSourceInfo(FixedTInfo);
7767   }
7768 
7769   if (T->isVoidType()) {
7770     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7771     //                    of objects and functions.
7772     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7773       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7774         << T;
7775       NewVD->setInvalidDecl();
7776       return;
7777     }
7778   }
7779 
7780   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7781     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7782     NewVD->setInvalidDecl();
7783     return;
7784   }
7785 
7786   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7787     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7788     NewVD->setInvalidDecl();
7789     return;
7790   }
7791 
7792   if (NewVD->isConstexpr() && !T->isDependentType() &&
7793       RequireLiteralType(NewVD->getLocation(), T,
7794                          diag::err_constexpr_var_non_literal)) {
7795     NewVD->setInvalidDecl();
7796     return;
7797   }
7798 }
7799 
7800 /// Perform semantic checking on a newly-created variable
7801 /// declaration.
7802 ///
7803 /// This routine performs all of the type-checking required for a
7804 /// variable declaration once it has been built. It is used both to
7805 /// check variables after they have been parsed and their declarators
7806 /// have been translated into a declaration, and to check variables
7807 /// that have been instantiated from a template.
7808 ///
7809 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7810 ///
7811 /// Returns true if the variable declaration is a redeclaration.
7812 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7813   CheckVariableDeclarationType(NewVD);
7814 
7815   // If the decl is already known invalid, don't check it.
7816   if (NewVD->isInvalidDecl())
7817     return false;
7818 
7819   // If we did not find anything by this name, look for a non-visible
7820   // extern "C" declaration with the same name.
7821   if (Previous.empty() &&
7822       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7823     Previous.setShadowed();
7824 
7825   if (!Previous.empty()) {
7826     MergeVarDecl(NewVD, Previous);
7827     return true;
7828   }
7829   return false;
7830 }
7831 
7832 namespace {
7833 struct FindOverriddenMethod {
7834   Sema *S;
7835   CXXMethodDecl *Method;
7836 
7837   /// Member lookup function that determines whether a given C++
7838   /// method overrides a method in a base class, to be used with
7839   /// CXXRecordDecl::lookupInBases().
7840   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7841     RecordDecl *BaseRecord =
7842         Specifier->getType()->castAs<RecordType>()->getDecl();
7843 
7844     DeclarationName Name = Method->getDeclName();
7845 
7846     // FIXME: Do we care about other names here too?
7847     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7848       // We really want to find the base class destructor here.
7849       QualType T = S->Context.getTypeDeclType(BaseRecord);
7850       CanQualType CT = S->Context.getCanonicalType(T);
7851 
7852       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7853     }
7854 
7855     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7856          Path.Decls = Path.Decls.slice(1)) {
7857       NamedDecl *D = Path.Decls.front();
7858       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7859         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7860           return true;
7861       }
7862     }
7863 
7864     return false;
7865   }
7866 };
7867 
7868 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7869 } // end anonymous namespace
7870 
7871 /// Report an error regarding overriding, along with any relevant
7872 /// overridden methods.
7873 ///
7874 /// \param DiagID the primary error to report.
7875 /// \param MD the overriding method.
7876 /// \param OEK which overrides to include as notes.
7877 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7878                             OverrideErrorKind OEK = OEK_All) {
7879   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7880   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7881     // This check (& the OEK parameter) could be replaced by a predicate, but
7882     // without lambdas that would be overkill. This is still nicer than writing
7883     // out the diag loop 3 times.
7884     if ((OEK == OEK_All) ||
7885         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7886         (OEK == OEK_Deleted && O->isDeleted()))
7887       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7888   }
7889 }
7890 
7891 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7892 /// and if so, check that it's a valid override and remember it.
7893 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7894   // Look for methods in base classes that this method might override.
7895   CXXBasePaths Paths;
7896   FindOverriddenMethod FOM;
7897   FOM.Method = MD;
7898   FOM.S = this;
7899   bool hasDeletedOverridenMethods = false;
7900   bool hasNonDeletedOverridenMethods = false;
7901   bool AddedAny = false;
7902   if (DC->lookupInBases(FOM, Paths)) {
7903     for (auto *I : Paths.found_decls()) {
7904       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7905         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7906         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7907             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7908             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7909             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7910           hasDeletedOverridenMethods |= OldMD->isDeleted();
7911           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7912           AddedAny = true;
7913         }
7914       }
7915     }
7916   }
7917 
7918   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7919     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7920   }
7921   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7922     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7923   }
7924 
7925   return AddedAny;
7926 }
7927 
7928 namespace {
7929   // Struct for holding all of the extra arguments needed by
7930   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7931   struct ActOnFDArgs {
7932     Scope *S;
7933     Declarator &D;
7934     MultiTemplateParamsArg TemplateParamLists;
7935     bool AddToScope;
7936   };
7937 } // end anonymous namespace
7938 
7939 namespace {
7940 
7941 // Callback to only accept typo corrections that have a non-zero edit distance.
7942 // Also only accept corrections that have the same parent decl.
7943 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7944  public:
7945   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7946                             CXXRecordDecl *Parent)
7947       : Context(Context), OriginalFD(TypoFD),
7948         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7949 
7950   bool ValidateCandidate(const TypoCorrection &candidate) override {
7951     if (candidate.getEditDistance() == 0)
7952       return false;
7953 
7954     SmallVector<unsigned, 1> MismatchedParams;
7955     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7956                                           CDeclEnd = candidate.end();
7957          CDecl != CDeclEnd; ++CDecl) {
7958       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7959 
7960       if (FD && !FD->hasBody() &&
7961           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7962         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7963           CXXRecordDecl *Parent = MD->getParent();
7964           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7965             return true;
7966         } else if (!ExpectedParent) {
7967           return true;
7968         }
7969       }
7970     }
7971 
7972     return false;
7973   }
7974 
7975   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7976     return std::make_unique<DifferentNameValidatorCCC>(*this);
7977   }
7978 
7979  private:
7980   ASTContext &Context;
7981   FunctionDecl *OriginalFD;
7982   CXXRecordDecl *ExpectedParent;
7983 };
7984 
7985 } // end anonymous namespace
7986 
7987 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7988   TypoCorrectedFunctionDefinitions.insert(F);
7989 }
7990 
7991 /// Generate diagnostics for an invalid function redeclaration.
7992 ///
7993 /// This routine handles generating the diagnostic messages for an invalid
7994 /// function redeclaration, including finding possible similar declarations
7995 /// or performing typo correction if there are no previous declarations with
7996 /// the same name.
7997 ///
7998 /// Returns a NamedDecl iff typo correction was performed and substituting in
7999 /// the new declaration name does not cause new errors.
8000 static NamedDecl *DiagnoseInvalidRedeclaration(
8001     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8002     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8003   DeclarationName Name = NewFD->getDeclName();
8004   DeclContext *NewDC = NewFD->getDeclContext();
8005   SmallVector<unsigned, 1> MismatchedParams;
8006   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8007   TypoCorrection Correction;
8008   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8009   unsigned DiagMsg =
8010     IsLocalFriend ? diag::err_no_matching_local_friend :
8011     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8012     diag::err_member_decl_does_not_match;
8013   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8014                     IsLocalFriend ? Sema::LookupLocalFriendName
8015                                   : Sema::LookupOrdinaryName,
8016                     Sema::ForVisibleRedeclaration);
8017 
8018   NewFD->setInvalidDecl();
8019   if (IsLocalFriend)
8020     SemaRef.LookupName(Prev, S);
8021   else
8022     SemaRef.LookupQualifiedName(Prev, NewDC);
8023   assert(!Prev.isAmbiguous() &&
8024          "Cannot have an ambiguity in previous-declaration lookup");
8025   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8026   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8027                                 MD ? MD->getParent() : nullptr);
8028   if (!Prev.empty()) {
8029     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8030          Func != FuncEnd; ++Func) {
8031       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8032       if (FD &&
8033           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8034         // Add 1 to the index so that 0 can mean the mismatch didn't
8035         // involve a parameter
8036         unsigned ParamNum =
8037             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8038         NearMatches.push_back(std::make_pair(FD, ParamNum));
8039       }
8040     }
8041   // If the qualified name lookup yielded nothing, try typo correction
8042   } else if ((Correction = SemaRef.CorrectTypo(
8043                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8044                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8045                   IsLocalFriend ? nullptr : NewDC))) {
8046     // Set up everything for the call to ActOnFunctionDeclarator
8047     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8048                               ExtraArgs.D.getIdentifierLoc());
8049     Previous.clear();
8050     Previous.setLookupName(Correction.getCorrection());
8051     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8052                                     CDeclEnd = Correction.end();
8053          CDecl != CDeclEnd; ++CDecl) {
8054       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8055       if (FD && !FD->hasBody() &&
8056           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8057         Previous.addDecl(FD);
8058       }
8059     }
8060     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8061 
8062     NamedDecl *Result;
8063     // Retry building the function declaration with the new previous
8064     // declarations, and with errors suppressed.
8065     {
8066       // Trap errors.
8067       Sema::SFINAETrap Trap(SemaRef);
8068 
8069       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8070       // pieces need to verify the typo-corrected C++ declaration and hopefully
8071       // eliminate the need for the parameter pack ExtraArgs.
8072       Result = SemaRef.ActOnFunctionDeclarator(
8073           ExtraArgs.S, ExtraArgs.D,
8074           Correction.getCorrectionDecl()->getDeclContext(),
8075           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8076           ExtraArgs.AddToScope);
8077 
8078       if (Trap.hasErrorOccurred())
8079         Result = nullptr;
8080     }
8081 
8082     if (Result) {
8083       // Determine which correction we picked.
8084       Decl *Canonical = Result->getCanonicalDecl();
8085       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8086            I != E; ++I)
8087         if ((*I)->getCanonicalDecl() == Canonical)
8088           Correction.setCorrectionDecl(*I);
8089 
8090       // Let Sema know about the correction.
8091       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8092       SemaRef.diagnoseTypo(
8093           Correction,
8094           SemaRef.PDiag(IsLocalFriend
8095                           ? diag::err_no_matching_local_friend_suggest
8096                           : diag::err_member_decl_does_not_match_suggest)
8097             << Name << NewDC << IsDefinition);
8098       return Result;
8099     }
8100 
8101     // Pretend the typo correction never occurred
8102     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8103                               ExtraArgs.D.getIdentifierLoc());
8104     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8105     Previous.clear();
8106     Previous.setLookupName(Name);
8107   }
8108 
8109   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8110       << Name << NewDC << IsDefinition << NewFD->getLocation();
8111 
8112   bool NewFDisConst = false;
8113   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8114     NewFDisConst = NewMD->isConst();
8115 
8116   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8117        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8118        NearMatch != NearMatchEnd; ++NearMatch) {
8119     FunctionDecl *FD = NearMatch->first;
8120     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8121     bool FDisConst = MD && MD->isConst();
8122     bool IsMember = MD || !IsLocalFriend;
8123 
8124     // FIXME: These notes are poorly worded for the local friend case.
8125     if (unsigned Idx = NearMatch->second) {
8126       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8127       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8128       if (Loc.isInvalid()) Loc = FD->getLocation();
8129       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8130                                  : diag::note_local_decl_close_param_match)
8131         << Idx << FDParam->getType()
8132         << NewFD->getParamDecl(Idx - 1)->getType();
8133     } else if (FDisConst != NewFDisConst) {
8134       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8135           << NewFDisConst << FD->getSourceRange().getEnd();
8136     } else
8137       SemaRef.Diag(FD->getLocation(),
8138                    IsMember ? diag::note_member_def_close_match
8139                             : diag::note_local_decl_close_match);
8140   }
8141   return nullptr;
8142 }
8143 
8144 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8145   switch (D.getDeclSpec().getStorageClassSpec()) {
8146   default: llvm_unreachable("Unknown storage class!");
8147   case DeclSpec::SCS_auto:
8148   case DeclSpec::SCS_register:
8149   case DeclSpec::SCS_mutable:
8150     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8151                  diag::err_typecheck_sclass_func);
8152     D.getMutableDeclSpec().ClearStorageClassSpecs();
8153     D.setInvalidType();
8154     break;
8155   case DeclSpec::SCS_unspecified: break;
8156   case DeclSpec::SCS_extern:
8157     if (D.getDeclSpec().isExternInLinkageSpec())
8158       return SC_None;
8159     return SC_Extern;
8160   case DeclSpec::SCS_static: {
8161     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8162       // C99 6.7.1p5:
8163       //   The declaration of an identifier for a function that has
8164       //   block scope shall have no explicit storage-class specifier
8165       //   other than extern
8166       // See also (C++ [dcl.stc]p4).
8167       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8168                    diag::err_static_block_func);
8169       break;
8170     } else
8171       return SC_Static;
8172   }
8173   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8174   }
8175 
8176   // No explicit storage class has already been returned
8177   return SC_None;
8178 }
8179 
8180 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8181                                            DeclContext *DC, QualType &R,
8182                                            TypeSourceInfo *TInfo,
8183                                            StorageClass SC,
8184                                            bool &IsVirtualOkay) {
8185   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8186   DeclarationName Name = NameInfo.getName();
8187 
8188   FunctionDecl *NewFD = nullptr;
8189   bool isInline = D.getDeclSpec().isInlineSpecified();
8190 
8191   if (!SemaRef.getLangOpts().CPlusPlus) {
8192     // Determine whether the function was written with a
8193     // prototype. This true when:
8194     //   - there is a prototype in the declarator, or
8195     //   - the type R of the function is some kind of typedef or other non-
8196     //     attributed reference to a type name (which eventually refers to a
8197     //     function type).
8198     bool HasPrototype =
8199       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8200       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8201 
8202     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8203                                  R, TInfo, SC, isInline, HasPrototype,
8204                                  CSK_unspecified);
8205     if (D.isInvalidType())
8206       NewFD->setInvalidDecl();
8207 
8208     return NewFD;
8209   }
8210 
8211   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8212 
8213   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8214   if (ConstexprKind == CSK_constinit) {
8215     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8216                  diag::err_constexpr_wrong_decl_kind)
8217         << ConstexprKind;
8218     ConstexprKind = CSK_unspecified;
8219     D.getMutableDeclSpec().ClearConstexprSpec();
8220   }
8221 
8222   // Check that the return type is not an abstract class type.
8223   // For record types, this is done by the AbstractClassUsageDiagnoser once
8224   // the class has been completely parsed.
8225   if (!DC->isRecord() &&
8226       SemaRef.RequireNonAbstractType(
8227           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8228           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8229     D.setInvalidType();
8230 
8231   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8232     // This is a C++ constructor declaration.
8233     assert(DC->isRecord() &&
8234            "Constructors can only be declared in a member context");
8235 
8236     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8237     return CXXConstructorDecl::Create(
8238         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8239         TInfo, ExplicitSpecifier, isInline,
8240         /*isImplicitlyDeclared=*/false, ConstexprKind);
8241 
8242   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8243     // This is a C++ destructor declaration.
8244     if (DC->isRecord()) {
8245       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8246       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8247       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8248           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8249           isInline,
8250           /*isImplicitlyDeclared=*/false, ConstexprKind);
8251 
8252       // If the destructor needs an implicit exception specification, set it
8253       // now. FIXME: It'd be nice to be able to create the right type to start
8254       // with, but the type needs to reference the destructor declaration.
8255       if (SemaRef.getLangOpts().CPlusPlus11)
8256         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8257 
8258       IsVirtualOkay = true;
8259       return NewDD;
8260 
8261     } else {
8262       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8263       D.setInvalidType();
8264 
8265       // Create a FunctionDecl to satisfy the function definition parsing
8266       // code path.
8267       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8268                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8269                                   isInline,
8270                                   /*hasPrototype=*/true, ConstexprKind);
8271     }
8272 
8273   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8274     if (!DC->isRecord()) {
8275       SemaRef.Diag(D.getIdentifierLoc(),
8276            diag::err_conv_function_not_member);
8277       return nullptr;
8278     }
8279 
8280     SemaRef.CheckConversionDeclarator(D, R, SC);
8281     if (D.isInvalidType())
8282       return nullptr;
8283 
8284     IsVirtualOkay = true;
8285     return CXXConversionDecl::Create(
8286         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8287         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8288 
8289   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8290     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8291 
8292     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8293                                          ExplicitSpecifier, NameInfo, R, TInfo,
8294                                          D.getEndLoc());
8295   } else if (DC->isRecord()) {
8296     // If the name of the function is the same as the name of the record,
8297     // then this must be an invalid constructor that has a return type.
8298     // (The parser checks for a return type and makes the declarator a
8299     // constructor if it has no return type).
8300     if (Name.getAsIdentifierInfo() &&
8301         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8302       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8303         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8304         << SourceRange(D.getIdentifierLoc());
8305       return nullptr;
8306     }
8307 
8308     // This is a C++ method declaration.
8309     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8310         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8311         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8312     IsVirtualOkay = !Ret->isStatic();
8313     return Ret;
8314   } else {
8315     bool isFriend =
8316         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8317     if (!isFriend && SemaRef.CurContext->isRecord())
8318       return nullptr;
8319 
8320     // Determine whether the function was written with a
8321     // prototype. This true when:
8322     //   - we're in C++ (where every function has a prototype),
8323     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8324                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8325                                 ConstexprKind);
8326   }
8327 }
8328 
8329 enum OpenCLParamType {
8330   ValidKernelParam,
8331   PtrPtrKernelParam,
8332   PtrKernelParam,
8333   InvalidAddrSpacePtrKernelParam,
8334   InvalidKernelParam,
8335   RecordKernelParam
8336 };
8337 
8338 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8339   // Size dependent types are just typedefs to normal integer types
8340   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8341   // integers other than by their names.
8342   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8343 
8344   // Remove typedefs one by one until we reach a typedef
8345   // for a size dependent type.
8346   QualType DesugaredTy = Ty;
8347   do {
8348     ArrayRef<StringRef> Names(SizeTypeNames);
8349     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8350     if (Names.end() != Match)
8351       return true;
8352 
8353     Ty = DesugaredTy;
8354     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8355   } while (DesugaredTy != Ty);
8356 
8357   return false;
8358 }
8359 
8360 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8361   if (PT->isPointerType()) {
8362     QualType PointeeType = PT->getPointeeType();
8363     if (PointeeType->isPointerType())
8364       return PtrPtrKernelParam;
8365     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8366         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8367         PointeeType.getAddressSpace() == LangAS::Default)
8368       return InvalidAddrSpacePtrKernelParam;
8369     return PtrKernelParam;
8370   }
8371 
8372   // OpenCL v1.2 s6.9.k:
8373   // Arguments to kernel functions in a program cannot be declared with the
8374   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8375   // uintptr_t or a struct and/or union that contain fields declared to be one
8376   // of these built-in scalar types.
8377   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8378     return InvalidKernelParam;
8379 
8380   if (PT->isImageType())
8381     return PtrKernelParam;
8382 
8383   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8384     return InvalidKernelParam;
8385 
8386   // OpenCL extension spec v1.2 s9.5:
8387   // This extension adds support for half scalar and vector types as built-in
8388   // types that can be used for arithmetic operations, conversions etc.
8389   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8390     return InvalidKernelParam;
8391 
8392   if (PT->isRecordType())
8393     return RecordKernelParam;
8394 
8395   // Look into an array argument to check if it has a forbidden type.
8396   if (PT->isArrayType()) {
8397     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8398     // Call ourself to check an underlying type of an array. Since the
8399     // getPointeeOrArrayElementType returns an innermost type which is not an
8400     // array, this recursive call only happens once.
8401     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8402   }
8403 
8404   return ValidKernelParam;
8405 }
8406 
8407 static void checkIsValidOpenCLKernelParameter(
8408   Sema &S,
8409   Declarator &D,
8410   ParmVarDecl *Param,
8411   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8412   QualType PT = Param->getType();
8413 
8414   // Cache the valid types we encounter to avoid rechecking structs that are
8415   // used again
8416   if (ValidTypes.count(PT.getTypePtr()))
8417     return;
8418 
8419   switch (getOpenCLKernelParameterType(S, PT)) {
8420   case PtrPtrKernelParam:
8421     // OpenCL v1.2 s6.9.a:
8422     // A kernel function argument cannot be declared as a
8423     // pointer to a pointer type.
8424     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8425     D.setInvalidType();
8426     return;
8427 
8428   case InvalidAddrSpacePtrKernelParam:
8429     // OpenCL v1.0 s6.5:
8430     // __kernel function arguments declared to be a pointer of a type can point
8431     // to one of the following address spaces only : __global, __local or
8432     // __constant.
8433     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8434     D.setInvalidType();
8435     return;
8436 
8437     // OpenCL v1.2 s6.9.k:
8438     // Arguments to kernel functions in a program cannot be declared with the
8439     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8440     // uintptr_t or a struct and/or union that contain fields declared to be
8441     // one of these built-in scalar types.
8442 
8443   case InvalidKernelParam:
8444     // OpenCL v1.2 s6.8 n:
8445     // A kernel function argument cannot be declared
8446     // of event_t type.
8447     // Do not diagnose half type since it is diagnosed as invalid argument
8448     // type for any function elsewhere.
8449     if (!PT->isHalfType()) {
8450       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8451 
8452       // Explain what typedefs are involved.
8453       const TypedefType *Typedef = nullptr;
8454       while ((Typedef = PT->getAs<TypedefType>())) {
8455         SourceLocation Loc = Typedef->getDecl()->getLocation();
8456         // SourceLocation may be invalid for a built-in type.
8457         if (Loc.isValid())
8458           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8459         PT = Typedef->desugar();
8460       }
8461     }
8462 
8463     D.setInvalidType();
8464     return;
8465 
8466   case PtrKernelParam:
8467   case ValidKernelParam:
8468     ValidTypes.insert(PT.getTypePtr());
8469     return;
8470 
8471   case RecordKernelParam:
8472     break;
8473   }
8474 
8475   // Track nested structs we will inspect
8476   SmallVector<const Decl *, 4> VisitStack;
8477 
8478   // Track where we are in the nested structs. Items will migrate from
8479   // VisitStack to HistoryStack as we do the DFS for bad field.
8480   SmallVector<const FieldDecl *, 4> HistoryStack;
8481   HistoryStack.push_back(nullptr);
8482 
8483   // At this point we already handled everything except of a RecordType or
8484   // an ArrayType of a RecordType.
8485   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8486   const RecordType *RecTy =
8487       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8488   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8489 
8490   VisitStack.push_back(RecTy->getDecl());
8491   assert(VisitStack.back() && "First decl null?");
8492 
8493   do {
8494     const Decl *Next = VisitStack.pop_back_val();
8495     if (!Next) {
8496       assert(!HistoryStack.empty());
8497       // Found a marker, we have gone up a level
8498       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8499         ValidTypes.insert(Hist->getType().getTypePtr());
8500 
8501       continue;
8502     }
8503 
8504     // Adds everything except the original parameter declaration (which is not a
8505     // field itself) to the history stack.
8506     const RecordDecl *RD;
8507     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8508       HistoryStack.push_back(Field);
8509 
8510       QualType FieldTy = Field->getType();
8511       // Other field types (known to be valid or invalid) are handled while we
8512       // walk around RecordDecl::fields().
8513       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8514              "Unexpected type.");
8515       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8516 
8517       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8518     } else {
8519       RD = cast<RecordDecl>(Next);
8520     }
8521 
8522     // Add a null marker so we know when we've gone back up a level
8523     VisitStack.push_back(nullptr);
8524 
8525     for (const auto *FD : RD->fields()) {
8526       QualType QT = FD->getType();
8527 
8528       if (ValidTypes.count(QT.getTypePtr()))
8529         continue;
8530 
8531       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8532       if (ParamType == ValidKernelParam)
8533         continue;
8534 
8535       if (ParamType == RecordKernelParam) {
8536         VisitStack.push_back(FD);
8537         continue;
8538       }
8539 
8540       // OpenCL v1.2 s6.9.p:
8541       // Arguments to kernel functions that are declared to be a struct or union
8542       // do not allow OpenCL objects to be passed as elements of the struct or
8543       // union.
8544       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8545           ParamType == InvalidAddrSpacePtrKernelParam) {
8546         S.Diag(Param->getLocation(),
8547                diag::err_record_with_pointers_kernel_param)
8548           << PT->isUnionType()
8549           << PT;
8550       } else {
8551         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8552       }
8553 
8554       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8555           << OrigRecDecl->getDeclName();
8556 
8557       // We have an error, now let's go back up through history and show where
8558       // the offending field came from
8559       for (ArrayRef<const FieldDecl *>::const_iterator
8560                I = HistoryStack.begin() + 1,
8561                E = HistoryStack.end();
8562            I != E; ++I) {
8563         const FieldDecl *OuterField = *I;
8564         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8565           << OuterField->getType();
8566       }
8567 
8568       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8569         << QT->isPointerType()
8570         << QT;
8571       D.setInvalidType();
8572       return;
8573     }
8574   } while (!VisitStack.empty());
8575 }
8576 
8577 /// Find the DeclContext in which a tag is implicitly declared if we see an
8578 /// elaborated type specifier in the specified context, and lookup finds
8579 /// nothing.
8580 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8581   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8582     DC = DC->getParent();
8583   return DC;
8584 }
8585 
8586 /// Find the Scope in which a tag is implicitly declared if we see an
8587 /// elaborated type specifier in the specified context, and lookup finds
8588 /// nothing.
8589 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8590   while (S->isClassScope() ||
8591          (LangOpts.CPlusPlus &&
8592           S->isFunctionPrototypeScope()) ||
8593          ((S->getFlags() & Scope::DeclScope) == 0) ||
8594          (S->getEntity() && S->getEntity()->isTransparentContext()))
8595     S = S->getParent();
8596   return S;
8597 }
8598 
8599 NamedDecl*
8600 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8601                               TypeSourceInfo *TInfo, LookupResult &Previous,
8602                               MultiTemplateParamsArg TemplateParamLists,
8603                               bool &AddToScope) {
8604   QualType R = TInfo->getType();
8605 
8606   assert(R->isFunctionType());
8607 
8608   // TODO: consider using NameInfo for diagnostic.
8609   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8610   DeclarationName Name = NameInfo.getName();
8611   StorageClass SC = getFunctionStorageClass(*this, D);
8612 
8613   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8614     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8615          diag::err_invalid_thread)
8616       << DeclSpec::getSpecifierName(TSCS);
8617 
8618   if (D.isFirstDeclarationOfMember())
8619     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8620                            D.getIdentifierLoc());
8621 
8622   bool isFriend = false;
8623   FunctionTemplateDecl *FunctionTemplate = nullptr;
8624   bool isMemberSpecialization = false;
8625   bool isFunctionTemplateSpecialization = false;
8626 
8627   bool isDependentClassScopeExplicitSpecialization = false;
8628   bool HasExplicitTemplateArgs = false;
8629   TemplateArgumentListInfo TemplateArgs;
8630 
8631   bool isVirtualOkay = false;
8632 
8633   DeclContext *OriginalDC = DC;
8634   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8635 
8636   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8637                                               isVirtualOkay);
8638   if (!NewFD) return nullptr;
8639 
8640   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8641     NewFD->setTopLevelDeclInObjCContainer();
8642 
8643   // Set the lexical context. If this is a function-scope declaration, or has a
8644   // C++ scope specifier, or is the object of a friend declaration, the lexical
8645   // context will be different from the semantic context.
8646   NewFD->setLexicalDeclContext(CurContext);
8647 
8648   if (IsLocalExternDecl)
8649     NewFD->setLocalExternDecl();
8650 
8651   if (getLangOpts().CPlusPlus) {
8652     bool isInline = D.getDeclSpec().isInlineSpecified();
8653     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8654     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8655     isFriend = D.getDeclSpec().isFriendSpecified();
8656     if (isFriend && !isInline && D.isFunctionDefinition()) {
8657       // C++ [class.friend]p5
8658       //   A function can be defined in a friend declaration of a
8659       //   class . . . . Such a function is implicitly inline.
8660       NewFD->setImplicitlyInline();
8661     }
8662 
8663     // If this is a method defined in an __interface, and is not a constructor
8664     // or an overloaded operator, then set the pure flag (isVirtual will already
8665     // return true).
8666     if (const CXXRecordDecl *Parent =
8667           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8668       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8669         NewFD->setPure(true);
8670 
8671       // C++ [class.union]p2
8672       //   A union can have member functions, but not virtual functions.
8673       if (isVirtual && Parent->isUnion())
8674         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8675     }
8676 
8677     SetNestedNameSpecifier(*this, NewFD, D);
8678     isMemberSpecialization = false;
8679     isFunctionTemplateSpecialization = false;
8680     if (D.isInvalidType())
8681       NewFD->setInvalidDecl();
8682 
8683     // Match up the template parameter lists with the scope specifier, then
8684     // determine whether we have a template or a template specialization.
8685     bool Invalid = false;
8686     if (TemplateParameterList *TemplateParams =
8687             MatchTemplateParametersToScopeSpecifier(
8688                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8689                 D.getCXXScopeSpec(),
8690                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8691                     ? D.getName().TemplateId
8692                     : nullptr,
8693                 TemplateParamLists, isFriend, isMemberSpecialization,
8694                 Invalid)) {
8695       if (TemplateParams->size() > 0) {
8696         // This is a function template
8697 
8698         // Check that we can declare a template here.
8699         if (CheckTemplateDeclScope(S, TemplateParams))
8700           NewFD->setInvalidDecl();
8701 
8702         // A destructor cannot be a template.
8703         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8704           Diag(NewFD->getLocation(), diag::err_destructor_template);
8705           NewFD->setInvalidDecl();
8706         }
8707 
8708         // If we're adding a template to a dependent context, we may need to
8709         // rebuilding some of the types used within the template parameter list,
8710         // now that we know what the current instantiation is.
8711         if (DC->isDependentContext()) {
8712           ContextRAII SavedContext(*this, DC);
8713           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8714             Invalid = true;
8715         }
8716 
8717         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8718                                                         NewFD->getLocation(),
8719                                                         Name, TemplateParams,
8720                                                         NewFD);
8721         FunctionTemplate->setLexicalDeclContext(CurContext);
8722         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8723 
8724         // For source fidelity, store the other template param lists.
8725         if (TemplateParamLists.size() > 1) {
8726           NewFD->setTemplateParameterListsInfo(Context,
8727                                                TemplateParamLists.drop_back(1));
8728         }
8729       } else {
8730         // This is a function template specialization.
8731         isFunctionTemplateSpecialization = true;
8732         // For source fidelity, store all the template param lists.
8733         if (TemplateParamLists.size() > 0)
8734           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8735 
8736         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8737         if (isFriend) {
8738           // We want to remove the "template<>", found here.
8739           SourceRange RemoveRange = TemplateParams->getSourceRange();
8740 
8741           // If we remove the template<> and the name is not a
8742           // template-id, we're actually silently creating a problem:
8743           // the friend declaration will refer to an untemplated decl,
8744           // and clearly the user wants a template specialization.  So
8745           // we need to insert '<>' after the name.
8746           SourceLocation InsertLoc;
8747           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8748             InsertLoc = D.getName().getSourceRange().getEnd();
8749             InsertLoc = getLocForEndOfToken(InsertLoc);
8750           }
8751 
8752           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8753             << Name << RemoveRange
8754             << FixItHint::CreateRemoval(RemoveRange)
8755             << FixItHint::CreateInsertion(InsertLoc, "<>");
8756         }
8757       }
8758     } else {
8759       // All template param lists were matched against the scope specifier:
8760       // this is NOT (an explicit specialization of) a template.
8761       if (TemplateParamLists.size() > 0)
8762         // For source fidelity, store all the template param lists.
8763         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8764     }
8765 
8766     if (Invalid) {
8767       NewFD->setInvalidDecl();
8768       if (FunctionTemplate)
8769         FunctionTemplate->setInvalidDecl();
8770     }
8771 
8772     // C++ [dcl.fct.spec]p5:
8773     //   The virtual specifier shall only be used in declarations of
8774     //   nonstatic class member functions that appear within a
8775     //   member-specification of a class declaration; see 10.3.
8776     //
8777     if (isVirtual && !NewFD->isInvalidDecl()) {
8778       if (!isVirtualOkay) {
8779         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8780              diag::err_virtual_non_function);
8781       } else if (!CurContext->isRecord()) {
8782         // 'virtual' was specified outside of the class.
8783         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8784              diag::err_virtual_out_of_class)
8785           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8786       } else if (NewFD->getDescribedFunctionTemplate()) {
8787         // C++ [temp.mem]p3:
8788         //  A member function template shall not be virtual.
8789         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8790              diag::err_virtual_member_function_template)
8791           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8792       } else {
8793         // Okay: Add virtual to the method.
8794         NewFD->setVirtualAsWritten(true);
8795       }
8796 
8797       if (getLangOpts().CPlusPlus14 &&
8798           NewFD->getReturnType()->isUndeducedType())
8799         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8800     }
8801 
8802     if (getLangOpts().CPlusPlus14 &&
8803         (NewFD->isDependentContext() ||
8804          (isFriend && CurContext->isDependentContext())) &&
8805         NewFD->getReturnType()->isUndeducedType()) {
8806       // If the function template is referenced directly (for instance, as a
8807       // member of the current instantiation), pretend it has a dependent type.
8808       // This is not really justified by the standard, but is the only sane
8809       // thing to do.
8810       // FIXME: For a friend function, we have not marked the function as being
8811       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8812       const FunctionProtoType *FPT =
8813           NewFD->getType()->castAs<FunctionProtoType>();
8814       QualType Result =
8815           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8816       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8817                                              FPT->getExtProtoInfo()));
8818     }
8819 
8820     // C++ [dcl.fct.spec]p3:
8821     //  The inline specifier shall not appear on a block scope function
8822     //  declaration.
8823     if (isInline && !NewFD->isInvalidDecl()) {
8824       if (CurContext->isFunctionOrMethod()) {
8825         // 'inline' is not allowed on block scope function declaration.
8826         Diag(D.getDeclSpec().getInlineSpecLoc(),
8827              diag::err_inline_declaration_block_scope) << Name
8828           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8829       }
8830     }
8831 
8832     // C++ [dcl.fct.spec]p6:
8833     //  The explicit specifier shall be used only in the declaration of a
8834     //  constructor or conversion function within its class definition;
8835     //  see 12.3.1 and 12.3.2.
8836     if (hasExplicit && !NewFD->isInvalidDecl() &&
8837         !isa<CXXDeductionGuideDecl>(NewFD)) {
8838       if (!CurContext->isRecord()) {
8839         // 'explicit' was specified outside of the class.
8840         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8841              diag::err_explicit_out_of_class)
8842             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8843       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8844                  !isa<CXXConversionDecl>(NewFD)) {
8845         // 'explicit' was specified on a function that wasn't a constructor
8846         // or conversion function.
8847         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8848              diag::err_explicit_non_ctor_or_conv_function)
8849             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8850       }
8851     }
8852 
8853     if (ConstexprSpecKind ConstexprKind =
8854             D.getDeclSpec().getConstexprSpecifier()) {
8855       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8856       // are implicitly inline.
8857       NewFD->setImplicitlyInline();
8858 
8859       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8860       // be either constructors or to return a literal type. Therefore,
8861       // destructors cannot be declared constexpr.
8862       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8863         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8864             << ConstexprKind;
8865       }
8866     }
8867 
8868     // If __module_private__ was specified, mark the function accordingly.
8869     if (D.getDeclSpec().isModulePrivateSpecified()) {
8870       if (isFunctionTemplateSpecialization) {
8871         SourceLocation ModulePrivateLoc
8872           = D.getDeclSpec().getModulePrivateSpecLoc();
8873         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8874           << 0
8875           << FixItHint::CreateRemoval(ModulePrivateLoc);
8876       } else {
8877         NewFD->setModulePrivate();
8878         if (FunctionTemplate)
8879           FunctionTemplate->setModulePrivate();
8880       }
8881     }
8882 
8883     if (isFriend) {
8884       if (FunctionTemplate) {
8885         FunctionTemplate->setObjectOfFriendDecl();
8886         FunctionTemplate->setAccess(AS_public);
8887       }
8888       NewFD->setObjectOfFriendDecl();
8889       NewFD->setAccess(AS_public);
8890     }
8891 
8892     // If a function is defined as defaulted or deleted, mark it as such now.
8893     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8894     // definition kind to FDK_Definition.
8895     switch (D.getFunctionDefinitionKind()) {
8896       case FDK_Declaration:
8897       case FDK_Definition:
8898         break;
8899 
8900       case FDK_Defaulted:
8901         NewFD->setDefaulted();
8902         break;
8903 
8904       case FDK_Deleted:
8905         NewFD->setDeletedAsWritten();
8906         break;
8907     }
8908 
8909     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8910         D.isFunctionDefinition()) {
8911       // C++ [class.mfct]p2:
8912       //   A member function may be defined (8.4) in its class definition, in
8913       //   which case it is an inline member function (7.1.2)
8914       NewFD->setImplicitlyInline();
8915     }
8916 
8917     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8918         !CurContext->isRecord()) {
8919       // C++ [class.static]p1:
8920       //   A data or function member of a class may be declared static
8921       //   in a class definition, in which case it is a static member of
8922       //   the class.
8923 
8924       // Complain about the 'static' specifier if it's on an out-of-line
8925       // member function definition.
8926 
8927       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8928       // member function template declaration and class member template
8929       // declaration (MSVC versions before 2015), warn about this.
8930       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8931            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8932              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8933            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8934            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8935         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8936     }
8937 
8938     // C++11 [except.spec]p15:
8939     //   A deallocation function with no exception-specification is treated
8940     //   as if it were specified with noexcept(true).
8941     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8942     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8943          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8944         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8945       NewFD->setType(Context.getFunctionType(
8946           FPT->getReturnType(), FPT->getParamTypes(),
8947           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8948   }
8949 
8950   // Filter out previous declarations that don't match the scope.
8951   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8952                        D.getCXXScopeSpec().isNotEmpty() ||
8953                        isMemberSpecialization ||
8954                        isFunctionTemplateSpecialization);
8955 
8956   // Handle GNU asm-label extension (encoded as an attribute).
8957   if (Expr *E = (Expr*) D.getAsmLabel()) {
8958     // The parser guarantees this is a string.
8959     StringLiteral *SE = cast<StringLiteral>(E);
8960     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
8961                                         /*IsLiteralLabel=*/true,
8962                                         SE->getStrTokenLoc(0)));
8963   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8964     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8965       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8966     if (I != ExtnameUndeclaredIdentifiers.end()) {
8967       if (isDeclExternC(NewFD)) {
8968         NewFD->addAttr(I->second);
8969         ExtnameUndeclaredIdentifiers.erase(I);
8970       } else
8971         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8972             << /*Variable*/0 << NewFD;
8973     }
8974   }
8975 
8976   // Copy the parameter declarations from the declarator D to the function
8977   // declaration NewFD, if they are available.  First scavenge them into Params.
8978   SmallVector<ParmVarDecl*, 16> Params;
8979   unsigned FTIIdx;
8980   if (D.isFunctionDeclarator(FTIIdx)) {
8981     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8982 
8983     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8984     // function that takes no arguments, not a function that takes a
8985     // single void argument.
8986     // We let through "const void" here because Sema::GetTypeForDeclarator
8987     // already checks for that case.
8988     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8989       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8990         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8991         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8992         Param->setDeclContext(NewFD);
8993         Params.push_back(Param);
8994 
8995         if (Param->isInvalidDecl())
8996           NewFD->setInvalidDecl();
8997       }
8998     }
8999 
9000     if (!getLangOpts().CPlusPlus) {
9001       // In C, find all the tag declarations from the prototype and move them
9002       // into the function DeclContext. Remove them from the surrounding tag
9003       // injection context of the function, which is typically but not always
9004       // the TU.
9005       DeclContext *PrototypeTagContext =
9006           getTagInjectionContext(NewFD->getLexicalDeclContext());
9007       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9008         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9009 
9010         // We don't want to reparent enumerators. Look at their parent enum
9011         // instead.
9012         if (!TD) {
9013           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9014             TD = cast<EnumDecl>(ECD->getDeclContext());
9015         }
9016         if (!TD)
9017           continue;
9018         DeclContext *TagDC = TD->getLexicalDeclContext();
9019         if (!TagDC->containsDecl(TD))
9020           continue;
9021         TagDC->removeDecl(TD);
9022         TD->setDeclContext(NewFD);
9023         NewFD->addDecl(TD);
9024 
9025         // Preserve the lexical DeclContext if it is not the surrounding tag
9026         // injection context of the FD. In this example, the semantic context of
9027         // E will be f and the lexical context will be S, while both the
9028         // semantic and lexical contexts of S will be f:
9029         //   void f(struct S { enum E { a } f; } s);
9030         if (TagDC != PrototypeTagContext)
9031           TD->setLexicalDeclContext(TagDC);
9032       }
9033     }
9034   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9035     // When we're declaring a function with a typedef, typeof, etc as in the
9036     // following example, we'll need to synthesize (unnamed)
9037     // parameters for use in the declaration.
9038     //
9039     // @code
9040     // typedef void fn(int);
9041     // fn f;
9042     // @endcode
9043 
9044     // Synthesize a parameter for each argument type.
9045     for (const auto &AI : FT->param_types()) {
9046       ParmVarDecl *Param =
9047           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9048       Param->setScopeInfo(0, Params.size());
9049       Params.push_back(Param);
9050     }
9051   } else {
9052     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9053            "Should not need args for typedef of non-prototype fn");
9054   }
9055 
9056   // Finally, we know we have the right number of parameters, install them.
9057   NewFD->setParams(Params);
9058 
9059   if (D.getDeclSpec().isNoreturnSpecified())
9060     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9061                                            D.getDeclSpec().getNoreturnSpecLoc(),
9062                                            AttributeCommonInfo::AS_Keyword));
9063 
9064   // Functions returning a variably modified type violate C99 6.7.5.2p2
9065   // because all functions have linkage.
9066   if (!NewFD->isInvalidDecl() &&
9067       NewFD->getReturnType()->isVariablyModifiedType()) {
9068     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9069     NewFD->setInvalidDecl();
9070   }
9071 
9072   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9073   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9074       !NewFD->hasAttr<SectionAttr>())
9075     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9076         Context, PragmaClangTextSection.SectionName,
9077         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9078 
9079   // Apply an implicit SectionAttr if #pragma code_seg is active.
9080   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9081       !NewFD->hasAttr<SectionAttr>()) {
9082     NewFD->addAttr(SectionAttr::CreateImplicit(
9083         Context, CodeSegStack.CurrentValue->getString(),
9084         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9085         SectionAttr::Declspec_allocate));
9086     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9087                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9088                          ASTContext::PSF_Read,
9089                      NewFD))
9090       NewFD->dropAttr<SectionAttr>();
9091   }
9092 
9093   // Apply an implicit CodeSegAttr from class declspec or
9094   // apply an implicit SectionAttr from #pragma code_seg if active.
9095   if (!NewFD->hasAttr<CodeSegAttr>()) {
9096     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9097                                                                  D.isFunctionDefinition())) {
9098       NewFD->addAttr(SAttr);
9099     }
9100   }
9101 
9102   // Handle attributes.
9103   ProcessDeclAttributes(S, NewFD, D);
9104 
9105   if (getLangOpts().OpenCL) {
9106     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9107     // type declaration will generate a compilation error.
9108     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9109     if (AddressSpace != LangAS::Default) {
9110       Diag(NewFD->getLocation(),
9111            diag::err_opencl_return_value_with_address_space);
9112       NewFD->setInvalidDecl();
9113     }
9114   }
9115 
9116   if (!getLangOpts().CPlusPlus) {
9117     // Perform semantic checking on the function declaration.
9118     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9119       CheckMain(NewFD, D.getDeclSpec());
9120 
9121     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9122       CheckMSVCRTEntryPoint(NewFD);
9123 
9124     if (!NewFD->isInvalidDecl())
9125       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9126                                                   isMemberSpecialization));
9127     else if (!Previous.empty())
9128       // Recover gracefully from an invalid redeclaration.
9129       D.setRedeclaration(true);
9130     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9131             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9132            "previous declaration set still overloaded");
9133 
9134     // Diagnose no-prototype function declarations with calling conventions that
9135     // don't support variadic calls. Only do this in C and do it after merging
9136     // possibly prototyped redeclarations.
9137     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9138     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9139       CallingConv CC = FT->getExtInfo().getCC();
9140       if (!supportsVariadicCall(CC)) {
9141         // Windows system headers sometimes accidentally use stdcall without
9142         // (void) parameters, so we relax this to a warning.
9143         int DiagID =
9144             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9145         Diag(NewFD->getLocation(), DiagID)
9146             << FunctionType::getNameForCallConv(CC);
9147       }
9148     }
9149 
9150    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9151        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9152      checkNonTrivialCUnion(NewFD->getReturnType(),
9153                            NewFD->getReturnTypeSourceRange().getBegin(),
9154                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9155   } else {
9156     // C++11 [replacement.functions]p3:
9157     //  The program's definitions shall not be specified as inline.
9158     //
9159     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9160     //
9161     // Suppress the diagnostic if the function is __attribute__((used)), since
9162     // that forces an external definition to be emitted.
9163     if (D.getDeclSpec().isInlineSpecified() &&
9164         NewFD->isReplaceableGlobalAllocationFunction() &&
9165         !NewFD->hasAttr<UsedAttr>())
9166       Diag(D.getDeclSpec().getInlineSpecLoc(),
9167            diag::ext_operator_new_delete_declared_inline)
9168         << NewFD->getDeclName();
9169 
9170     // If the declarator is a template-id, translate the parser's template
9171     // argument list into our AST format.
9172     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9173       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9174       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9175       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9176       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9177                                          TemplateId->NumArgs);
9178       translateTemplateArguments(TemplateArgsPtr,
9179                                  TemplateArgs);
9180 
9181       HasExplicitTemplateArgs = true;
9182 
9183       if (NewFD->isInvalidDecl()) {
9184         HasExplicitTemplateArgs = false;
9185       } else if (FunctionTemplate) {
9186         // Function template with explicit template arguments.
9187         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9188           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9189 
9190         HasExplicitTemplateArgs = false;
9191       } else {
9192         assert((isFunctionTemplateSpecialization ||
9193                 D.getDeclSpec().isFriendSpecified()) &&
9194                "should have a 'template<>' for this decl");
9195         // "friend void foo<>(int);" is an implicit specialization decl.
9196         isFunctionTemplateSpecialization = true;
9197       }
9198     } else if (isFriend && isFunctionTemplateSpecialization) {
9199       // This combination is only possible in a recovery case;  the user
9200       // wrote something like:
9201       //   template <> friend void foo(int);
9202       // which we're recovering from as if the user had written:
9203       //   friend void foo<>(int);
9204       // Go ahead and fake up a template id.
9205       HasExplicitTemplateArgs = true;
9206       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9207       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9208     }
9209 
9210     // We do not add HD attributes to specializations here because
9211     // they may have different constexpr-ness compared to their
9212     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9213     // may end up with different effective targets. Instead, a
9214     // specialization inherits its target attributes from its template
9215     // in the CheckFunctionTemplateSpecialization() call below.
9216     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9217       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9218 
9219     // If it's a friend (and only if it's a friend), it's possible
9220     // that either the specialized function type or the specialized
9221     // template is dependent, and therefore matching will fail.  In
9222     // this case, don't check the specialization yet.
9223     bool InstantiationDependent = false;
9224     if (isFunctionTemplateSpecialization && isFriend &&
9225         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9226          TemplateSpecializationType::anyDependentTemplateArguments(
9227             TemplateArgs,
9228             InstantiationDependent))) {
9229       assert(HasExplicitTemplateArgs &&
9230              "friend function specialization without template args");
9231       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9232                                                        Previous))
9233         NewFD->setInvalidDecl();
9234     } else if (isFunctionTemplateSpecialization) {
9235       if (CurContext->isDependentContext() && CurContext->isRecord()
9236           && !isFriend) {
9237         isDependentClassScopeExplicitSpecialization = true;
9238       } else if (!NewFD->isInvalidDecl() &&
9239                  CheckFunctionTemplateSpecialization(
9240                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9241                      Previous))
9242         NewFD->setInvalidDecl();
9243 
9244       // C++ [dcl.stc]p1:
9245       //   A storage-class-specifier shall not be specified in an explicit
9246       //   specialization (14.7.3)
9247       FunctionTemplateSpecializationInfo *Info =
9248           NewFD->getTemplateSpecializationInfo();
9249       if (Info && SC != SC_None) {
9250         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9251           Diag(NewFD->getLocation(),
9252                diag::err_explicit_specialization_inconsistent_storage_class)
9253             << SC
9254             << FixItHint::CreateRemoval(
9255                                       D.getDeclSpec().getStorageClassSpecLoc());
9256 
9257         else
9258           Diag(NewFD->getLocation(),
9259                diag::ext_explicit_specialization_storage_class)
9260             << FixItHint::CreateRemoval(
9261                                       D.getDeclSpec().getStorageClassSpecLoc());
9262       }
9263     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9264       if (CheckMemberSpecialization(NewFD, Previous))
9265           NewFD->setInvalidDecl();
9266     }
9267 
9268     // Perform semantic checking on the function declaration.
9269     if (!isDependentClassScopeExplicitSpecialization) {
9270       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9271         CheckMain(NewFD, D.getDeclSpec());
9272 
9273       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9274         CheckMSVCRTEntryPoint(NewFD);
9275 
9276       if (!NewFD->isInvalidDecl())
9277         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9278                                                     isMemberSpecialization));
9279       else if (!Previous.empty())
9280         // Recover gracefully from an invalid redeclaration.
9281         D.setRedeclaration(true);
9282     }
9283 
9284     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9285             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9286            "previous declaration set still overloaded");
9287 
9288     NamedDecl *PrincipalDecl = (FunctionTemplate
9289                                 ? cast<NamedDecl>(FunctionTemplate)
9290                                 : NewFD);
9291 
9292     if (isFriend && NewFD->getPreviousDecl()) {
9293       AccessSpecifier Access = AS_public;
9294       if (!NewFD->isInvalidDecl())
9295         Access = NewFD->getPreviousDecl()->getAccess();
9296 
9297       NewFD->setAccess(Access);
9298       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9299     }
9300 
9301     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9302         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9303       PrincipalDecl->setNonMemberOperator();
9304 
9305     // If we have a function template, check the template parameter
9306     // list. This will check and merge default template arguments.
9307     if (FunctionTemplate) {
9308       FunctionTemplateDecl *PrevTemplate =
9309                                      FunctionTemplate->getPreviousDecl();
9310       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9311                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9312                                     : nullptr,
9313                             D.getDeclSpec().isFriendSpecified()
9314                               ? (D.isFunctionDefinition()
9315                                    ? TPC_FriendFunctionTemplateDefinition
9316                                    : TPC_FriendFunctionTemplate)
9317                               : (D.getCXXScopeSpec().isSet() &&
9318                                  DC && DC->isRecord() &&
9319                                  DC->isDependentContext())
9320                                   ? TPC_ClassTemplateMember
9321                                   : TPC_FunctionTemplate);
9322     }
9323 
9324     if (NewFD->isInvalidDecl()) {
9325       // Ignore all the rest of this.
9326     } else if (!D.isRedeclaration()) {
9327       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9328                                        AddToScope };
9329       // Fake up an access specifier if it's supposed to be a class member.
9330       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9331         NewFD->setAccess(AS_public);
9332 
9333       // Qualified decls generally require a previous declaration.
9334       if (D.getCXXScopeSpec().isSet()) {
9335         // ...with the major exception of templated-scope or
9336         // dependent-scope friend declarations.
9337 
9338         // TODO: we currently also suppress this check in dependent
9339         // contexts because (1) the parameter depth will be off when
9340         // matching friend templates and (2) we might actually be
9341         // selecting a friend based on a dependent factor.  But there
9342         // are situations where these conditions don't apply and we
9343         // can actually do this check immediately.
9344         //
9345         // Unless the scope is dependent, it's always an error if qualified
9346         // redeclaration lookup found nothing at all. Diagnose that now;
9347         // nothing will diagnose that error later.
9348         if (isFriend &&
9349             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9350              (!Previous.empty() && CurContext->isDependentContext()))) {
9351           // ignore these
9352         } else {
9353           // The user tried to provide an out-of-line definition for a
9354           // function that is a member of a class or namespace, but there
9355           // was no such member function declared (C++ [class.mfct]p2,
9356           // C++ [namespace.memdef]p2). For example:
9357           //
9358           // class X {
9359           //   void f() const;
9360           // };
9361           //
9362           // void X::f() { } // ill-formed
9363           //
9364           // Complain about this problem, and attempt to suggest close
9365           // matches (e.g., those that differ only in cv-qualifiers and
9366           // whether the parameter types are references).
9367 
9368           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9369                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9370             AddToScope = ExtraArgs.AddToScope;
9371             return Result;
9372           }
9373         }
9374 
9375         // Unqualified local friend declarations are required to resolve
9376         // to something.
9377       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9378         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9379                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9380           AddToScope = ExtraArgs.AddToScope;
9381           return Result;
9382         }
9383       }
9384     } else if (!D.isFunctionDefinition() &&
9385                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9386                !isFriend && !isFunctionTemplateSpecialization &&
9387                !isMemberSpecialization) {
9388       // An out-of-line member function declaration must also be a
9389       // definition (C++ [class.mfct]p2).
9390       // Note that this is not the case for explicit specializations of
9391       // function templates or member functions of class templates, per
9392       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9393       // extension for compatibility with old SWIG code which likes to
9394       // generate them.
9395       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9396         << D.getCXXScopeSpec().getRange();
9397     }
9398   }
9399 
9400   ProcessPragmaWeak(S, NewFD);
9401   checkAttributesAfterMerging(*this, *NewFD);
9402 
9403   AddKnownFunctionAttributes(NewFD);
9404 
9405   if (NewFD->hasAttr<OverloadableAttr>() &&
9406       !NewFD->getType()->getAs<FunctionProtoType>()) {
9407     Diag(NewFD->getLocation(),
9408          diag::err_attribute_overloadable_no_prototype)
9409       << NewFD;
9410 
9411     // Turn this into a variadic function with no parameters.
9412     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9413     FunctionProtoType::ExtProtoInfo EPI(
9414         Context.getDefaultCallingConvention(true, false));
9415     EPI.Variadic = true;
9416     EPI.ExtInfo = FT->getExtInfo();
9417 
9418     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9419     NewFD->setType(R);
9420   }
9421 
9422   // If there's a #pragma GCC visibility in scope, and this isn't a class
9423   // member, set the visibility of this function.
9424   if (!DC->isRecord() && NewFD->isExternallyVisible())
9425     AddPushedVisibilityAttribute(NewFD);
9426 
9427   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9428   // marking the function.
9429   AddCFAuditedAttribute(NewFD);
9430 
9431   // If this is a function definition, check if we have to apply optnone due to
9432   // a pragma.
9433   if(D.isFunctionDefinition())
9434     AddRangeBasedOptnone(NewFD);
9435 
9436   // If this is the first declaration of an extern C variable, update
9437   // the map of such variables.
9438   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9439       isIncompleteDeclExternC(*this, NewFD))
9440     RegisterLocallyScopedExternCDecl(NewFD, S);
9441 
9442   // Set this FunctionDecl's range up to the right paren.
9443   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9444 
9445   if (D.isRedeclaration() && !Previous.empty()) {
9446     NamedDecl *Prev = Previous.getRepresentativeDecl();
9447     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9448                                    isMemberSpecialization ||
9449                                        isFunctionTemplateSpecialization,
9450                                    D.isFunctionDefinition());
9451   }
9452 
9453   if (getLangOpts().CUDA) {
9454     IdentifierInfo *II = NewFD->getIdentifier();
9455     if (II && II->isStr(getCudaConfigureFuncName()) &&
9456         !NewFD->isInvalidDecl() &&
9457         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9458       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9459         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9460             << getCudaConfigureFuncName();
9461       Context.setcudaConfigureCallDecl(NewFD);
9462     }
9463 
9464     // Variadic functions, other than a *declaration* of printf, are not allowed
9465     // in device-side CUDA code, unless someone passed
9466     // -fcuda-allow-variadic-functions.
9467     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9468         (NewFD->hasAttr<CUDADeviceAttr>() ||
9469          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9470         !(II && II->isStr("printf") && NewFD->isExternC() &&
9471           !D.isFunctionDefinition())) {
9472       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9473     }
9474   }
9475 
9476   MarkUnusedFileScopedDecl(NewFD);
9477 
9478 
9479 
9480   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9481     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9482     if ((getLangOpts().OpenCLVersion >= 120)
9483         && (SC == SC_Static)) {
9484       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9485       D.setInvalidType();
9486     }
9487 
9488     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9489     if (!NewFD->getReturnType()->isVoidType()) {
9490       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9491       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9492           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9493                                 : FixItHint());
9494       D.setInvalidType();
9495     }
9496 
9497     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9498     for (auto Param : NewFD->parameters())
9499       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9500 
9501     if (getLangOpts().OpenCLCPlusPlus) {
9502       if (DC->isRecord()) {
9503         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9504         D.setInvalidType();
9505       }
9506       if (FunctionTemplate) {
9507         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9508         D.setInvalidType();
9509       }
9510     }
9511   }
9512 
9513   if (getLangOpts().CPlusPlus) {
9514     if (FunctionTemplate) {
9515       if (NewFD->isInvalidDecl())
9516         FunctionTemplate->setInvalidDecl();
9517       return FunctionTemplate;
9518     }
9519 
9520     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9521       CompleteMemberSpecialization(NewFD, Previous);
9522   }
9523 
9524   for (const ParmVarDecl *Param : NewFD->parameters()) {
9525     QualType PT = Param->getType();
9526 
9527     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9528     // types.
9529     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9530       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9531         QualType ElemTy = PipeTy->getElementType();
9532           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9533             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9534             D.setInvalidType();
9535           }
9536       }
9537     }
9538   }
9539 
9540   // Here we have an function template explicit specialization at class scope.
9541   // The actual specialization will be postponed to template instatiation
9542   // time via the ClassScopeFunctionSpecializationDecl node.
9543   if (isDependentClassScopeExplicitSpecialization) {
9544     ClassScopeFunctionSpecializationDecl *NewSpec =
9545                          ClassScopeFunctionSpecializationDecl::Create(
9546                                 Context, CurContext, NewFD->getLocation(),
9547                                 cast<CXXMethodDecl>(NewFD),
9548                                 HasExplicitTemplateArgs, TemplateArgs);
9549     CurContext->addDecl(NewSpec);
9550     AddToScope = false;
9551   }
9552 
9553   // Diagnose availability attributes. Availability cannot be used on functions
9554   // that are run during load/unload.
9555   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9556     if (NewFD->hasAttr<ConstructorAttr>()) {
9557       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9558           << 1;
9559       NewFD->dropAttr<AvailabilityAttr>();
9560     }
9561     if (NewFD->hasAttr<DestructorAttr>()) {
9562       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9563           << 2;
9564       NewFD->dropAttr<AvailabilityAttr>();
9565     }
9566   }
9567 
9568   // Diagnose no_builtin attribute on function declaration that are not a
9569   // definition.
9570   // FIXME: We should really be doing this in
9571   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9572   // the FunctionDecl and at this point of the code
9573   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9574   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9575   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9576     switch (D.getFunctionDefinitionKind()) {
9577     case FDK_Defaulted:
9578     case FDK_Deleted:
9579       Diag(NBA->getLocation(),
9580            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9581           << NBA->getSpelling();
9582       break;
9583     case FDK_Declaration:
9584       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9585           << NBA->getSpelling();
9586       break;
9587     case FDK_Definition:
9588       break;
9589     }
9590 
9591   return NewFD;
9592 }
9593 
9594 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9595 /// when __declspec(code_seg) "is applied to a class, all member functions of
9596 /// the class and nested classes -- this includes compiler-generated special
9597 /// member functions -- are put in the specified segment."
9598 /// The actual behavior is a little more complicated. The Microsoft compiler
9599 /// won't check outer classes if there is an active value from #pragma code_seg.
9600 /// The CodeSeg is always applied from the direct parent but only from outer
9601 /// classes when the #pragma code_seg stack is empty. See:
9602 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9603 /// available since MS has removed the page.
9604 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9605   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9606   if (!Method)
9607     return nullptr;
9608   const CXXRecordDecl *Parent = Method->getParent();
9609   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9610     Attr *NewAttr = SAttr->clone(S.getASTContext());
9611     NewAttr->setImplicit(true);
9612     return NewAttr;
9613   }
9614 
9615   // The Microsoft compiler won't check outer classes for the CodeSeg
9616   // when the #pragma code_seg stack is active.
9617   if (S.CodeSegStack.CurrentValue)
9618    return nullptr;
9619 
9620   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9621     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9622       Attr *NewAttr = SAttr->clone(S.getASTContext());
9623       NewAttr->setImplicit(true);
9624       return NewAttr;
9625     }
9626   }
9627   return nullptr;
9628 }
9629 
9630 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9631 /// containing class. Otherwise it will return implicit SectionAttr if the
9632 /// function is a definition and there is an active value on CodeSegStack
9633 /// (from the current #pragma code-seg value).
9634 ///
9635 /// \param FD Function being declared.
9636 /// \param IsDefinition Whether it is a definition or just a declarartion.
9637 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9638 ///          nullptr if no attribute should be added.
9639 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9640                                                        bool IsDefinition) {
9641   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9642     return A;
9643   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9644       CodeSegStack.CurrentValue)
9645     return SectionAttr::CreateImplicit(
9646         getASTContext(), CodeSegStack.CurrentValue->getString(),
9647         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9648         SectionAttr::Declspec_allocate);
9649   return nullptr;
9650 }
9651 
9652 /// Determines if we can perform a correct type check for \p D as a
9653 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9654 /// best-effort check.
9655 ///
9656 /// \param NewD The new declaration.
9657 /// \param OldD The old declaration.
9658 /// \param NewT The portion of the type of the new declaration to check.
9659 /// \param OldT The portion of the type of the old declaration to check.
9660 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9661                                           QualType NewT, QualType OldT) {
9662   if (!NewD->getLexicalDeclContext()->isDependentContext())
9663     return true;
9664 
9665   // For dependently-typed local extern declarations and friends, we can't
9666   // perform a correct type check in general until instantiation:
9667   //
9668   //   int f();
9669   //   template<typename T> void g() { T f(); }
9670   //
9671   // (valid if g() is only instantiated with T = int).
9672   if (NewT->isDependentType() &&
9673       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9674     return false;
9675 
9676   // Similarly, if the previous declaration was a dependent local extern
9677   // declaration, we don't really know its type yet.
9678   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9679     return false;
9680 
9681   return true;
9682 }
9683 
9684 /// Checks if the new declaration declared in dependent context must be
9685 /// put in the same redeclaration chain as the specified declaration.
9686 ///
9687 /// \param D Declaration that is checked.
9688 /// \param PrevDecl Previous declaration found with proper lookup method for the
9689 ///                 same declaration name.
9690 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9691 ///          belongs to.
9692 ///
9693 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9694   if (!D->getLexicalDeclContext()->isDependentContext())
9695     return true;
9696 
9697   // Don't chain dependent friend function definitions until instantiation, to
9698   // permit cases like
9699   //
9700   //   void func();
9701   //   template<typename T> class C1 { friend void func() {} };
9702   //   template<typename T> class C2 { friend void func() {} };
9703   //
9704   // ... which is valid if only one of C1 and C2 is ever instantiated.
9705   //
9706   // FIXME: This need only apply to function definitions. For now, we proxy
9707   // this by checking for a file-scope function. We do not want this to apply
9708   // to friend declarations nominating member functions, because that gets in
9709   // the way of access checks.
9710   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9711     return false;
9712 
9713   auto *VD = dyn_cast<ValueDecl>(D);
9714   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9715   return !VD || !PrevVD ||
9716          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9717                                         PrevVD->getType());
9718 }
9719 
9720 /// Check the target attribute of the function for MultiVersion
9721 /// validity.
9722 ///
9723 /// Returns true if there was an error, false otherwise.
9724 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9725   const auto *TA = FD->getAttr<TargetAttr>();
9726   assert(TA && "MultiVersion Candidate requires a target attribute");
9727   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9728   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9729   enum ErrType { Feature = 0, Architecture = 1 };
9730 
9731   if (!ParseInfo.Architecture.empty() &&
9732       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9733     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9734         << Architecture << ParseInfo.Architecture;
9735     return true;
9736   }
9737 
9738   for (const auto &Feat : ParseInfo.Features) {
9739     auto BareFeat = StringRef{Feat}.substr(1);
9740     if (Feat[0] == '-') {
9741       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9742           << Feature << ("no-" + BareFeat).str();
9743       return true;
9744     }
9745 
9746     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9747         !TargetInfo.isValidFeatureName(BareFeat)) {
9748       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9749           << Feature << BareFeat;
9750       return true;
9751     }
9752   }
9753   return false;
9754 }
9755 
9756 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9757                                          MultiVersionKind MVType) {
9758   for (const Attr *A : FD->attrs()) {
9759     switch (A->getKind()) {
9760     case attr::CPUDispatch:
9761     case attr::CPUSpecific:
9762       if (MVType != MultiVersionKind::CPUDispatch &&
9763           MVType != MultiVersionKind::CPUSpecific)
9764         return true;
9765       break;
9766     case attr::Target:
9767       if (MVType != MultiVersionKind::Target)
9768         return true;
9769       break;
9770     default:
9771       return true;
9772     }
9773   }
9774   return false;
9775 }
9776 
9777 bool Sema::areMultiversionVariantFunctionsCompatible(
9778     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9779     const PartialDiagnostic &NoProtoDiagID,
9780     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9781     const PartialDiagnosticAt &NoSupportDiagIDAt,
9782     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9783     bool ConstexprSupported, bool CLinkageMayDiffer) {
9784   enum DoesntSupport {
9785     FuncTemplates = 0,
9786     VirtFuncs = 1,
9787     DeducedReturn = 2,
9788     Constructors = 3,
9789     Destructors = 4,
9790     DeletedFuncs = 5,
9791     DefaultedFuncs = 6,
9792     ConstexprFuncs = 7,
9793     ConstevalFuncs = 8,
9794   };
9795   enum Different {
9796     CallingConv = 0,
9797     ReturnType = 1,
9798     ConstexprSpec = 2,
9799     InlineSpec = 3,
9800     StorageClass = 4,
9801     Linkage = 5,
9802   };
9803 
9804   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9805     Diag(OldFD->getLocation(), NoProtoDiagID);
9806     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9807     return true;
9808   }
9809 
9810   if (!NewFD->getType()->getAs<FunctionProtoType>())
9811     return Diag(NewFD->getLocation(), NoProtoDiagID);
9812 
9813   if (!TemplatesSupported &&
9814       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9815     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9816            << FuncTemplates;
9817 
9818   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9819     if (NewCXXFD->isVirtual())
9820       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9821              << VirtFuncs;
9822 
9823     if (isa<CXXConstructorDecl>(NewCXXFD))
9824       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9825              << Constructors;
9826 
9827     if (isa<CXXDestructorDecl>(NewCXXFD))
9828       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9829              << Destructors;
9830   }
9831 
9832   if (NewFD->isDeleted())
9833     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9834            << DeletedFuncs;
9835 
9836   if (NewFD->isDefaulted())
9837     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9838            << DefaultedFuncs;
9839 
9840   if (!ConstexprSupported && NewFD->isConstexpr())
9841     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9842            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9843 
9844   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9845   const auto *NewType = cast<FunctionType>(NewQType);
9846   QualType NewReturnType = NewType->getReturnType();
9847 
9848   if (NewReturnType->isUndeducedType())
9849     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9850            << DeducedReturn;
9851 
9852   // Ensure the return type is identical.
9853   if (OldFD) {
9854     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9855     const auto *OldType = cast<FunctionType>(OldQType);
9856     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9857     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9858 
9859     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9860       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9861 
9862     QualType OldReturnType = OldType->getReturnType();
9863 
9864     if (OldReturnType != NewReturnType)
9865       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9866 
9867     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9868       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9869 
9870     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9871       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9872 
9873     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9874       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9875 
9876     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9877       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9878 
9879     if (CheckEquivalentExceptionSpec(
9880             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9881             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9882       return true;
9883   }
9884   return false;
9885 }
9886 
9887 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9888                                              const FunctionDecl *NewFD,
9889                                              bool CausesMV,
9890                                              MultiVersionKind MVType) {
9891   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9892     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9893     if (OldFD)
9894       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9895     return true;
9896   }
9897 
9898   bool IsCPUSpecificCPUDispatchMVType =
9899       MVType == MultiVersionKind::CPUDispatch ||
9900       MVType == MultiVersionKind::CPUSpecific;
9901 
9902   // For now, disallow all other attributes.  These should be opt-in, but
9903   // an analysis of all of them is a future FIXME.
9904   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9905     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9906         << IsCPUSpecificCPUDispatchMVType;
9907     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9908     return true;
9909   }
9910 
9911   if (HasNonMultiVersionAttributes(NewFD, MVType))
9912     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9913            << IsCPUSpecificCPUDispatchMVType;
9914 
9915   // Only allow transition to MultiVersion if it hasn't been used.
9916   if (OldFD && CausesMV && OldFD->isUsed(false))
9917     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9918 
9919   return S.areMultiversionVariantFunctionsCompatible(
9920       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9921       PartialDiagnosticAt(NewFD->getLocation(),
9922                           S.PDiag(diag::note_multiversioning_caused_here)),
9923       PartialDiagnosticAt(NewFD->getLocation(),
9924                           S.PDiag(diag::err_multiversion_doesnt_support)
9925                               << IsCPUSpecificCPUDispatchMVType),
9926       PartialDiagnosticAt(NewFD->getLocation(),
9927                           S.PDiag(diag::err_multiversion_diff)),
9928       /*TemplatesSupported=*/false,
9929       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9930       /*CLinkageMayDiffer=*/false);
9931 }
9932 
9933 /// Check the validity of a multiversion function declaration that is the
9934 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9935 ///
9936 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9937 ///
9938 /// Returns true if there was an error, false otherwise.
9939 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9940                                            MultiVersionKind MVType,
9941                                            const TargetAttr *TA) {
9942   assert(MVType != MultiVersionKind::None &&
9943          "Function lacks multiversion attribute");
9944 
9945   // Target only causes MV if it is default, otherwise this is a normal
9946   // function.
9947   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9948     return false;
9949 
9950   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9951     FD->setInvalidDecl();
9952     return true;
9953   }
9954 
9955   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9956     FD->setInvalidDecl();
9957     return true;
9958   }
9959 
9960   FD->setIsMultiVersion();
9961   return false;
9962 }
9963 
9964 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9965   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9966     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9967       return true;
9968   }
9969 
9970   return false;
9971 }
9972 
9973 static bool CheckTargetCausesMultiVersioning(
9974     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9975     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9976     LookupResult &Previous) {
9977   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9978   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9979   // Sort order doesn't matter, it just needs to be consistent.
9980   llvm::sort(NewParsed.Features);
9981 
9982   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9983   // to change, this is a simple redeclaration.
9984   if (!NewTA->isDefaultVersion() &&
9985       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9986     return false;
9987 
9988   // Otherwise, this decl causes MultiVersioning.
9989   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9990     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9991     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9992     NewFD->setInvalidDecl();
9993     return true;
9994   }
9995 
9996   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9997                                        MultiVersionKind::Target)) {
9998     NewFD->setInvalidDecl();
9999     return true;
10000   }
10001 
10002   if (CheckMultiVersionValue(S, NewFD)) {
10003     NewFD->setInvalidDecl();
10004     return true;
10005   }
10006 
10007   // If this is 'default', permit the forward declaration.
10008   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10009     Redeclaration = true;
10010     OldDecl = OldFD;
10011     OldFD->setIsMultiVersion();
10012     NewFD->setIsMultiVersion();
10013     return false;
10014   }
10015 
10016   if (CheckMultiVersionValue(S, OldFD)) {
10017     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10018     NewFD->setInvalidDecl();
10019     return true;
10020   }
10021 
10022   TargetAttr::ParsedTargetAttr OldParsed =
10023       OldTA->parse(std::less<std::string>());
10024 
10025   if (OldParsed == NewParsed) {
10026     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10027     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10028     NewFD->setInvalidDecl();
10029     return true;
10030   }
10031 
10032   for (const auto *FD : OldFD->redecls()) {
10033     const auto *CurTA = FD->getAttr<TargetAttr>();
10034     // We allow forward declarations before ANY multiversioning attributes, but
10035     // nothing after the fact.
10036     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10037         (!CurTA || CurTA->isInherited())) {
10038       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10039           << 0;
10040       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10041       NewFD->setInvalidDecl();
10042       return true;
10043     }
10044   }
10045 
10046   OldFD->setIsMultiVersion();
10047   NewFD->setIsMultiVersion();
10048   Redeclaration = false;
10049   MergeTypeWithPrevious = false;
10050   OldDecl = nullptr;
10051   Previous.clear();
10052   return false;
10053 }
10054 
10055 /// Check the validity of a new function declaration being added to an existing
10056 /// multiversioned declaration collection.
10057 static bool CheckMultiVersionAdditionalDecl(
10058     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10059     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10060     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10061     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10062     LookupResult &Previous) {
10063 
10064   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10065   // Disallow mixing of multiversioning types.
10066   if ((OldMVType == MultiVersionKind::Target &&
10067        NewMVType != MultiVersionKind::Target) ||
10068       (NewMVType == MultiVersionKind::Target &&
10069        OldMVType != MultiVersionKind::Target)) {
10070     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10071     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10072     NewFD->setInvalidDecl();
10073     return true;
10074   }
10075 
10076   TargetAttr::ParsedTargetAttr NewParsed;
10077   if (NewTA) {
10078     NewParsed = NewTA->parse();
10079     llvm::sort(NewParsed.Features);
10080   }
10081 
10082   bool UseMemberUsingDeclRules =
10083       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10084 
10085   // Next, check ALL non-overloads to see if this is a redeclaration of a
10086   // previous member of the MultiVersion set.
10087   for (NamedDecl *ND : Previous) {
10088     FunctionDecl *CurFD = ND->getAsFunction();
10089     if (!CurFD)
10090       continue;
10091     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10092       continue;
10093 
10094     if (NewMVType == MultiVersionKind::Target) {
10095       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10096       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10097         NewFD->setIsMultiVersion();
10098         Redeclaration = true;
10099         OldDecl = ND;
10100         return false;
10101       }
10102 
10103       TargetAttr::ParsedTargetAttr CurParsed =
10104           CurTA->parse(std::less<std::string>());
10105       if (CurParsed == NewParsed) {
10106         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10107         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10108         NewFD->setInvalidDecl();
10109         return true;
10110       }
10111     } else {
10112       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10113       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10114       // Handle CPUDispatch/CPUSpecific versions.
10115       // Only 1 CPUDispatch function is allowed, this will make it go through
10116       // the redeclaration errors.
10117       if (NewMVType == MultiVersionKind::CPUDispatch &&
10118           CurFD->hasAttr<CPUDispatchAttr>()) {
10119         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10120             std::equal(
10121                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10122                 NewCPUDisp->cpus_begin(),
10123                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10124                   return Cur->getName() == New->getName();
10125                 })) {
10126           NewFD->setIsMultiVersion();
10127           Redeclaration = true;
10128           OldDecl = ND;
10129           return false;
10130         }
10131 
10132         // If the declarations don't match, this is an error condition.
10133         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10134         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10135         NewFD->setInvalidDecl();
10136         return true;
10137       }
10138       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10139 
10140         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10141             std::equal(
10142                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10143                 NewCPUSpec->cpus_begin(),
10144                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10145                   return Cur->getName() == New->getName();
10146                 })) {
10147           NewFD->setIsMultiVersion();
10148           Redeclaration = true;
10149           OldDecl = ND;
10150           return false;
10151         }
10152 
10153         // Only 1 version of CPUSpecific is allowed for each CPU.
10154         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10155           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10156             if (CurII == NewII) {
10157               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10158                   << NewII;
10159               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10160               NewFD->setInvalidDecl();
10161               return true;
10162             }
10163           }
10164         }
10165       }
10166       // If the two decls aren't the same MVType, there is no possible error
10167       // condition.
10168     }
10169   }
10170 
10171   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10172   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10173   // handled in the attribute adding step.
10174   if (NewMVType == MultiVersionKind::Target &&
10175       CheckMultiVersionValue(S, NewFD)) {
10176     NewFD->setInvalidDecl();
10177     return true;
10178   }
10179 
10180   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10181                                        !OldFD->isMultiVersion(), NewMVType)) {
10182     NewFD->setInvalidDecl();
10183     return true;
10184   }
10185 
10186   // Permit forward declarations in the case where these two are compatible.
10187   if (!OldFD->isMultiVersion()) {
10188     OldFD->setIsMultiVersion();
10189     NewFD->setIsMultiVersion();
10190     Redeclaration = true;
10191     OldDecl = OldFD;
10192     return false;
10193   }
10194 
10195   NewFD->setIsMultiVersion();
10196   Redeclaration = false;
10197   MergeTypeWithPrevious = false;
10198   OldDecl = nullptr;
10199   Previous.clear();
10200   return false;
10201 }
10202 
10203 
10204 /// Check the validity of a mulitversion function declaration.
10205 /// Also sets the multiversion'ness' of the function itself.
10206 ///
10207 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10208 ///
10209 /// Returns true if there was an error, false otherwise.
10210 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10211                                       bool &Redeclaration, NamedDecl *&OldDecl,
10212                                       bool &MergeTypeWithPrevious,
10213                                       LookupResult &Previous) {
10214   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10215   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10216   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10217 
10218   // Mixing Multiversioning types is prohibited.
10219   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10220       (NewCPUDisp && NewCPUSpec)) {
10221     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10222     NewFD->setInvalidDecl();
10223     return true;
10224   }
10225 
10226   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10227 
10228   // Main isn't allowed to become a multiversion function, however it IS
10229   // permitted to have 'main' be marked with the 'target' optimization hint.
10230   if (NewFD->isMain()) {
10231     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10232         MVType == MultiVersionKind::CPUDispatch ||
10233         MVType == MultiVersionKind::CPUSpecific) {
10234       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10235       NewFD->setInvalidDecl();
10236       return true;
10237     }
10238     return false;
10239   }
10240 
10241   if (!OldDecl || !OldDecl->getAsFunction() ||
10242       OldDecl->getDeclContext()->getRedeclContext() !=
10243           NewFD->getDeclContext()->getRedeclContext()) {
10244     // If there's no previous declaration, AND this isn't attempting to cause
10245     // multiversioning, this isn't an error condition.
10246     if (MVType == MultiVersionKind::None)
10247       return false;
10248     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10249   }
10250 
10251   FunctionDecl *OldFD = OldDecl->getAsFunction();
10252 
10253   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10254     return false;
10255 
10256   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10257     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10258         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10259     NewFD->setInvalidDecl();
10260     return true;
10261   }
10262 
10263   // Handle the target potentially causes multiversioning case.
10264   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10265     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10266                                             Redeclaration, OldDecl,
10267                                             MergeTypeWithPrevious, Previous);
10268 
10269   // At this point, we have a multiversion function decl (in OldFD) AND an
10270   // appropriate attribute in the current function decl.  Resolve that these are
10271   // still compatible with previous declarations.
10272   return CheckMultiVersionAdditionalDecl(
10273       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10274       OldDecl, MergeTypeWithPrevious, Previous);
10275 }
10276 
10277 /// Perform semantic checking of a new function declaration.
10278 ///
10279 /// Performs semantic analysis of the new function declaration
10280 /// NewFD. This routine performs all semantic checking that does not
10281 /// require the actual declarator involved in the declaration, and is
10282 /// used both for the declaration of functions as they are parsed
10283 /// (called via ActOnDeclarator) and for the declaration of functions
10284 /// that have been instantiated via C++ template instantiation (called
10285 /// via InstantiateDecl).
10286 ///
10287 /// \param IsMemberSpecialization whether this new function declaration is
10288 /// a member specialization (that replaces any definition provided by the
10289 /// previous declaration).
10290 ///
10291 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10292 ///
10293 /// \returns true if the function declaration is a redeclaration.
10294 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10295                                     LookupResult &Previous,
10296                                     bool IsMemberSpecialization) {
10297   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10298          "Variably modified return types are not handled here");
10299 
10300   // Determine whether the type of this function should be merged with
10301   // a previous visible declaration. This never happens for functions in C++,
10302   // and always happens in C if the previous declaration was visible.
10303   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10304                                !Previous.isShadowed();
10305 
10306   bool Redeclaration = false;
10307   NamedDecl *OldDecl = nullptr;
10308   bool MayNeedOverloadableChecks = false;
10309 
10310   // Merge or overload the declaration with an existing declaration of
10311   // the same name, if appropriate.
10312   if (!Previous.empty()) {
10313     // Determine whether NewFD is an overload of PrevDecl or
10314     // a declaration that requires merging. If it's an overload,
10315     // there's no more work to do here; we'll just add the new
10316     // function to the scope.
10317     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10318       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10319       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10320         Redeclaration = true;
10321         OldDecl = Candidate;
10322       }
10323     } else {
10324       MayNeedOverloadableChecks = true;
10325       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10326                             /*NewIsUsingDecl*/ false)) {
10327       case Ovl_Match:
10328         Redeclaration = true;
10329         break;
10330 
10331       case Ovl_NonFunction:
10332         Redeclaration = true;
10333         break;
10334 
10335       case Ovl_Overload:
10336         Redeclaration = false;
10337         break;
10338       }
10339     }
10340   }
10341 
10342   // Check for a previous extern "C" declaration with this name.
10343   if (!Redeclaration &&
10344       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10345     if (!Previous.empty()) {
10346       // This is an extern "C" declaration with the same name as a previous
10347       // declaration, and thus redeclares that entity...
10348       Redeclaration = true;
10349       OldDecl = Previous.getFoundDecl();
10350       MergeTypeWithPrevious = false;
10351 
10352       // ... except in the presence of __attribute__((overloadable)).
10353       if (OldDecl->hasAttr<OverloadableAttr>() ||
10354           NewFD->hasAttr<OverloadableAttr>()) {
10355         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10356           MayNeedOverloadableChecks = true;
10357           Redeclaration = false;
10358           OldDecl = nullptr;
10359         }
10360       }
10361     }
10362   }
10363 
10364   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10365                                 MergeTypeWithPrevious, Previous))
10366     return Redeclaration;
10367 
10368   // C++11 [dcl.constexpr]p8:
10369   //   A constexpr specifier for a non-static member function that is not
10370   //   a constructor declares that member function to be const.
10371   //
10372   // This needs to be delayed until we know whether this is an out-of-line
10373   // definition of a static member function.
10374   //
10375   // This rule is not present in C++1y, so we produce a backwards
10376   // compatibility warning whenever it happens in C++11.
10377   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10378   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10379       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10380       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10381     CXXMethodDecl *OldMD = nullptr;
10382     if (OldDecl)
10383       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10384     if (!OldMD || !OldMD->isStatic()) {
10385       const FunctionProtoType *FPT =
10386         MD->getType()->castAs<FunctionProtoType>();
10387       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10388       EPI.TypeQuals.addConst();
10389       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10390                                           FPT->getParamTypes(), EPI));
10391 
10392       // Warn that we did this, if we're not performing template instantiation.
10393       // In that case, we'll have warned already when the template was defined.
10394       if (!inTemplateInstantiation()) {
10395         SourceLocation AddConstLoc;
10396         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10397                 .IgnoreParens().getAs<FunctionTypeLoc>())
10398           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10399 
10400         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10401           << FixItHint::CreateInsertion(AddConstLoc, " const");
10402       }
10403     }
10404   }
10405 
10406   if (Redeclaration) {
10407     // NewFD and OldDecl represent declarations that need to be
10408     // merged.
10409     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10410       NewFD->setInvalidDecl();
10411       return Redeclaration;
10412     }
10413 
10414     Previous.clear();
10415     Previous.addDecl(OldDecl);
10416 
10417     if (FunctionTemplateDecl *OldTemplateDecl =
10418             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10419       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10420       FunctionTemplateDecl *NewTemplateDecl
10421         = NewFD->getDescribedFunctionTemplate();
10422       assert(NewTemplateDecl && "Template/non-template mismatch");
10423 
10424       // The call to MergeFunctionDecl above may have created some state in
10425       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10426       // can add it as a redeclaration.
10427       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10428 
10429       NewFD->setPreviousDeclaration(OldFD);
10430       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10431       if (NewFD->isCXXClassMember()) {
10432         NewFD->setAccess(OldTemplateDecl->getAccess());
10433         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10434       }
10435 
10436       // If this is an explicit specialization of a member that is a function
10437       // template, mark it as a member specialization.
10438       if (IsMemberSpecialization &&
10439           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10440         NewTemplateDecl->setMemberSpecialization();
10441         assert(OldTemplateDecl->isMemberSpecialization());
10442         // Explicit specializations of a member template do not inherit deleted
10443         // status from the parent member template that they are specializing.
10444         if (OldFD->isDeleted()) {
10445           // FIXME: This assert will not hold in the presence of modules.
10446           assert(OldFD->getCanonicalDecl() == OldFD);
10447           // FIXME: We need an update record for this AST mutation.
10448           OldFD->setDeletedAsWritten(false);
10449         }
10450       }
10451 
10452     } else {
10453       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10454         auto *OldFD = cast<FunctionDecl>(OldDecl);
10455         // This needs to happen first so that 'inline' propagates.
10456         NewFD->setPreviousDeclaration(OldFD);
10457         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10458         if (NewFD->isCXXClassMember())
10459           NewFD->setAccess(OldFD->getAccess());
10460       }
10461     }
10462   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10463              !NewFD->getAttr<OverloadableAttr>()) {
10464     assert((Previous.empty() ||
10465             llvm::any_of(Previous,
10466                          [](const NamedDecl *ND) {
10467                            return ND->hasAttr<OverloadableAttr>();
10468                          })) &&
10469            "Non-redecls shouldn't happen without overloadable present");
10470 
10471     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10472       const auto *FD = dyn_cast<FunctionDecl>(ND);
10473       return FD && !FD->hasAttr<OverloadableAttr>();
10474     });
10475 
10476     if (OtherUnmarkedIter != Previous.end()) {
10477       Diag(NewFD->getLocation(),
10478            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10479       Diag((*OtherUnmarkedIter)->getLocation(),
10480            diag::note_attribute_overloadable_prev_overload)
10481           << false;
10482 
10483       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10484     }
10485   }
10486 
10487   // Semantic checking for this function declaration (in isolation).
10488 
10489   if (getLangOpts().CPlusPlus) {
10490     // C++-specific checks.
10491     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10492       CheckConstructor(Constructor);
10493     } else if (CXXDestructorDecl *Destructor =
10494                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10495       CXXRecordDecl *Record = Destructor->getParent();
10496       QualType ClassType = Context.getTypeDeclType(Record);
10497 
10498       // FIXME: Shouldn't we be able to perform this check even when the class
10499       // type is dependent? Both gcc and edg can handle that.
10500       if (!ClassType->isDependentType()) {
10501         DeclarationName Name
10502           = Context.DeclarationNames.getCXXDestructorName(
10503                                         Context.getCanonicalType(ClassType));
10504         if (NewFD->getDeclName() != Name) {
10505           Diag(NewFD->getLocation(), diag::err_destructor_name);
10506           NewFD->setInvalidDecl();
10507           return Redeclaration;
10508         }
10509       }
10510     } else if (CXXConversionDecl *Conversion
10511                = dyn_cast<CXXConversionDecl>(NewFD)) {
10512       ActOnConversionDeclarator(Conversion);
10513     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10514       if (auto *TD = Guide->getDescribedFunctionTemplate())
10515         CheckDeductionGuideTemplate(TD);
10516 
10517       // A deduction guide is not on the list of entities that can be
10518       // explicitly specialized.
10519       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10520         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10521             << /*explicit specialization*/ 1;
10522     }
10523 
10524     // Find any virtual functions that this function overrides.
10525     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10526       if (!Method->isFunctionTemplateSpecialization() &&
10527           !Method->getDescribedFunctionTemplate() &&
10528           Method->isCanonicalDecl()) {
10529         if (AddOverriddenMethods(Method->getParent(), Method)) {
10530           // If the function was marked as "static", we have a problem.
10531           if (NewFD->getStorageClass() == SC_Static) {
10532             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10533           }
10534         }
10535       }
10536 
10537       if (Method->isStatic())
10538         checkThisInStaticMemberFunctionType(Method);
10539     }
10540 
10541     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10542     if (NewFD->isOverloadedOperator() &&
10543         CheckOverloadedOperatorDeclaration(NewFD)) {
10544       NewFD->setInvalidDecl();
10545       return Redeclaration;
10546     }
10547 
10548     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10549     if (NewFD->getLiteralIdentifier() &&
10550         CheckLiteralOperatorDeclaration(NewFD)) {
10551       NewFD->setInvalidDecl();
10552       return Redeclaration;
10553     }
10554 
10555     // In C++, check default arguments now that we have merged decls. Unless
10556     // the lexical context is the class, because in this case this is done
10557     // during delayed parsing anyway.
10558     if (!CurContext->isRecord())
10559       CheckCXXDefaultArguments(NewFD);
10560 
10561     // If this function declares a builtin function, check the type of this
10562     // declaration against the expected type for the builtin.
10563     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10564       ASTContext::GetBuiltinTypeError Error;
10565       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10566       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10567       // If the type of the builtin differs only in its exception
10568       // specification, that's OK.
10569       // FIXME: If the types do differ in this way, it would be better to
10570       // retain the 'noexcept' form of the type.
10571       if (!T.isNull() &&
10572           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10573                                                             NewFD->getType()))
10574         // The type of this function differs from the type of the builtin,
10575         // so forget about the builtin entirely.
10576         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10577     }
10578 
10579     // If this function is declared as being extern "C", then check to see if
10580     // the function returns a UDT (class, struct, or union type) that is not C
10581     // compatible, and if it does, warn the user.
10582     // But, issue any diagnostic on the first declaration only.
10583     if (Previous.empty() && NewFD->isExternC()) {
10584       QualType R = NewFD->getReturnType();
10585       if (R->isIncompleteType() && !R->isVoidType())
10586         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10587             << NewFD << R;
10588       else if (!R.isPODType(Context) && !R->isVoidType() &&
10589                !R->isObjCObjectPointerType())
10590         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10591     }
10592 
10593     // C++1z [dcl.fct]p6:
10594     //   [...] whether the function has a non-throwing exception-specification
10595     //   [is] part of the function type
10596     //
10597     // This results in an ABI break between C++14 and C++17 for functions whose
10598     // declared type includes an exception-specification in a parameter or
10599     // return type. (Exception specifications on the function itself are OK in
10600     // most cases, and exception specifications are not permitted in most other
10601     // contexts where they could make it into a mangling.)
10602     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10603       auto HasNoexcept = [&](QualType T) -> bool {
10604         // Strip off declarator chunks that could be between us and a function
10605         // type. We don't need to look far, exception specifications are very
10606         // restricted prior to C++17.
10607         if (auto *RT = T->getAs<ReferenceType>())
10608           T = RT->getPointeeType();
10609         else if (T->isAnyPointerType())
10610           T = T->getPointeeType();
10611         else if (auto *MPT = T->getAs<MemberPointerType>())
10612           T = MPT->getPointeeType();
10613         if (auto *FPT = T->getAs<FunctionProtoType>())
10614           if (FPT->isNothrow())
10615             return true;
10616         return false;
10617       };
10618 
10619       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10620       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10621       for (QualType T : FPT->param_types())
10622         AnyNoexcept |= HasNoexcept(T);
10623       if (AnyNoexcept)
10624         Diag(NewFD->getLocation(),
10625              diag::warn_cxx17_compat_exception_spec_in_signature)
10626             << NewFD;
10627     }
10628 
10629     if (!Redeclaration && LangOpts.CUDA)
10630       checkCUDATargetOverload(NewFD, Previous);
10631   }
10632   return Redeclaration;
10633 }
10634 
10635 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10636   // C++11 [basic.start.main]p3:
10637   //   A program that [...] declares main to be inline, static or
10638   //   constexpr is ill-formed.
10639   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10640   //   appear in a declaration of main.
10641   // static main is not an error under C99, but we should warn about it.
10642   // We accept _Noreturn main as an extension.
10643   if (FD->getStorageClass() == SC_Static)
10644     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10645          ? diag::err_static_main : diag::warn_static_main)
10646       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10647   if (FD->isInlineSpecified())
10648     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10649       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10650   if (DS.isNoreturnSpecified()) {
10651     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10652     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10653     Diag(NoreturnLoc, diag::ext_noreturn_main);
10654     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10655       << FixItHint::CreateRemoval(NoreturnRange);
10656   }
10657   if (FD->isConstexpr()) {
10658     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10659         << FD->isConsteval()
10660         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10661     FD->setConstexprKind(CSK_unspecified);
10662   }
10663 
10664   if (getLangOpts().OpenCL) {
10665     Diag(FD->getLocation(), diag::err_opencl_no_main)
10666         << FD->hasAttr<OpenCLKernelAttr>();
10667     FD->setInvalidDecl();
10668     return;
10669   }
10670 
10671   QualType T = FD->getType();
10672   assert(T->isFunctionType() && "function decl is not of function type");
10673   const FunctionType* FT = T->castAs<FunctionType>();
10674 
10675   // Set default calling convention for main()
10676   if (FT->getCallConv() != CC_C) {
10677     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10678     FD->setType(QualType(FT, 0));
10679     T = Context.getCanonicalType(FD->getType());
10680   }
10681 
10682   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10683     // In C with GNU extensions we allow main() to have non-integer return
10684     // type, but we should warn about the extension, and we disable the
10685     // implicit-return-zero rule.
10686 
10687     // GCC in C mode accepts qualified 'int'.
10688     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10689       FD->setHasImplicitReturnZero(true);
10690     else {
10691       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10692       SourceRange RTRange = FD->getReturnTypeSourceRange();
10693       if (RTRange.isValid())
10694         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10695             << FixItHint::CreateReplacement(RTRange, "int");
10696     }
10697   } else {
10698     // In C and C++, main magically returns 0 if you fall off the end;
10699     // set the flag which tells us that.
10700     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10701 
10702     // All the standards say that main() should return 'int'.
10703     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10704       FD->setHasImplicitReturnZero(true);
10705     else {
10706       // Otherwise, this is just a flat-out error.
10707       SourceRange RTRange = FD->getReturnTypeSourceRange();
10708       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10709           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10710                                 : FixItHint());
10711       FD->setInvalidDecl(true);
10712     }
10713   }
10714 
10715   // Treat protoless main() as nullary.
10716   if (isa<FunctionNoProtoType>(FT)) return;
10717 
10718   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10719   unsigned nparams = FTP->getNumParams();
10720   assert(FD->getNumParams() == nparams);
10721 
10722   bool HasExtraParameters = (nparams > 3);
10723 
10724   if (FTP->isVariadic()) {
10725     Diag(FD->getLocation(), diag::ext_variadic_main);
10726     // FIXME: if we had information about the location of the ellipsis, we
10727     // could add a FixIt hint to remove it as a parameter.
10728   }
10729 
10730   // Darwin passes an undocumented fourth argument of type char**.  If
10731   // other platforms start sprouting these, the logic below will start
10732   // getting shifty.
10733   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10734     HasExtraParameters = false;
10735 
10736   if (HasExtraParameters) {
10737     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10738     FD->setInvalidDecl(true);
10739     nparams = 3;
10740   }
10741 
10742   // FIXME: a lot of the following diagnostics would be improved
10743   // if we had some location information about types.
10744 
10745   QualType CharPP =
10746     Context.getPointerType(Context.getPointerType(Context.CharTy));
10747   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10748 
10749   for (unsigned i = 0; i < nparams; ++i) {
10750     QualType AT = FTP->getParamType(i);
10751 
10752     bool mismatch = true;
10753 
10754     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10755       mismatch = false;
10756     else if (Expected[i] == CharPP) {
10757       // As an extension, the following forms are okay:
10758       //   char const **
10759       //   char const * const *
10760       //   char * const *
10761 
10762       QualifierCollector qs;
10763       const PointerType* PT;
10764       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10765           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10766           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10767                               Context.CharTy)) {
10768         qs.removeConst();
10769         mismatch = !qs.empty();
10770       }
10771     }
10772 
10773     if (mismatch) {
10774       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10775       // TODO: suggest replacing given type with expected type
10776       FD->setInvalidDecl(true);
10777     }
10778   }
10779 
10780   if (nparams == 1 && !FD->isInvalidDecl()) {
10781     Diag(FD->getLocation(), diag::warn_main_one_arg);
10782   }
10783 
10784   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10785     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10786     FD->setInvalidDecl();
10787   }
10788 }
10789 
10790 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10791   QualType T = FD->getType();
10792   assert(T->isFunctionType() && "function decl is not of function type");
10793   const FunctionType *FT = T->castAs<FunctionType>();
10794 
10795   // Set an implicit return of 'zero' if the function can return some integral,
10796   // enumeration, pointer or nullptr type.
10797   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10798       FT->getReturnType()->isAnyPointerType() ||
10799       FT->getReturnType()->isNullPtrType())
10800     // DllMain is exempt because a return value of zero means it failed.
10801     if (FD->getName() != "DllMain")
10802       FD->setHasImplicitReturnZero(true);
10803 
10804   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10805     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10806     FD->setInvalidDecl();
10807   }
10808 }
10809 
10810 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10811   // FIXME: Need strict checking.  In C89, we need to check for
10812   // any assignment, increment, decrement, function-calls, or
10813   // commas outside of a sizeof.  In C99, it's the same list,
10814   // except that the aforementioned are allowed in unevaluated
10815   // expressions.  Everything else falls under the
10816   // "may accept other forms of constant expressions" exception.
10817   // (We never end up here for C++, so the constant expression
10818   // rules there don't matter.)
10819   const Expr *Culprit;
10820   if (Init->isConstantInitializer(Context, false, &Culprit))
10821     return false;
10822   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10823     << Culprit->getSourceRange();
10824   return true;
10825 }
10826 
10827 namespace {
10828   // Visits an initialization expression to see if OrigDecl is evaluated in
10829   // its own initialization and throws a warning if it does.
10830   class SelfReferenceChecker
10831       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10832     Sema &S;
10833     Decl *OrigDecl;
10834     bool isRecordType;
10835     bool isPODType;
10836     bool isReferenceType;
10837 
10838     bool isInitList;
10839     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10840 
10841   public:
10842     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10843 
10844     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10845                                                     S(S), OrigDecl(OrigDecl) {
10846       isPODType = false;
10847       isRecordType = false;
10848       isReferenceType = false;
10849       isInitList = false;
10850       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10851         isPODType = VD->getType().isPODType(S.Context);
10852         isRecordType = VD->getType()->isRecordType();
10853         isReferenceType = VD->getType()->isReferenceType();
10854       }
10855     }
10856 
10857     // For most expressions, just call the visitor.  For initializer lists,
10858     // track the index of the field being initialized since fields are
10859     // initialized in order allowing use of previously initialized fields.
10860     void CheckExpr(Expr *E) {
10861       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10862       if (!InitList) {
10863         Visit(E);
10864         return;
10865       }
10866 
10867       // Track and increment the index here.
10868       isInitList = true;
10869       InitFieldIndex.push_back(0);
10870       for (auto Child : InitList->children()) {
10871         CheckExpr(cast<Expr>(Child));
10872         ++InitFieldIndex.back();
10873       }
10874       InitFieldIndex.pop_back();
10875     }
10876 
10877     // Returns true if MemberExpr is checked and no further checking is needed.
10878     // Returns false if additional checking is required.
10879     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10880       llvm::SmallVector<FieldDecl*, 4> Fields;
10881       Expr *Base = E;
10882       bool ReferenceField = false;
10883 
10884       // Get the field members used.
10885       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10886         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10887         if (!FD)
10888           return false;
10889         Fields.push_back(FD);
10890         if (FD->getType()->isReferenceType())
10891           ReferenceField = true;
10892         Base = ME->getBase()->IgnoreParenImpCasts();
10893       }
10894 
10895       // Keep checking only if the base Decl is the same.
10896       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10897       if (!DRE || DRE->getDecl() != OrigDecl)
10898         return false;
10899 
10900       // A reference field can be bound to an unininitialized field.
10901       if (CheckReference && !ReferenceField)
10902         return true;
10903 
10904       // Convert FieldDecls to their index number.
10905       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10906       for (const FieldDecl *I : llvm::reverse(Fields))
10907         UsedFieldIndex.push_back(I->getFieldIndex());
10908 
10909       // See if a warning is needed by checking the first difference in index
10910       // numbers.  If field being used has index less than the field being
10911       // initialized, then the use is safe.
10912       for (auto UsedIter = UsedFieldIndex.begin(),
10913                 UsedEnd = UsedFieldIndex.end(),
10914                 OrigIter = InitFieldIndex.begin(),
10915                 OrigEnd = InitFieldIndex.end();
10916            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10917         if (*UsedIter < *OrigIter)
10918           return true;
10919         if (*UsedIter > *OrigIter)
10920           break;
10921       }
10922 
10923       // TODO: Add a different warning which will print the field names.
10924       HandleDeclRefExpr(DRE);
10925       return true;
10926     }
10927 
10928     // For most expressions, the cast is directly above the DeclRefExpr.
10929     // For conditional operators, the cast can be outside the conditional
10930     // operator if both expressions are DeclRefExpr's.
10931     void HandleValue(Expr *E) {
10932       E = E->IgnoreParens();
10933       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10934         HandleDeclRefExpr(DRE);
10935         return;
10936       }
10937 
10938       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10939         Visit(CO->getCond());
10940         HandleValue(CO->getTrueExpr());
10941         HandleValue(CO->getFalseExpr());
10942         return;
10943       }
10944 
10945       if (BinaryConditionalOperator *BCO =
10946               dyn_cast<BinaryConditionalOperator>(E)) {
10947         Visit(BCO->getCond());
10948         HandleValue(BCO->getFalseExpr());
10949         return;
10950       }
10951 
10952       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10953         HandleValue(OVE->getSourceExpr());
10954         return;
10955       }
10956 
10957       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10958         if (BO->getOpcode() == BO_Comma) {
10959           Visit(BO->getLHS());
10960           HandleValue(BO->getRHS());
10961           return;
10962         }
10963       }
10964 
10965       if (isa<MemberExpr>(E)) {
10966         if (isInitList) {
10967           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10968                                       false /*CheckReference*/))
10969             return;
10970         }
10971 
10972         Expr *Base = E->IgnoreParenImpCasts();
10973         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10974           // Check for static member variables and don't warn on them.
10975           if (!isa<FieldDecl>(ME->getMemberDecl()))
10976             return;
10977           Base = ME->getBase()->IgnoreParenImpCasts();
10978         }
10979         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10980           HandleDeclRefExpr(DRE);
10981         return;
10982       }
10983 
10984       Visit(E);
10985     }
10986 
10987     // Reference types not handled in HandleValue are handled here since all
10988     // uses of references are bad, not just r-value uses.
10989     void VisitDeclRefExpr(DeclRefExpr *E) {
10990       if (isReferenceType)
10991         HandleDeclRefExpr(E);
10992     }
10993 
10994     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10995       if (E->getCastKind() == CK_LValueToRValue) {
10996         HandleValue(E->getSubExpr());
10997         return;
10998       }
10999 
11000       Inherited::VisitImplicitCastExpr(E);
11001     }
11002 
11003     void VisitMemberExpr(MemberExpr *E) {
11004       if (isInitList) {
11005         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11006           return;
11007       }
11008 
11009       // Don't warn on arrays since they can be treated as pointers.
11010       if (E->getType()->canDecayToPointerType()) return;
11011 
11012       // Warn when a non-static method call is followed by non-static member
11013       // field accesses, which is followed by a DeclRefExpr.
11014       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11015       bool Warn = (MD && !MD->isStatic());
11016       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11017       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11018         if (!isa<FieldDecl>(ME->getMemberDecl()))
11019           Warn = false;
11020         Base = ME->getBase()->IgnoreParenImpCasts();
11021       }
11022 
11023       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11024         if (Warn)
11025           HandleDeclRefExpr(DRE);
11026         return;
11027       }
11028 
11029       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11030       // Visit that expression.
11031       Visit(Base);
11032     }
11033 
11034     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11035       Expr *Callee = E->getCallee();
11036 
11037       if (isa<UnresolvedLookupExpr>(Callee))
11038         return Inherited::VisitCXXOperatorCallExpr(E);
11039 
11040       Visit(Callee);
11041       for (auto Arg: E->arguments())
11042         HandleValue(Arg->IgnoreParenImpCasts());
11043     }
11044 
11045     void VisitUnaryOperator(UnaryOperator *E) {
11046       // For POD record types, addresses of its own members are well-defined.
11047       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11048           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11049         if (!isPODType)
11050           HandleValue(E->getSubExpr());
11051         return;
11052       }
11053 
11054       if (E->isIncrementDecrementOp()) {
11055         HandleValue(E->getSubExpr());
11056         return;
11057       }
11058 
11059       Inherited::VisitUnaryOperator(E);
11060     }
11061 
11062     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11063 
11064     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11065       if (E->getConstructor()->isCopyConstructor()) {
11066         Expr *ArgExpr = E->getArg(0);
11067         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11068           if (ILE->getNumInits() == 1)
11069             ArgExpr = ILE->getInit(0);
11070         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11071           if (ICE->getCastKind() == CK_NoOp)
11072             ArgExpr = ICE->getSubExpr();
11073         HandleValue(ArgExpr);
11074         return;
11075       }
11076       Inherited::VisitCXXConstructExpr(E);
11077     }
11078 
11079     void VisitCallExpr(CallExpr *E) {
11080       // Treat std::move as a use.
11081       if (E->isCallToStdMove()) {
11082         HandleValue(E->getArg(0));
11083         return;
11084       }
11085 
11086       Inherited::VisitCallExpr(E);
11087     }
11088 
11089     void VisitBinaryOperator(BinaryOperator *E) {
11090       if (E->isCompoundAssignmentOp()) {
11091         HandleValue(E->getLHS());
11092         Visit(E->getRHS());
11093         return;
11094       }
11095 
11096       Inherited::VisitBinaryOperator(E);
11097     }
11098 
11099     // A custom visitor for BinaryConditionalOperator is needed because the
11100     // regular visitor would check the condition and true expression separately
11101     // but both point to the same place giving duplicate diagnostics.
11102     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11103       Visit(E->getCond());
11104       Visit(E->getFalseExpr());
11105     }
11106 
11107     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11108       Decl* ReferenceDecl = DRE->getDecl();
11109       if (OrigDecl != ReferenceDecl) return;
11110       unsigned diag;
11111       if (isReferenceType) {
11112         diag = diag::warn_uninit_self_reference_in_reference_init;
11113       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11114         diag = diag::warn_static_self_reference_in_init;
11115       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11116                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11117                  DRE->getDecl()->getType()->isRecordType()) {
11118         diag = diag::warn_uninit_self_reference_in_init;
11119       } else {
11120         // Local variables will be handled by the CFG analysis.
11121         return;
11122       }
11123 
11124       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11125                             S.PDiag(diag)
11126                                 << DRE->getDecl() << OrigDecl->getLocation()
11127                                 << DRE->getSourceRange());
11128     }
11129   };
11130 
11131   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11132   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11133                                  bool DirectInit) {
11134     // Parameters arguments are occassionially constructed with itself,
11135     // for instance, in recursive functions.  Skip them.
11136     if (isa<ParmVarDecl>(OrigDecl))
11137       return;
11138 
11139     E = E->IgnoreParens();
11140 
11141     // Skip checking T a = a where T is not a record or reference type.
11142     // Doing so is a way to silence uninitialized warnings.
11143     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11144       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11145         if (ICE->getCastKind() == CK_LValueToRValue)
11146           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11147             if (DRE->getDecl() == OrigDecl)
11148               return;
11149 
11150     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11151   }
11152 } // end anonymous namespace
11153 
11154 namespace {
11155   // Simple wrapper to add the name of a variable or (if no variable is
11156   // available) a DeclarationName into a diagnostic.
11157   struct VarDeclOrName {
11158     VarDecl *VDecl;
11159     DeclarationName Name;
11160 
11161     friend const Sema::SemaDiagnosticBuilder &
11162     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11163       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11164     }
11165   };
11166 } // end anonymous namespace
11167 
11168 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11169                                             DeclarationName Name, QualType Type,
11170                                             TypeSourceInfo *TSI,
11171                                             SourceRange Range, bool DirectInit,
11172                                             Expr *Init) {
11173   bool IsInitCapture = !VDecl;
11174   assert((!VDecl || !VDecl->isInitCapture()) &&
11175          "init captures are expected to be deduced prior to initialization");
11176 
11177   VarDeclOrName VN{VDecl, Name};
11178 
11179   DeducedType *Deduced = Type->getContainedDeducedType();
11180   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11181 
11182   // C++11 [dcl.spec.auto]p3
11183   if (!Init) {
11184     assert(VDecl && "no init for init capture deduction?");
11185 
11186     // Except for class argument deduction, and then for an initializing
11187     // declaration only, i.e. no static at class scope or extern.
11188     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11189         VDecl->hasExternalStorage() ||
11190         VDecl->isStaticDataMember()) {
11191       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11192         << VDecl->getDeclName() << Type;
11193       return QualType();
11194     }
11195   }
11196 
11197   ArrayRef<Expr*> DeduceInits;
11198   if (Init)
11199     DeduceInits = Init;
11200 
11201   if (DirectInit) {
11202     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11203       DeduceInits = PL->exprs();
11204   }
11205 
11206   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11207     assert(VDecl && "non-auto type for init capture deduction?");
11208     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11209     InitializationKind Kind = InitializationKind::CreateForInit(
11210         VDecl->getLocation(), DirectInit, Init);
11211     // FIXME: Initialization should not be taking a mutable list of inits.
11212     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11213     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11214                                                        InitsCopy);
11215   }
11216 
11217   if (DirectInit) {
11218     if (auto *IL = dyn_cast<InitListExpr>(Init))
11219       DeduceInits = IL->inits();
11220   }
11221 
11222   // Deduction only works if we have exactly one source expression.
11223   if (DeduceInits.empty()) {
11224     // It isn't possible to write this directly, but it is possible to
11225     // end up in this situation with "auto x(some_pack...);"
11226     Diag(Init->getBeginLoc(), IsInitCapture
11227                                   ? diag::err_init_capture_no_expression
11228                                   : diag::err_auto_var_init_no_expression)
11229         << VN << Type << Range;
11230     return QualType();
11231   }
11232 
11233   if (DeduceInits.size() > 1) {
11234     Diag(DeduceInits[1]->getBeginLoc(),
11235          IsInitCapture ? diag::err_init_capture_multiple_expressions
11236                        : diag::err_auto_var_init_multiple_expressions)
11237         << VN << Type << Range;
11238     return QualType();
11239   }
11240 
11241   Expr *DeduceInit = DeduceInits[0];
11242   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11243     Diag(Init->getBeginLoc(), IsInitCapture
11244                                   ? diag::err_init_capture_paren_braces
11245                                   : diag::err_auto_var_init_paren_braces)
11246         << isa<InitListExpr>(Init) << VN << Type << Range;
11247     return QualType();
11248   }
11249 
11250   // Expressions default to 'id' when we're in a debugger.
11251   bool DefaultedAnyToId = false;
11252   if (getLangOpts().DebuggerCastResultToId &&
11253       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11254     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11255     if (Result.isInvalid()) {
11256       return QualType();
11257     }
11258     Init = Result.get();
11259     DefaultedAnyToId = true;
11260   }
11261 
11262   // C++ [dcl.decomp]p1:
11263   //   If the assignment-expression [...] has array type A and no ref-qualifier
11264   //   is present, e has type cv A
11265   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11266       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11267       DeduceInit->getType()->isConstantArrayType())
11268     return Context.getQualifiedType(DeduceInit->getType(),
11269                                     Type.getQualifiers());
11270 
11271   QualType DeducedType;
11272   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11273     if (!IsInitCapture)
11274       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11275     else if (isa<InitListExpr>(Init))
11276       Diag(Range.getBegin(),
11277            diag::err_init_capture_deduction_failure_from_init_list)
11278           << VN
11279           << (DeduceInit->getType().isNull() ? TSI->getType()
11280                                              : DeduceInit->getType())
11281           << DeduceInit->getSourceRange();
11282     else
11283       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11284           << VN << TSI->getType()
11285           << (DeduceInit->getType().isNull() ? TSI->getType()
11286                                              : DeduceInit->getType())
11287           << DeduceInit->getSourceRange();
11288   }
11289 
11290   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11291   // 'id' instead of a specific object type prevents most of our usual
11292   // checks.
11293   // We only want to warn outside of template instantiations, though:
11294   // inside a template, the 'id' could have come from a parameter.
11295   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11296       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11297     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11298     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11299   }
11300 
11301   return DeducedType;
11302 }
11303 
11304 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11305                                          Expr *Init) {
11306   QualType DeducedType = deduceVarTypeFromInitializer(
11307       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11308       VDecl->getSourceRange(), DirectInit, Init);
11309   if (DeducedType.isNull()) {
11310     VDecl->setInvalidDecl();
11311     return true;
11312   }
11313 
11314   VDecl->setType(DeducedType);
11315   assert(VDecl->isLinkageValid());
11316 
11317   // In ARC, infer lifetime.
11318   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11319     VDecl->setInvalidDecl();
11320 
11321   if (getLangOpts().OpenCL)
11322     deduceOpenCLAddressSpace(VDecl);
11323 
11324   // If this is a redeclaration, check that the type we just deduced matches
11325   // the previously declared type.
11326   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11327     // We never need to merge the type, because we cannot form an incomplete
11328     // array of auto, nor deduce such a type.
11329     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11330   }
11331 
11332   // Check the deduced type is valid for a variable declaration.
11333   CheckVariableDeclarationType(VDecl);
11334   return VDecl->isInvalidDecl();
11335 }
11336 
11337 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11338                                               SourceLocation Loc) {
11339   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11340     Init = CE->getSubExpr();
11341 
11342   QualType InitType = Init->getType();
11343   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11344           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11345          "shouldn't be called if type doesn't have a non-trivial C struct");
11346   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11347     for (auto I : ILE->inits()) {
11348       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11349           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11350         continue;
11351       SourceLocation SL = I->getExprLoc();
11352       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11353     }
11354     return;
11355   }
11356 
11357   if (isa<ImplicitValueInitExpr>(Init)) {
11358     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11359       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11360                             NTCUK_Init);
11361   } else {
11362     // Assume all other explicit initializers involving copying some existing
11363     // object.
11364     // TODO: ignore any explicit initializers where we can guarantee
11365     // copy-elision.
11366     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11367       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11368   }
11369 }
11370 
11371 namespace {
11372 
11373 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11374   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11375   // in the source code or implicitly by the compiler if it is in a union
11376   // defined in a system header and has non-trivial ObjC ownership
11377   // qualifications. We don't want those fields to participate in determining
11378   // whether the containing union is non-trivial.
11379   return FD->hasAttr<UnavailableAttr>();
11380 }
11381 
11382 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11383     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11384                                     void> {
11385   using Super =
11386       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11387                                     void>;
11388 
11389   DiagNonTrivalCUnionDefaultInitializeVisitor(
11390       QualType OrigTy, SourceLocation OrigLoc,
11391       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11392       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11393 
11394   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11395                      const FieldDecl *FD, bool InNonTrivialUnion) {
11396     if (const auto *AT = S.Context.getAsArrayType(QT))
11397       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11398                                      InNonTrivialUnion);
11399     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11400   }
11401 
11402   void visitARCStrong(QualType QT, const FieldDecl *FD,
11403                       bool InNonTrivialUnion) {
11404     if (InNonTrivialUnion)
11405       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11406           << 1 << 0 << QT << FD->getName();
11407   }
11408 
11409   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11410     if (InNonTrivialUnion)
11411       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11412           << 1 << 0 << QT << FD->getName();
11413   }
11414 
11415   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11416     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11417     if (RD->isUnion()) {
11418       if (OrigLoc.isValid()) {
11419         bool IsUnion = false;
11420         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11421           IsUnion = OrigRD->isUnion();
11422         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11423             << 0 << OrigTy << IsUnion << UseContext;
11424         // Reset OrigLoc so that this diagnostic is emitted only once.
11425         OrigLoc = SourceLocation();
11426       }
11427       InNonTrivialUnion = true;
11428     }
11429 
11430     if (InNonTrivialUnion)
11431       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11432           << 0 << 0 << QT.getUnqualifiedType() << "";
11433 
11434     for (const FieldDecl *FD : RD->fields())
11435       if (!shouldIgnoreForRecordTriviality(FD))
11436         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11437   }
11438 
11439   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11440 
11441   // The non-trivial C union type or the struct/union type that contains a
11442   // non-trivial C union.
11443   QualType OrigTy;
11444   SourceLocation OrigLoc;
11445   Sema::NonTrivialCUnionContext UseContext;
11446   Sema &S;
11447 };
11448 
11449 struct DiagNonTrivalCUnionDestructedTypeVisitor
11450     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11451   using Super =
11452       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11453 
11454   DiagNonTrivalCUnionDestructedTypeVisitor(
11455       QualType OrigTy, SourceLocation OrigLoc,
11456       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11457       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11458 
11459   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11460                      const FieldDecl *FD, bool InNonTrivialUnion) {
11461     if (const auto *AT = S.Context.getAsArrayType(QT))
11462       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11463                                      InNonTrivialUnion);
11464     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11465   }
11466 
11467   void visitARCStrong(QualType QT, const FieldDecl *FD,
11468                       bool InNonTrivialUnion) {
11469     if (InNonTrivialUnion)
11470       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11471           << 1 << 1 << QT << FD->getName();
11472   }
11473 
11474   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11475     if (InNonTrivialUnion)
11476       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11477           << 1 << 1 << QT << FD->getName();
11478   }
11479 
11480   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11481     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11482     if (RD->isUnion()) {
11483       if (OrigLoc.isValid()) {
11484         bool IsUnion = false;
11485         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11486           IsUnion = OrigRD->isUnion();
11487         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11488             << 1 << OrigTy << IsUnion << UseContext;
11489         // Reset OrigLoc so that this diagnostic is emitted only once.
11490         OrigLoc = SourceLocation();
11491       }
11492       InNonTrivialUnion = true;
11493     }
11494 
11495     if (InNonTrivialUnion)
11496       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11497           << 0 << 1 << QT.getUnqualifiedType() << "";
11498 
11499     for (const FieldDecl *FD : RD->fields())
11500       if (!shouldIgnoreForRecordTriviality(FD))
11501         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11502   }
11503 
11504   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11505   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11506                           bool InNonTrivialUnion) {}
11507 
11508   // The non-trivial C union type or the struct/union type that contains a
11509   // non-trivial C union.
11510   QualType OrigTy;
11511   SourceLocation OrigLoc;
11512   Sema::NonTrivialCUnionContext UseContext;
11513   Sema &S;
11514 };
11515 
11516 struct DiagNonTrivalCUnionCopyVisitor
11517     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11518   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11519 
11520   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11521                                  Sema::NonTrivialCUnionContext UseContext,
11522                                  Sema &S)
11523       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11524 
11525   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11526                      const FieldDecl *FD, bool InNonTrivialUnion) {
11527     if (const auto *AT = S.Context.getAsArrayType(QT))
11528       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11529                                      InNonTrivialUnion);
11530     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11531   }
11532 
11533   void visitARCStrong(QualType QT, const FieldDecl *FD,
11534                       bool InNonTrivialUnion) {
11535     if (InNonTrivialUnion)
11536       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11537           << 1 << 2 << QT << FD->getName();
11538   }
11539 
11540   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11541     if (InNonTrivialUnion)
11542       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11543           << 1 << 2 << QT << FD->getName();
11544   }
11545 
11546   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11547     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11548     if (RD->isUnion()) {
11549       if (OrigLoc.isValid()) {
11550         bool IsUnion = false;
11551         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11552           IsUnion = OrigRD->isUnion();
11553         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11554             << 2 << OrigTy << IsUnion << UseContext;
11555         // Reset OrigLoc so that this diagnostic is emitted only once.
11556         OrigLoc = SourceLocation();
11557       }
11558       InNonTrivialUnion = true;
11559     }
11560 
11561     if (InNonTrivialUnion)
11562       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11563           << 0 << 2 << QT.getUnqualifiedType() << "";
11564 
11565     for (const FieldDecl *FD : RD->fields())
11566       if (!shouldIgnoreForRecordTriviality(FD))
11567         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11568   }
11569 
11570   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11571                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11572   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11573   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11574                             bool InNonTrivialUnion) {}
11575 
11576   // The non-trivial C union type or the struct/union type that contains a
11577   // non-trivial C union.
11578   QualType OrigTy;
11579   SourceLocation OrigLoc;
11580   Sema::NonTrivialCUnionContext UseContext;
11581   Sema &S;
11582 };
11583 
11584 } // namespace
11585 
11586 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11587                                  NonTrivialCUnionContext UseContext,
11588                                  unsigned NonTrivialKind) {
11589   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11590           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11591           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11592          "shouldn't be called if type doesn't have a non-trivial C union");
11593 
11594   if ((NonTrivialKind & NTCUK_Init) &&
11595       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11596     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11597         .visit(QT, nullptr, false);
11598   if ((NonTrivialKind & NTCUK_Destruct) &&
11599       QT.hasNonTrivialToPrimitiveDestructCUnion())
11600     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11601         .visit(QT, nullptr, false);
11602   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11603     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11604         .visit(QT, nullptr, false);
11605 }
11606 
11607 /// AddInitializerToDecl - Adds the initializer Init to the
11608 /// declaration dcl. If DirectInit is true, this is C++ direct
11609 /// initialization rather than copy initialization.
11610 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11611   // If there is no declaration, there was an error parsing it.  Just ignore
11612   // the initializer.
11613   if (!RealDecl || RealDecl->isInvalidDecl()) {
11614     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11615     return;
11616   }
11617 
11618   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11619     // Pure-specifiers are handled in ActOnPureSpecifier.
11620     Diag(Method->getLocation(), diag::err_member_function_initialization)
11621       << Method->getDeclName() << Init->getSourceRange();
11622     Method->setInvalidDecl();
11623     return;
11624   }
11625 
11626   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11627   if (!VDecl) {
11628     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11629     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11630     RealDecl->setInvalidDecl();
11631     return;
11632   }
11633 
11634   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11635   if (VDecl->getType()->isUndeducedType()) {
11636     // Attempt typo correction early so that the type of the init expression can
11637     // be deduced based on the chosen correction if the original init contains a
11638     // TypoExpr.
11639     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11640     if (!Res.isUsable()) {
11641       RealDecl->setInvalidDecl();
11642       return;
11643     }
11644     Init = Res.get();
11645 
11646     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11647       return;
11648   }
11649 
11650   // dllimport cannot be used on variable definitions.
11651   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11652     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11653     VDecl->setInvalidDecl();
11654     return;
11655   }
11656 
11657   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11658     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11659     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11660     VDecl->setInvalidDecl();
11661     return;
11662   }
11663 
11664   if (!VDecl->getType()->isDependentType()) {
11665     // A definition must end up with a complete type, which means it must be
11666     // complete with the restriction that an array type might be completed by
11667     // the initializer; note that later code assumes this restriction.
11668     QualType BaseDeclType = VDecl->getType();
11669     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11670       BaseDeclType = Array->getElementType();
11671     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11672                             diag::err_typecheck_decl_incomplete_type)) {
11673       RealDecl->setInvalidDecl();
11674       return;
11675     }
11676 
11677     // The variable can not have an abstract class type.
11678     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11679                                diag::err_abstract_type_in_decl,
11680                                AbstractVariableType))
11681       VDecl->setInvalidDecl();
11682   }
11683 
11684   // If adding the initializer will turn this declaration into a definition,
11685   // and we already have a definition for this variable, diagnose or otherwise
11686   // handle the situation.
11687   VarDecl *Def;
11688   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11689       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11690       !VDecl->isThisDeclarationADemotedDefinition() &&
11691       checkVarDeclRedefinition(Def, VDecl))
11692     return;
11693 
11694   if (getLangOpts().CPlusPlus) {
11695     // C++ [class.static.data]p4
11696     //   If a static data member is of const integral or const
11697     //   enumeration type, its declaration in the class definition can
11698     //   specify a constant-initializer which shall be an integral
11699     //   constant expression (5.19). In that case, the member can appear
11700     //   in integral constant expressions. The member shall still be
11701     //   defined in a namespace scope if it is used in the program and the
11702     //   namespace scope definition shall not contain an initializer.
11703     //
11704     // We already performed a redefinition check above, but for static
11705     // data members we also need to check whether there was an in-class
11706     // declaration with an initializer.
11707     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11708       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11709           << VDecl->getDeclName();
11710       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11711            diag::note_previous_initializer)
11712           << 0;
11713       return;
11714     }
11715 
11716     if (VDecl->hasLocalStorage())
11717       setFunctionHasBranchProtectedScope();
11718 
11719     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11720       VDecl->setInvalidDecl();
11721       return;
11722     }
11723   }
11724 
11725   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11726   // a kernel function cannot be initialized."
11727   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11728     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11729     VDecl->setInvalidDecl();
11730     return;
11731   }
11732 
11733   // Get the decls type and save a reference for later, since
11734   // CheckInitializerTypes may change it.
11735   QualType DclT = VDecl->getType(), SavT = DclT;
11736 
11737   // Expressions default to 'id' when we're in a debugger
11738   // and we are assigning it to a variable of Objective-C pointer type.
11739   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11740       Init->getType() == Context.UnknownAnyTy) {
11741     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11742     if (Result.isInvalid()) {
11743       VDecl->setInvalidDecl();
11744       return;
11745     }
11746     Init = Result.get();
11747   }
11748 
11749   // Perform the initialization.
11750   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11751   if (!VDecl->isInvalidDecl()) {
11752     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11753     InitializationKind Kind = InitializationKind::CreateForInit(
11754         VDecl->getLocation(), DirectInit, Init);
11755 
11756     MultiExprArg Args = Init;
11757     if (CXXDirectInit)
11758       Args = MultiExprArg(CXXDirectInit->getExprs(),
11759                           CXXDirectInit->getNumExprs());
11760 
11761     // Try to correct any TypoExprs in the initialization arguments.
11762     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11763       ExprResult Res = CorrectDelayedTyposInExpr(
11764           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11765             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11766             return Init.Failed() ? ExprError() : E;
11767           });
11768       if (Res.isInvalid()) {
11769         VDecl->setInvalidDecl();
11770       } else if (Res.get() != Args[Idx]) {
11771         Args[Idx] = Res.get();
11772       }
11773     }
11774     if (VDecl->isInvalidDecl())
11775       return;
11776 
11777     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11778                                    /*TopLevelOfInitList=*/false,
11779                                    /*TreatUnavailableAsInvalid=*/false);
11780     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11781     if (Result.isInvalid()) {
11782       VDecl->setInvalidDecl();
11783       return;
11784     }
11785 
11786     Init = Result.getAs<Expr>();
11787   }
11788 
11789   // Check for self-references within variable initializers.
11790   // Variables declared within a function/method body (except for references)
11791   // are handled by a dataflow analysis.
11792   // This is undefined behavior in C++, but valid in C.
11793   if (getLangOpts().CPlusPlus) {
11794     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11795         VDecl->getType()->isReferenceType()) {
11796       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11797     }
11798   }
11799 
11800   // If the type changed, it means we had an incomplete type that was
11801   // completed by the initializer. For example:
11802   //   int ary[] = { 1, 3, 5 };
11803   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11804   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11805     VDecl->setType(DclT);
11806 
11807   if (!VDecl->isInvalidDecl()) {
11808     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11809 
11810     if (VDecl->hasAttr<BlocksAttr>())
11811       checkRetainCycles(VDecl, Init);
11812 
11813     // It is safe to assign a weak reference into a strong variable.
11814     // Although this code can still have problems:
11815     //   id x = self.weakProp;
11816     //   id y = self.weakProp;
11817     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11818     // paths through the function. This should be revisited if
11819     // -Wrepeated-use-of-weak is made flow-sensitive.
11820     if (FunctionScopeInfo *FSI = getCurFunction())
11821       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11822            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11823           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11824                            Init->getBeginLoc()))
11825         FSI->markSafeWeakUse(Init);
11826   }
11827 
11828   // The initialization is usually a full-expression.
11829   //
11830   // FIXME: If this is a braced initialization of an aggregate, it is not
11831   // an expression, and each individual field initializer is a separate
11832   // full-expression. For instance, in:
11833   //
11834   //   struct Temp { ~Temp(); };
11835   //   struct S { S(Temp); };
11836   //   struct T { S a, b; } t = { Temp(), Temp() }
11837   //
11838   // we should destroy the first Temp before constructing the second.
11839   ExprResult Result =
11840       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11841                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11842   if (Result.isInvalid()) {
11843     VDecl->setInvalidDecl();
11844     return;
11845   }
11846   Init = Result.get();
11847 
11848   // Attach the initializer to the decl.
11849   VDecl->setInit(Init);
11850 
11851   if (VDecl->isLocalVarDecl()) {
11852     // Don't check the initializer if the declaration is malformed.
11853     if (VDecl->isInvalidDecl()) {
11854       // do nothing
11855 
11856     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11857     // This is true even in C++ for OpenCL.
11858     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11859       CheckForConstantInitializer(Init, DclT);
11860 
11861     // Otherwise, C++ does not restrict the initializer.
11862     } else if (getLangOpts().CPlusPlus) {
11863       // do nothing
11864 
11865     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11866     // static storage duration shall be constant expressions or string literals.
11867     } else if (VDecl->getStorageClass() == SC_Static) {
11868       CheckForConstantInitializer(Init, DclT);
11869 
11870     // C89 is stricter than C99 for aggregate initializers.
11871     // C89 6.5.7p3: All the expressions [...] in an initializer list
11872     // for an object that has aggregate or union type shall be
11873     // constant expressions.
11874     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11875                isa<InitListExpr>(Init)) {
11876       const Expr *Culprit;
11877       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11878         Diag(Culprit->getExprLoc(),
11879              diag::ext_aggregate_init_not_constant)
11880           << Culprit->getSourceRange();
11881       }
11882     }
11883 
11884     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11885       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11886         if (VDecl->hasLocalStorage())
11887           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11888   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11889              VDecl->getLexicalDeclContext()->isRecord()) {
11890     // This is an in-class initialization for a static data member, e.g.,
11891     //
11892     // struct S {
11893     //   static const int value = 17;
11894     // };
11895 
11896     // C++ [class.mem]p4:
11897     //   A member-declarator can contain a constant-initializer only
11898     //   if it declares a static member (9.4) of const integral or
11899     //   const enumeration type, see 9.4.2.
11900     //
11901     // C++11 [class.static.data]p3:
11902     //   If a non-volatile non-inline const static data member is of integral
11903     //   or enumeration type, its declaration in the class definition can
11904     //   specify a brace-or-equal-initializer in which every initializer-clause
11905     //   that is an assignment-expression is a constant expression. A static
11906     //   data member of literal type can be declared in the class definition
11907     //   with the constexpr specifier; if so, its declaration shall specify a
11908     //   brace-or-equal-initializer in which every initializer-clause that is
11909     //   an assignment-expression is a constant expression.
11910 
11911     // Do nothing on dependent types.
11912     if (DclT->isDependentType()) {
11913 
11914     // Allow any 'static constexpr' members, whether or not they are of literal
11915     // type. We separately check that every constexpr variable is of literal
11916     // type.
11917     } else if (VDecl->isConstexpr()) {
11918 
11919     // Require constness.
11920     } else if (!DclT.isConstQualified()) {
11921       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11922         << Init->getSourceRange();
11923       VDecl->setInvalidDecl();
11924 
11925     // We allow integer constant expressions in all cases.
11926     } else if (DclT->isIntegralOrEnumerationType()) {
11927       // Check whether the expression is a constant expression.
11928       SourceLocation Loc;
11929       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11930         // In C++11, a non-constexpr const static data member with an
11931         // in-class initializer cannot be volatile.
11932         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11933       else if (Init->isValueDependent())
11934         ; // Nothing to check.
11935       else if (Init->isIntegerConstantExpr(Context, &Loc))
11936         ; // Ok, it's an ICE!
11937       else if (Init->getType()->isScopedEnumeralType() &&
11938                Init->isCXX11ConstantExpr(Context))
11939         ; // Ok, it is a scoped-enum constant expression.
11940       else if (Init->isEvaluatable(Context)) {
11941         // If we can constant fold the initializer through heroics, accept it,
11942         // but report this as a use of an extension for -pedantic.
11943         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11944           << Init->getSourceRange();
11945       } else {
11946         // Otherwise, this is some crazy unknown case.  Report the issue at the
11947         // location provided by the isIntegerConstantExpr failed check.
11948         Diag(Loc, diag::err_in_class_initializer_non_constant)
11949           << Init->getSourceRange();
11950         VDecl->setInvalidDecl();
11951       }
11952 
11953     // We allow foldable floating-point constants as an extension.
11954     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11955       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11956       // it anyway and provide a fixit to add the 'constexpr'.
11957       if (getLangOpts().CPlusPlus11) {
11958         Diag(VDecl->getLocation(),
11959              diag::ext_in_class_initializer_float_type_cxx11)
11960             << DclT << Init->getSourceRange();
11961         Diag(VDecl->getBeginLoc(),
11962              diag::note_in_class_initializer_float_type_cxx11)
11963             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11964       } else {
11965         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11966           << DclT << Init->getSourceRange();
11967 
11968         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11969           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11970             << Init->getSourceRange();
11971           VDecl->setInvalidDecl();
11972         }
11973       }
11974 
11975     // Suggest adding 'constexpr' in C++11 for literal types.
11976     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11977       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11978           << DclT << Init->getSourceRange()
11979           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11980       VDecl->setConstexpr(true);
11981 
11982     } else {
11983       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11984         << DclT << Init->getSourceRange();
11985       VDecl->setInvalidDecl();
11986     }
11987   } else if (VDecl->isFileVarDecl()) {
11988     // In C, extern is typically used to avoid tentative definitions when
11989     // declaring variables in headers, but adding an intializer makes it a
11990     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11991     // In C++, extern is often used to give implictly static const variables
11992     // external linkage, so don't warn in that case. If selectany is present,
11993     // this might be header code intended for C and C++ inclusion, so apply the
11994     // C++ rules.
11995     if (VDecl->getStorageClass() == SC_Extern &&
11996         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11997          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11998         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11999         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12000       Diag(VDecl->getLocation(), diag::warn_extern_init);
12001 
12002     // In Microsoft C++ mode, a const variable defined in namespace scope has
12003     // external linkage by default if the variable is declared with
12004     // __declspec(dllexport).
12005     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12006         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12007         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12008       VDecl->setStorageClass(SC_Extern);
12009 
12010     // C99 6.7.8p4. All file scoped initializers need to be constant.
12011     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12012       CheckForConstantInitializer(Init, DclT);
12013   }
12014 
12015   QualType InitType = Init->getType();
12016   if (!InitType.isNull() &&
12017       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12018        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12019     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12020 
12021   // We will represent direct-initialization similarly to copy-initialization:
12022   //    int x(1);  -as-> int x = 1;
12023   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12024   //
12025   // Clients that want to distinguish between the two forms, can check for
12026   // direct initializer using VarDecl::getInitStyle().
12027   // A major benefit is that clients that don't particularly care about which
12028   // exactly form was it (like the CodeGen) can handle both cases without
12029   // special case code.
12030 
12031   // C++ 8.5p11:
12032   // The form of initialization (using parentheses or '=') is generally
12033   // insignificant, but does matter when the entity being initialized has a
12034   // class type.
12035   if (CXXDirectInit) {
12036     assert(DirectInit && "Call-style initializer must be direct init.");
12037     VDecl->setInitStyle(VarDecl::CallInit);
12038   } else if (DirectInit) {
12039     // This must be list-initialization. No other way is direct-initialization.
12040     VDecl->setInitStyle(VarDecl::ListInit);
12041   }
12042 
12043   CheckCompleteVariableDeclaration(VDecl);
12044 }
12045 
12046 /// ActOnInitializerError - Given that there was an error parsing an
12047 /// initializer for the given declaration, try to return to some form
12048 /// of sanity.
12049 void Sema::ActOnInitializerError(Decl *D) {
12050   // Our main concern here is re-establishing invariants like "a
12051   // variable's type is either dependent or complete".
12052   if (!D || D->isInvalidDecl()) return;
12053 
12054   VarDecl *VD = dyn_cast<VarDecl>(D);
12055   if (!VD) return;
12056 
12057   // Bindings are not usable if we can't make sense of the initializer.
12058   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12059     for (auto *BD : DD->bindings())
12060       BD->setInvalidDecl();
12061 
12062   // Auto types are meaningless if we can't make sense of the initializer.
12063   if (ParsingInitForAutoVars.count(D)) {
12064     D->setInvalidDecl();
12065     return;
12066   }
12067 
12068   QualType Ty = VD->getType();
12069   if (Ty->isDependentType()) return;
12070 
12071   // Require a complete type.
12072   if (RequireCompleteType(VD->getLocation(),
12073                           Context.getBaseElementType(Ty),
12074                           diag::err_typecheck_decl_incomplete_type)) {
12075     VD->setInvalidDecl();
12076     return;
12077   }
12078 
12079   // Require a non-abstract type.
12080   if (RequireNonAbstractType(VD->getLocation(), Ty,
12081                              diag::err_abstract_type_in_decl,
12082                              AbstractVariableType)) {
12083     VD->setInvalidDecl();
12084     return;
12085   }
12086 
12087   // Don't bother complaining about constructors or destructors,
12088   // though.
12089 }
12090 
12091 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12092   // If there is no declaration, there was an error parsing it. Just ignore it.
12093   if (!RealDecl)
12094     return;
12095 
12096   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12097     QualType Type = Var->getType();
12098 
12099     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12100     if (isa<DecompositionDecl>(RealDecl)) {
12101       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12102       Var->setInvalidDecl();
12103       return;
12104     }
12105 
12106     if (Type->isUndeducedType() &&
12107         DeduceVariableDeclarationType(Var, false, nullptr))
12108       return;
12109 
12110     // C++11 [class.static.data]p3: A static data member can be declared with
12111     // the constexpr specifier; if so, its declaration shall specify
12112     // a brace-or-equal-initializer.
12113     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12114     // the definition of a variable [...] or the declaration of a static data
12115     // member.
12116     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12117         !Var->isThisDeclarationADemotedDefinition()) {
12118       if (Var->isStaticDataMember()) {
12119         // C++1z removes the relevant rule; the in-class declaration is always
12120         // a definition there.
12121         if (!getLangOpts().CPlusPlus17 &&
12122             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12123           Diag(Var->getLocation(),
12124                diag::err_constexpr_static_mem_var_requires_init)
12125             << Var->getDeclName();
12126           Var->setInvalidDecl();
12127           return;
12128         }
12129       } else {
12130         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12131         Var->setInvalidDecl();
12132         return;
12133       }
12134     }
12135 
12136     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12137     // be initialized.
12138     if (!Var->isInvalidDecl() &&
12139         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12140         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12141       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12142       Var->setInvalidDecl();
12143       return;
12144     }
12145 
12146     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12147     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12148         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12149       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12150                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12151 
12152 
12153     switch (DefKind) {
12154     case VarDecl::Definition:
12155       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12156         break;
12157 
12158       // We have an out-of-line definition of a static data member
12159       // that has an in-class initializer, so we type-check this like
12160       // a declaration.
12161       //
12162       LLVM_FALLTHROUGH;
12163 
12164     case VarDecl::DeclarationOnly:
12165       // It's only a declaration.
12166 
12167       // Block scope. C99 6.7p7: If an identifier for an object is
12168       // declared with no linkage (C99 6.2.2p6), the type for the
12169       // object shall be complete.
12170       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12171           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12172           RequireCompleteType(Var->getLocation(), Type,
12173                               diag::err_typecheck_decl_incomplete_type))
12174         Var->setInvalidDecl();
12175 
12176       // Make sure that the type is not abstract.
12177       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12178           RequireNonAbstractType(Var->getLocation(), Type,
12179                                  diag::err_abstract_type_in_decl,
12180                                  AbstractVariableType))
12181         Var->setInvalidDecl();
12182       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12183           Var->getStorageClass() == SC_PrivateExtern) {
12184         Diag(Var->getLocation(), diag::warn_private_extern);
12185         Diag(Var->getLocation(), diag::note_private_extern);
12186       }
12187 
12188       return;
12189 
12190     case VarDecl::TentativeDefinition:
12191       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12192       // object that has file scope without an initializer, and without a
12193       // storage-class specifier or with the storage-class specifier "static",
12194       // constitutes a tentative definition. Note: A tentative definition with
12195       // external linkage is valid (C99 6.2.2p5).
12196       if (!Var->isInvalidDecl()) {
12197         if (const IncompleteArrayType *ArrayT
12198                                     = Context.getAsIncompleteArrayType(Type)) {
12199           if (RequireCompleteType(Var->getLocation(),
12200                                   ArrayT->getElementType(),
12201                                   diag::err_illegal_decl_array_incomplete_type))
12202             Var->setInvalidDecl();
12203         } else if (Var->getStorageClass() == SC_Static) {
12204           // C99 6.9.2p3: If the declaration of an identifier for an object is
12205           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12206           // declared type shall not be an incomplete type.
12207           // NOTE: code such as the following
12208           //     static struct s;
12209           //     struct s { int a; };
12210           // is accepted by gcc. Hence here we issue a warning instead of
12211           // an error and we do not invalidate the static declaration.
12212           // NOTE: to avoid multiple warnings, only check the first declaration.
12213           if (Var->isFirstDecl())
12214             RequireCompleteType(Var->getLocation(), Type,
12215                                 diag::ext_typecheck_decl_incomplete_type);
12216         }
12217       }
12218 
12219       // Record the tentative definition; we're done.
12220       if (!Var->isInvalidDecl())
12221         TentativeDefinitions.push_back(Var);
12222       return;
12223     }
12224 
12225     // Provide a specific diagnostic for uninitialized variable
12226     // definitions with incomplete array type.
12227     if (Type->isIncompleteArrayType()) {
12228       Diag(Var->getLocation(),
12229            diag::err_typecheck_incomplete_array_needs_initializer);
12230       Var->setInvalidDecl();
12231       return;
12232     }
12233 
12234     // Provide a specific diagnostic for uninitialized variable
12235     // definitions with reference type.
12236     if (Type->isReferenceType()) {
12237       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12238         << Var->getDeclName()
12239         << SourceRange(Var->getLocation(), Var->getLocation());
12240       Var->setInvalidDecl();
12241       return;
12242     }
12243 
12244     // Do not attempt to type-check the default initializer for a
12245     // variable with dependent type.
12246     if (Type->isDependentType())
12247       return;
12248 
12249     if (Var->isInvalidDecl())
12250       return;
12251 
12252     if (!Var->hasAttr<AliasAttr>()) {
12253       if (RequireCompleteType(Var->getLocation(),
12254                               Context.getBaseElementType(Type),
12255                               diag::err_typecheck_decl_incomplete_type)) {
12256         Var->setInvalidDecl();
12257         return;
12258       }
12259     } else {
12260       return;
12261     }
12262 
12263     // The variable can not have an abstract class type.
12264     if (RequireNonAbstractType(Var->getLocation(), Type,
12265                                diag::err_abstract_type_in_decl,
12266                                AbstractVariableType)) {
12267       Var->setInvalidDecl();
12268       return;
12269     }
12270 
12271     // Check for jumps past the implicit initializer.  C++0x
12272     // clarifies that this applies to a "variable with automatic
12273     // storage duration", not a "local variable".
12274     // C++11 [stmt.dcl]p3
12275     //   A program that jumps from a point where a variable with automatic
12276     //   storage duration is not in scope to a point where it is in scope is
12277     //   ill-formed unless the variable has scalar type, class type with a
12278     //   trivial default constructor and a trivial destructor, a cv-qualified
12279     //   version of one of these types, or an array of one of the preceding
12280     //   types and is declared without an initializer.
12281     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12282       if (const RecordType *Record
12283             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12284         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12285         // Mark the function (if we're in one) for further checking even if the
12286         // looser rules of C++11 do not require such checks, so that we can
12287         // diagnose incompatibilities with C++98.
12288         if (!CXXRecord->isPOD())
12289           setFunctionHasBranchProtectedScope();
12290       }
12291     }
12292     // In OpenCL, we can't initialize objects in the __local address space,
12293     // even implicitly, so don't synthesize an implicit initializer.
12294     if (getLangOpts().OpenCL &&
12295         Var->getType().getAddressSpace() == LangAS::opencl_local)
12296       return;
12297     // C++03 [dcl.init]p9:
12298     //   If no initializer is specified for an object, and the
12299     //   object is of (possibly cv-qualified) non-POD class type (or
12300     //   array thereof), the object shall be default-initialized; if
12301     //   the object is of const-qualified type, the underlying class
12302     //   type shall have a user-declared default
12303     //   constructor. Otherwise, if no initializer is specified for
12304     //   a non- static object, the object and its subobjects, if
12305     //   any, have an indeterminate initial value); if the object
12306     //   or any of its subobjects are of const-qualified type, the
12307     //   program is ill-formed.
12308     // C++0x [dcl.init]p11:
12309     //   If no initializer is specified for an object, the object is
12310     //   default-initialized; [...].
12311     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12312     InitializationKind Kind
12313       = InitializationKind::CreateDefault(Var->getLocation());
12314 
12315     InitializationSequence InitSeq(*this, Entity, Kind, None);
12316     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12317     if (Init.isInvalid())
12318       Var->setInvalidDecl();
12319     else if (Init.get()) {
12320       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12321       // This is important for template substitution.
12322       Var->setInitStyle(VarDecl::CallInit);
12323     }
12324 
12325     CheckCompleteVariableDeclaration(Var);
12326   }
12327 }
12328 
12329 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12330   // If there is no declaration, there was an error parsing it. Ignore it.
12331   if (!D)
12332     return;
12333 
12334   VarDecl *VD = dyn_cast<VarDecl>(D);
12335   if (!VD) {
12336     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12337     D->setInvalidDecl();
12338     return;
12339   }
12340 
12341   VD->setCXXForRangeDecl(true);
12342 
12343   // for-range-declaration cannot be given a storage class specifier.
12344   int Error = -1;
12345   switch (VD->getStorageClass()) {
12346   case SC_None:
12347     break;
12348   case SC_Extern:
12349     Error = 0;
12350     break;
12351   case SC_Static:
12352     Error = 1;
12353     break;
12354   case SC_PrivateExtern:
12355     Error = 2;
12356     break;
12357   case SC_Auto:
12358     Error = 3;
12359     break;
12360   case SC_Register:
12361     Error = 4;
12362     break;
12363   }
12364   if (Error != -1) {
12365     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12366       << VD->getDeclName() << Error;
12367     D->setInvalidDecl();
12368   }
12369 }
12370 
12371 StmtResult
12372 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12373                                  IdentifierInfo *Ident,
12374                                  ParsedAttributes &Attrs,
12375                                  SourceLocation AttrEnd) {
12376   // C++1y [stmt.iter]p1:
12377   //   A range-based for statement of the form
12378   //      for ( for-range-identifier : for-range-initializer ) statement
12379   //   is equivalent to
12380   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12381   DeclSpec DS(Attrs.getPool().getFactory());
12382 
12383   const char *PrevSpec;
12384   unsigned DiagID;
12385   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12386                      getPrintingPolicy());
12387 
12388   Declarator D(DS, DeclaratorContext::ForContext);
12389   D.SetIdentifier(Ident, IdentLoc);
12390   D.takeAttributes(Attrs, AttrEnd);
12391 
12392   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12393                 IdentLoc);
12394   Decl *Var = ActOnDeclarator(S, D);
12395   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12396   FinalizeDeclaration(Var);
12397   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12398                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12399 }
12400 
12401 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12402   if (var->isInvalidDecl()) return;
12403 
12404   if (getLangOpts().OpenCL) {
12405     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12406     // initialiser
12407     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12408         !var->hasInit()) {
12409       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12410           << 1 /*Init*/;
12411       var->setInvalidDecl();
12412       return;
12413     }
12414   }
12415 
12416   // In Objective-C, don't allow jumps past the implicit initialization of a
12417   // local retaining variable.
12418   if (getLangOpts().ObjC &&
12419       var->hasLocalStorage()) {
12420     switch (var->getType().getObjCLifetime()) {
12421     case Qualifiers::OCL_None:
12422     case Qualifiers::OCL_ExplicitNone:
12423     case Qualifiers::OCL_Autoreleasing:
12424       break;
12425 
12426     case Qualifiers::OCL_Weak:
12427     case Qualifiers::OCL_Strong:
12428       setFunctionHasBranchProtectedScope();
12429       break;
12430     }
12431   }
12432 
12433   if (var->hasLocalStorage() &&
12434       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12435     setFunctionHasBranchProtectedScope();
12436 
12437   // Warn about externally-visible variables being defined without a
12438   // prior declaration.  We only want to do this for global
12439   // declarations, but we also specifically need to avoid doing it for
12440   // class members because the linkage of an anonymous class can
12441   // change if it's later given a typedef name.
12442   if (var->isThisDeclarationADefinition() &&
12443       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12444       var->isExternallyVisible() && var->hasLinkage() &&
12445       !var->isInline() && !var->getDescribedVarTemplate() &&
12446       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12447       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12448                                   var->getLocation())) {
12449     // Find a previous declaration that's not a definition.
12450     VarDecl *prev = var->getPreviousDecl();
12451     while (prev && prev->isThisDeclarationADefinition())
12452       prev = prev->getPreviousDecl();
12453 
12454     if (!prev) {
12455       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12456       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12457           << /* variable */ 0;
12458     }
12459   }
12460 
12461   // Cache the result of checking for constant initialization.
12462   Optional<bool> CacheHasConstInit;
12463   const Expr *CacheCulprit = nullptr;
12464   auto checkConstInit = [&]() mutable {
12465     if (!CacheHasConstInit)
12466       CacheHasConstInit = var->getInit()->isConstantInitializer(
12467             Context, var->getType()->isReferenceType(), &CacheCulprit);
12468     return *CacheHasConstInit;
12469   };
12470 
12471   if (var->getTLSKind() == VarDecl::TLS_Static) {
12472     if (var->getType().isDestructedType()) {
12473       // GNU C++98 edits for __thread, [basic.start.term]p3:
12474       //   The type of an object with thread storage duration shall not
12475       //   have a non-trivial destructor.
12476       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12477       if (getLangOpts().CPlusPlus11)
12478         Diag(var->getLocation(), diag::note_use_thread_local);
12479     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12480       if (!checkConstInit()) {
12481         // GNU C++98 edits for __thread, [basic.start.init]p4:
12482         //   An object of thread storage duration shall not require dynamic
12483         //   initialization.
12484         // FIXME: Need strict checking here.
12485         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12486           << CacheCulprit->getSourceRange();
12487         if (getLangOpts().CPlusPlus11)
12488           Diag(var->getLocation(), diag::note_use_thread_local);
12489       }
12490     }
12491   }
12492 
12493   // Apply section attributes and pragmas to global variables.
12494   bool GlobalStorage = var->hasGlobalStorage();
12495   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12496       !inTemplateInstantiation()) {
12497     PragmaStack<StringLiteral *> *Stack = nullptr;
12498     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12499     if (var->getType().isConstQualified())
12500       Stack = &ConstSegStack;
12501     else if (!var->getInit()) {
12502       Stack = &BSSSegStack;
12503       SectionFlags |= ASTContext::PSF_Write;
12504     } else {
12505       Stack = &DataSegStack;
12506       SectionFlags |= ASTContext::PSF_Write;
12507     }
12508     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12509       var->addAttr(SectionAttr::CreateImplicit(
12510           Context, Stack->CurrentValue->getString(),
12511           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12512           SectionAttr::Declspec_allocate));
12513     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12514       if (UnifySection(SA->getName(), SectionFlags, var))
12515         var->dropAttr<SectionAttr>();
12516 
12517     // Apply the init_seg attribute if this has an initializer.  If the
12518     // initializer turns out to not be dynamic, we'll end up ignoring this
12519     // attribute.
12520     if (CurInitSeg && var->getInit())
12521       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12522                                                CurInitSegLoc,
12523                                                AttributeCommonInfo::AS_Pragma));
12524   }
12525 
12526   // All the following checks are C++ only.
12527   if (!getLangOpts().CPlusPlus) {
12528       // If this variable must be emitted, add it as an initializer for the
12529       // current module.
12530      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12531        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12532      return;
12533   }
12534 
12535   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12536     CheckCompleteDecompositionDeclaration(DD);
12537 
12538   QualType type = var->getType();
12539   if (type->isDependentType()) return;
12540 
12541   if (var->hasAttr<BlocksAttr>())
12542     getCurFunction()->addByrefBlockVar(var);
12543 
12544   Expr *Init = var->getInit();
12545   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12546   QualType baseType = Context.getBaseElementType(type);
12547 
12548   if (Init && !Init->isValueDependent()) {
12549     if (var->isConstexpr()) {
12550       SmallVector<PartialDiagnosticAt, 8> Notes;
12551       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12552         SourceLocation DiagLoc = var->getLocation();
12553         // If the note doesn't add any useful information other than a source
12554         // location, fold it into the primary diagnostic.
12555         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12556               diag::note_invalid_subexpr_in_const_expr) {
12557           DiagLoc = Notes[0].first;
12558           Notes.clear();
12559         }
12560         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12561           << var << Init->getSourceRange();
12562         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12563           Diag(Notes[I].first, Notes[I].second);
12564       }
12565     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12566       // Check whether the initializer of a const variable of integral or
12567       // enumeration type is an ICE now, since we can't tell whether it was
12568       // initialized by a constant expression if we check later.
12569       var->checkInitIsICE();
12570     }
12571 
12572     // Don't emit further diagnostics about constexpr globals since they
12573     // were just diagnosed.
12574     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12575       // FIXME: Need strict checking in C++03 here.
12576       bool DiagErr = getLangOpts().CPlusPlus11
12577           ? !var->checkInitIsICE() : !checkConstInit();
12578       if (DiagErr) {
12579         auto *Attr = var->getAttr<ConstInitAttr>();
12580         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12581           << Init->getSourceRange();
12582         Diag(Attr->getLocation(),
12583              diag::note_declared_required_constant_init_here)
12584             << Attr->getRange() << Attr->isConstinit();
12585         if (getLangOpts().CPlusPlus11) {
12586           APValue Value;
12587           SmallVector<PartialDiagnosticAt, 8> Notes;
12588           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12589           for (auto &it : Notes)
12590             Diag(it.first, it.second);
12591         } else {
12592           Diag(CacheCulprit->getExprLoc(),
12593                diag::note_invalid_subexpr_in_const_expr)
12594               << CacheCulprit->getSourceRange();
12595         }
12596       }
12597     }
12598     else if (!var->isConstexpr() && IsGlobal &&
12599              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12600                                     var->getLocation())) {
12601       // Warn about globals which don't have a constant initializer.  Don't
12602       // warn about globals with a non-trivial destructor because we already
12603       // warned about them.
12604       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12605       if (!(RD && !RD->hasTrivialDestructor())) {
12606         if (!checkConstInit())
12607           Diag(var->getLocation(), diag::warn_global_constructor)
12608             << Init->getSourceRange();
12609       }
12610     }
12611   }
12612 
12613   // Require the destructor.
12614   if (const RecordType *recordType = baseType->getAs<RecordType>())
12615     FinalizeVarWithDestructor(var, recordType);
12616 
12617   // If this variable must be emitted, add it as an initializer for the current
12618   // module.
12619   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12620     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12621 }
12622 
12623 /// Determines if a variable's alignment is dependent.
12624 static bool hasDependentAlignment(VarDecl *VD) {
12625   if (VD->getType()->isDependentType())
12626     return true;
12627   for (auto *I : VD->specific_attrs<AlignedAttr>())
12628     if (I->isAlignmentDependent())
12629       return true;
12630   return false;
12631 }
12632 
12633 /// Check if VD needs to be dllexport/dllimport due to being in a
12634 /// dllexport/import function.
12635 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12636   assert(VD->isStaticLocal());
12637 
12638   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12639 
12640   // Find outermost function when VD is in lambda function.
12641   while (FD && !getDLLAttr(FD) &&
12642          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12643          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12644     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12645   }
12646 
12647   if (!FD)
12648     return;
12649 
12650   // Static locals inherit dll attributes from their function.
12651   if (Attr *A = getDLLAttr(FD)) {
12652     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12653     NewAttr->setInherited(true);
12654     VD->addAttr(NewAttr);
12655   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12656     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12657     NewAttr->setInherited(true);
12658     VD->addAttr(NewAttr);
12659 
12660     // Export this function to enforce exporting this static variable even
12661     // if it is not used in this compilation unit.
12662     if (!FD->hasAttr<DLLExportAttr>())
12663       FD->addAttr(NewAttr);
12664 
12665   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12666     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12667     NewAttr->setInherited(true);
12668     VD->addAttr(NewAttr);
12669   }
12670 }
12671 
12672 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12673 /// any semantic actions necessary after any initializer has been attached.
12674 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12675   // Note that we are no longer parsing the initializer for this declaration.
12676   ParsingInitForAutoVars.erase(ThisDecl);
12677 
12678   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12679   if (!VD)
12680     return;
12681 
12682   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12683   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12684       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12685     if (PragmaClangBSSSection.Valid)
12686       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12687           Context, PragmaClangBSSSection.SectionName,
12688           PragmaClangBSSSection.PragmaLocation,
12689           AttributeCommonInfo::AS_Pragma));
12690     if (PragmaClangDataSection.Valid)
12691       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12692           Context, PragmaClangDataSection.SectionName,
12693           PragmaClangDataSection.PragmaLocation,
12694           AttributeCommonInfo::AS_Pragma));
12695     if (PragmaClangRodataSection.Valid)
12696       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12697           Context, PragmaClangRodataSection.SectionName,
12698           PragmaClangRodataSection.PragmaLocation,
12699           AttributeCommonInfo::AS_Pragma));
12700     if (PragmaClangRelroSection.Valid)
12701       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12702           Context, PragmaClangRelroSection.SectionName,
12703           PragmaClangRelroSection.PragmaLocation,
12704           AttributeCommonInfo::AS_Pragma));
12705   }
12706 
12707   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12708     for (auto *BD : DD->bindings()) {
12709       FinalizeDeclaration(BD);
12710     }
12711   }
12712 
12713   checkAttributesAfterMerging(*this, *VD);
12714 
12715   // Perform TLS alignment check here after attributes attached to the variable
12716   // which may affect the alignment have been processed. Only perform the check
12717   // if the target has a maximum TLS alignment (zero means no constraints).
12718   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12719     // Protect the check so that it's not performed on dependent types and
12720     // dependent alignments (we can't determine the alignment in that case).
12721     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12722         !VD->isInvalidDecl()) {
12723       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12724       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12725         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12726           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12727           << (unsigned)MaxAlignChars.getQuantity();
12728       }
12729     }
12730   }
12731 
12732   if (VD->isStaticLocal()) {
12733     CheckStaticLocalForDllExport(VD);
12734 
12735     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12736       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12737       // function, only __shared__ variables or variables without any device
12738       // memory qualifiers may be declared with static storage class.
12739       // Note: It is unclear how a function-scope non-const static variable
12740       // without device memory qualifier is implemented, therefore only static
12741       // const variable without device memory qualifier is allowed.
12742       [&]() {
12743         if (!getLangOpts().CUDA)
12744           return;
12745         if (VD->hasAttr<CUDASharedAttr>())
12746           return;
12747         if (VD->getType().isConstQualified() &&
12748             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12749           return;
12750         if (CUDADiagIfDeviceCode(VD->getLocation(),
12751                                  diag::err_device_static_local_var)
12752             << CurrentCUDATarget())
12753           VD->setInvalidDecl();
12754       }();
12755     }
12756   }
12757 
12758   // Perform check for initializers of device-side global variables.
12759   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12760   // 7.5). We must also apply the same checks to all __shared__
12761   // variables whether they are local or not. CUDA also allows
12762   // constant initializers for __constant__ and __device__ variables.
12763   if (getLangOpts().CUDA)
12764     checkAllowedCUDAInitializer(VD);
12765 
12766   // Grab the dllimport or dllexport attribute off of the VarDecl.
12767   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12768 
12769   // Imported static data members cannot be defined out-of-line.
12770   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12771     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12772         VD->isThisDeclarationADefinition()) {
12773       // We allow definitions of dllimport class template static data members
12774       // with a warning.
12775       CXXRecordDecl *Context =
12776         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12777       bool IsClassTemplateMember =
12778           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12779           Context->getDescribedClassTemplate();
12780 
12781       Diag(VD->getLocation(),
12782            IsClassTemplateMember
12783                ? diag::warn_attribute_dllimport_static_field_definition
12784                : diag::err_attribute_dllimport_static_field_definition);
12785       Diag(IA->getLocation(), diag::note_attribute);
12786       if (!IsClassTemplateMember)
12787         VD->setInvalidDecl();
12788     }
12789   }
12790 
12791   // dllimport/dllexport variables cannot be thread local, their TLS index
12792   // isn't exported with the variable.
12793   if (DLLAttr && VD->getTLSKind()) {
12794     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12795     if (F && getDLLAttr(F)) {
12796       assert(VD->isStaticLocal());
12797       // But if this is a static local in a dlimport/dllexport function, the
12798       // function will never be inlined, which means the var would never be
12799       // imported, so having it marked import/export is safe.
12800     } else {
12801       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12802                                                                     << DLLAttr;
12803       VD->setInvalidDecl();
12804     }
12805   }
12806 
12807   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12808     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12809       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12810       VD->dropAttr<UsedAttr>();
12811     }
12812   }
12813 
12814   const DeclContext *DC = VD->getDeclContext();
12815   // If there's a #pragma GCC visibility in scope, and this isn't a class
12816   // member, set the visibility of this variable.
12817   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12818     AddPushedVisibilityAttribute(VD);
12819 
12820   // FIXME: Warn on unused var template partial specializations.
12821   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12822     MarkUnusedFileScopedDecl(VD);
12823 
12824   // Now we have parsed the initializer and can update the table of magic
12825   // tag values.
12826   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12827       !VD->getType()->isIntegralOrEnumerationType())
12828     return;
12829 
12830   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12831     const Expr *MagicValueExpr = VD->getInit();
12832     if (!MagicValueExpr) {
12833       continue;
12834     }
12835     llvm::APSInt MagicValueInt;
12836     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12837       Diag(I->getRange().getBegin(),
12838            diag::err_type_tag_for_datatype_not_ice)
12839         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12840       continue;
12841     }
12842     if (MagicValueInt.getActiveBits() > 64) {
12843       Diag(I->getRange().getBegin(),
12844            diag::err_type_tag_for_datatype_too_large)
12845         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12846       continue;
12847     }
12848     uint64_t MagicValue = MagicValueInt.getZExtValue();
12849     RegisterTypeTagForDatatype(I->getArgumentKind(),
12850                                MagicValue,
12851                                I->getMatchingCType(),
12852                                I->getLayoutCompatible(),
12853                                I->getMustBeNull());
12854   }
12855 }
12856 
12857 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12858   auto *VD = dyn_cast<VarDecl>(DD);
12859   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12860 }
12861 
12862 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12863                                                    ArrayRef<Decl *> Group) {
12864   SmallVector<Decl*, 8> Decls;
12865 
12866   if (DS.isTypeSpecOwned())
12867     Decls.push_back(DS.getRepAsDecl());
12868 
12869   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12870   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12871   bool DiagnosedMultipleDecomps = false;
12872   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12873   bool DiagnosedNonDeducedAuto = false;
12874 
12875   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12876     if (Decl *D = Group[i]) {
12877       // For declarators, there are some additional syntactic-ish checks we need
12878       // to perform.
12879       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12880         if (!FirstDeclaratorInGroup)
12881           FirstDeclaratorInGroup = DD;
12882         if (!FirstDecompDeclaratorInGroup)
12883           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12884         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12885             !hasDeducedAuto(DD))
12886           FirstNonDeducedAutoInGroup = DD;
12887 
12888         if (FirstDeclaratorInGroup != DD) {
12889           // A decomposition declaration cannot be combined with any other
12890           // declaration in the same group.
12891           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12892             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12893                  diag::err_decomp_decl_not_alone)
12894                 << FirstDeclaratorInGroup->getSourceRange()
12895                 << DD->getSourceRange();
12896             DiagnosedMultipleDecomps = true;
12897           }
12898 
12899           // A declarator that uses 'auto' in any way other than to declare a
12900           // variable with a deduced type cannot be combined with any other
12901           // declarator in the same group.
12902           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12903             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12904                  diag::err_auto_non_deduced_not_alone)
12905                 << FirstNonDeducedAutoInGroup->getType()
12906                        ->hasAutoForTrailingReturnType()
12907                 << FirstDeclaratorInGroup->getSourceRange()
12908                 << DD->getSourceRange();
12909             DiagnosedNonDeducedAuto = true;
12910           }
12911         }
12912       }
12913 
12914       Decls.push_back(D);
12915     }
12916   }
12917 
12918   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12919     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12920       handleTagNumbering(Tag, S);
12921       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12922           getLangOpts().CPlusPlus)
12923         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12924     }
12925   }
12926 
12927   return BuildDeclaratorGroup(Decls);
12928 }
12929 
12930 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12931 /// group, performing any necessary semantic checking.
12932 Sema::DeclGroupPtrTy
12933 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12934   // C++14 [dcl.spec.auto]p7: (DR1347)
12935   //   If the type that replaces the placeholder type is not the same in each
12936   //   deduction, the program is ill-formed.
12937   if (Group.size() > 1) {
12938     QualType Deduced;
12939     VarDecl *DeducedDecl = nullptr;
12940     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12941       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12942       if (!D || D->isInvalidDecl())
12943         break;
12944       DeducedType *DT = D->getType()->getContainedDeducedType();
12945       if (!DT || DT->getDeducedType().isNull())
12946         continue;
12947       if (Deduced.isNull()) {
12948         Deduced = DT->getDeducedType();
12949         DeducedDecl = D;
12950       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12951         auto *AT = dyn_cast<AutoType>(DT);
12952         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12953              diag::err_auto_different_deductions)
12954           << (AT ? (unsigned)AT->getKeyword() : 3)
12955           << Deduced << DeducedDecl->getDeclName()
12956           << DT->getDeducedType() << D->getDeclName()
12957           << DeducedDecl->getInit()->getSourceRange()
12958           << D->getInit()->getSourceRange();
12959         D->setInvalidDecl();
12960         break;
12961       }
12962     }
12963   }
12964 
12965   ActOnDocumentableDecls(Group);
12966 
12967   return DeclGroupPtrTy::make(
12968       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12969 }
12970 
12971 void Sema::ActOnDocumentableDecl(Decl *D) {
12972   ActOnDocumentableDecls(D);
12973 }
12974 
12975 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12976   // Don't parse the comment if Doxygen diagnostics are ignored.
12977   if (Group.empty() || !Group[0])
12978     return;
12979 
12980   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12981                       Group[0]->getLocation()) &&
12982       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12983                       Group[0]->getLocation()))
12984     return;
12985 
12986   if (Group.size() >= 2) {
12987     // This is a decl group.  Normally it will contain only declarations
12988     // produced from declarator list.  But in case we have any definitions or
12989     // additional declaration references:
12990     //   'typedef struct S {} S;'
12991     //   'typedef struct S *S;'
12992     //   'struct S *pS;'
12993     // FinalizeDeclaratorGroup adds these as separate declarations.
12994     Decl *MaybeTagDecl = Group[0];
12995     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12996       Group = Group.slice(1);
12997     }
12998   }
12999 
13000   // FIMXE: We assume every Decl in the group is in the same file.
13001   // This is false when preprocessor constructs the group from decls in
13002   // different files (e. g. macros or #include).
13003   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13004 }
13005 
13006 /// Common checks for a parameter-declaration that should apply to both function
13007 /// parameters and non-type template parameters.
13008 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13009   // Check that there are no default arguments inside the type of this
13010   // parameter.
13011   if (getLangOpts().CPlusPlus)
13012     CheckExtraCXXDefaultArguments(D);
13013 
13014   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13015   if (D.getCXXScopeSpec().isSet()) {
13016     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13017       << D.getCXXScopeSpec().getRange();
13018   }
13019 
13020   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13021   // simple identifier except [...irrelevant cases...].
13022   switch (D.getName().getKind()) {
13023   case UnqualifiedIdKind::IK_Identifier:
13024     break;
13025 
13026   case UnqualifiedIdKind::IK_OperatorFunctionId:
13027   case UnqualifiedIdKind::IK_ConversionFunctionId:
13028   case UnqualifiedIdKind::IK_LiteralOperatorId:
13029   case UnqualifiedIdKind::IK_ConstructorName:
13030   case UnqualifiedIdKind::IK_DestructorName:
13031   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13032   case UnqualifiedIdKind::IK_DeductionGuideName:
13033     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13034       << GetNameForDeclarator(D).getName();
13035     break;
13036 
13037   case UnqualifiedIdKind::IK_TemplateId:
13038   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13039     // GetNameForDeclarator would not produce a useful name in this case.
13040     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13041     break;
13042   }
13043 }
13044 
13045 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13046 /// to introduce parameters into function prototype scope.
13047 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13048   const DeclSpec &DS = D.getDeclSpec();
13049 
13050   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13051 
13052   // C++03 [dcl.stc]p2 also permits 'auto'.
13053   StorageClass SC = SC_None;
13054   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13055     SC = SC_Register;
13056     // In C++11, the 'register' storage class specifier is deprecated.
13057     // In C++17, it is not allowed, but we tolerate it as an extension.
13058     if (getLangOpts().CPlusPlus11) {
13059       Diag(DS.getStorageClassSpecLoc(),
13060            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13061                                      : diag::warn_deprecated_register)
13062         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13063     }
13064   } else if (getLangOpts().CPlusPlus &&
13065              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13066     SC = SC_Auto;
13067   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13068     Diag(DS.getStorageClassSpecLoc(),
13069          diag::err_invalid_storage_class_in_func_decl);
13070     D.getMutableDeclSpec().ClearStorageClassSpecs();
13071   }
13072 
13073   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13074     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13075       << DeclSpec::getSpecifierName(TSCS);
13076   if (DS.isInlineSpecified())
13077     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13078         << getLangOpts().CPlusPlus17;
13079   if (DS.hasConstexprSpecifier())
13080     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13081         << 0 << D.getDeclSpec().getConstexprSpecifier();
13082 
13083   DiagnoseFunctionSpecifiers(DS);
13084 
13085   CheckFunctionOrTemplateParamDeclarator(S, D);
13086 
13087   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13088   QualType parmDeclType = TInfo->getType();
13089 
13090   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13091   IdentifierInfo *II = D.getIdentifier();
13092   if (II) {
13093     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13094                    ForVisibleRedeclaration);
13095     LookupName(R, S);
13096     if (R.isSingleResult()) {
13097       NamedDecl *PrevDecl = R.getFoundDecl();
13098       if (PrevDecl->isTemplateParameter()) {
13099         // Maybe we will complain about the shadowed template parameter.
13100         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13101         // Just pretend that we didn't see the previous declaration.
13102         PrevDecl = nullptr;
13103       } else if (S->isDeclScope(PrevDecl)) {
13104         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13105         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13106 
13107         // Recover by removing the name
13108         II = nullptr;
13109         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13110         D.setInvalidType(true);
13111       }
13112     }
13113   }
13114 
13115   // Temporarily put parameter variables in the translation unit, not
13116   // the enclosing context.  This prevents them from accidentally
13117   // looking like class members in C++.
13118   ParmVarDecl *New =
13119       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13120                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13121 
13122   if (D.isInvalidType())
13123     New->setInvalidDecl();
13124 
13125   assert(S->isFunctionPrototypeScope());
13126   assert(S->getFunctionPrototypeDepth() >= 1);
13127   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13128                     S->getNextFunctionPrototypeIndex());
13129 
13130   // Add the parameter declaration into this scope.
13131   S->AddDecl(New);
13132   if (II)
13133     IdResolver.AddDecl(New);
13134 
13135   ProcessDeclAttributes(S, New, D);
13136 
13137   if (D.getDeclSpec().isModulePrivateSpecified())
13138     Diag(New->getLocation(), diag::err_module_private_local)
13139       << 1 << New->getDeclName()
13140       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13141       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13142 
13143   if (New->hasAttr<BlocksAttr>()) {
13144     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13145   }
13146 
13147   if (getLangOpts().OpenCL)
13148     deduceOpenCLAddressSpace(New);
13149 
13150   return New;
13151 }
13152 
13153 /// Synthesizes a variable for a parameter arising from a
13154 /// typedef.
13155 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13156                                               SourceLocation Loc,
13157                                               QualType T) {
13158   /* FIXME: setting StartLoc == Loc.
13159      Would it be worth to modify callers so as to provide proper source
13160      location for the unnamed parameters, embedding the parameter's type? */
13161   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13162                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13163                                            SC_None, nullptr);
13164   Param->setImplicit();
13165   return Param;
13166 }
13167 
13168 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13169   // Don't diagnose unused-parameter errors in template instantiations; we
13170   // will already have done so in the template itself.
13171   if (inTemplateInstantiation())
13172     return;
13173 
13174   for (const ParmVarDecl *Parameter : Parameters) {
13175     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13176         !Parameter->hasAttr<UnusedAttr>()) {
13177       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13178         << Parameter->getDeclName();
13179     }
13180   }
13181 }
13182 
13183 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13184     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13185   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13186     return;
13187 
13188   // Warn if the return value is pass-by-value and larger than the specified
13189   // threshold.
13190   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13191     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13192     if (Size > LangOpts.NumLargeByValueCopy)
13193       Diag(D->getLocation(), diag::warn_return_value_size)
13194           << D->getDeclName() << Size;
13195   }
13196 
13197   // Warn if any parameter is pass-by-value and larger than the specified
13198   // threshold.
13199   for (const ParmVarDecl *Parameter : Parameters) {
13200     QualType T = Parameter->getType();
13201     if (T->isDependentType() || !T.isPODType(Context))
13202       continue;
13203     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13204     if (Size > LangOpts.NumLargeByValueCopy)
13205       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13206           << Parameter->getDeclName() << Size;
13207   }
13208 }
13209 
13210 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13211                                   SourceLocation NameLoc, IdentifierInfo *Name,
13212                                   QualType T, TypeSourceInfo *TSInfo,
13213                                   StorageClass SC) {
13214   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13215   if (getLangOpts().ObjCAutoRefCount &&
13216       T.getObjCLifetime() == Qualifiers::OCL_None &&
13217       T->isObjCLifetimeType()) {
13218 
13219     Qualifiers::ObjCLifetime lifetime;
13220 
13221     // Special cases for arrays:
13222     //   - if it's const, use __unsafe_unretained
13223     //   - otherwise, it's an error
13224     if (T->isArrayType()) {
13225       if (!T.isConstQualified()) {
13226         if (DelayedDiagnostics.shouldDelayDiagnostics())
13227           DelayedDiagnostics.add(
13228               sema::DelayedDiagnostic::makeForbiddenType(
13229               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13230         else
13231           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13232               << TSInfo->getTypeLoc().getSourceRange();
13233       }
13234       lifetime = Qualifiers::OCL_ExplicitNone;
13235     } else {
13236       lifetime = T->getObjCARCImplicitLifetime();
13237     }
13238     T = Context.getLifetimeQualifiedType(T, lifetime);
13239   }
13240 
13241   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13242                                          Context.getAdjustedParameterType(T),
13243                                          TSInfo, SC, nullptr);
13244 
13245   // Make a note if we created a new pack in the scope of a lambda, so that
13246   // we know that references to that pack must also be expanded within the
13247   // lambda scope.
13248   if (New->isParameterPack())
13249     if (auto *LSI = getEnclosingLambda())
13250       LSI->LocalPacks.push_back(New);
13251 
13252   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13253       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13254     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13255                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13256 
13257   // Parameters can not be abstract class types.
13258   // For record types, this is done by the AbstractClassUsageDiagnoser once
13259   // the class has been completely parsed.
13260   if (!CurContext->isRecord() &&
13261       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13262                              AbstractParamType))
13263     New->setInvalidDecl();
13264 
13265   // Parameter declarators cannot be interface types. All ObjC objects are
13266   // passed by reference.
13267   if (T->isObjCObjectType()) {
13268     SourceLocation TypeEndLoc =
13269         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13270     Diag(NameLoc,
13271          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13272       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13273     T = Context.getObjCObjectPointerType(T);
13274     New->setType(T);
13275   }
13276 
13277   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13278   // duration shall not be qualified by an address-space qualifier."
13279   // Since all parameters have automatic store duration, they can not have
13280   // an address space.
13281   if (T.getAddressSpace() != LangAS::Default &&
13282       // OpenCL allows function arguments declared to be an array of a type
13283       // to be qualified with an address space.
13284       !(getLangOpts().OpenCL &&
13285         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13286     Diag(NameLoc, diag::err_arg_with_address_space);
13287     New->setInvalidDecl();
13288   }
13289 
13290   return New;
13291 }
13292 
13293 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13294                                            SourceLocation LocAfterDecls) {
13295   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13296 
13297   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13298   // for a K&R function.
13299   if (!FTI.hasPrototype) {
13300     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13301       --i;
13302       if (FTI.Params[i].Param == nullptr) {
13303         SmallString<256> Code;
13304         llvm::raw_svector_ostream(Code)
13305             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13306         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13307             << FTI.Params[i].Ident
13308             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13309 
13310         // Implicitly declare the argument as type 'int' for lack of a better
13311         // type.
13312         AttributeFactory attrs;
13313         DeclSpec DS(attrs);
13314         const char* PrevSpec; // unused
13315         unsigned DiagID; // unused
13316         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13317                            DiagID, Context.getPrintingPolicy());
13318         // Use the identifier location for the type source range.
13319         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13320         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13321         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13322         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13323         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13324       }
13325     }
13326   }
13327 }
13328 
13329 Decl *
13330 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13331                               MultiTemplateParamsArg TemplateParameterLists,
13332                               SkipBodyInfo *SkipBody) {
13333   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13334   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13335   Scope *ParentScope = FnBodyScope->getParent();
13336 
13337   D.setFunctionDefinitionKind(FDK_Definition);
13338   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13339   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13340 }
13341 
13342 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13343   Consumer.HandleInlineFunctionDefinition(D);
13344 }
13345 
13346 static bool
13347 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13348                                 const FunctionDecl *&PossiblePrototype) {
13349   // Don't warn about invalid declarations.
13350   if (FD->isInvalidDecl())
13351     return false;
13352 
13353   // Or declarations that aren't global.
13354   if (!FD->isGlobal())
13355     return false;
13356 
13357   // Don't warn about C++ member functions.
13358   if (isa<CXXMethodDecl>(FD))
13359     return false;
13360 
13361   // Don't warn about 'main'.
13362   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13363     if (IdentifierInfo *II = FD->getIdentifier())
13364       if (II->isStr("main"))
13365         return false;
13366 
13367   // Don't warn about inline functions.
13368   if (FD->isInlined())
13369     return false;
13370 
13371   // Don't warn about function templates.
13372   if (FD->getDescribedFunctionTemplate())
13373     return false;
13374 
13375   // Don't warn about function template specializations.
13376   if (FD->isFunctionTemplateSpecialization())
13377     return false;
13378 
13379   // Don't warn for OpenCL kernels.
13380   if (FD->hasAttr<OpenCLKernelAttr>())
13381     return false;
13382 
13383   // Don't warn on explicitly deleted functions.
13384   if (FD->isDeleted())
13385     return false;
13386 
13387   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13388        Prev; Prev = Prev->getPreviousDecl()) {
13389     // Ignore any declarations that occur in function or method
13390     // scope, because they aren't visible from the header.
13391     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13392       continue;
13393 
13394     PossiblePrototype = Prev;
13395     return Prev->getType()->isFunctionNoProtoType();
13396   }
13397 
13398   return true;
13399 }
13400 
13401 void
13402 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13403                                    const FunctionDecl *EffectiveDefinition,
13404                                    SkipBodyInfo *SkipBody) {
13405   const FunctionDecl *Definition = EffectiveDefinition;
13406   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13407     // If this is a friend function defined in a class template, it does not
13408     // have a body until it is used, nevertheless it is a definition, see
13409     // [temp.inst]p2:
13410     //
13411     // ... for the purpose of determining whether an instantiated redeclaration
13412     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13413     // corresponds to a definition in the template is considered to be a
13414     // definition.
13415     //
13416     // The following code must produce redefinition error:
13417     //
13418     //     template<typename T> struct C20 { friend void func_20() {} };
13419     //     C20<int> c20i;
13420     //     void func_20() {}
13421     //
13422     for (auto I : FD->redecls()) {
13423       if (I != FD && !I->isInvalidDecl() &&
13424           I->getFriendObjectKind() != Decl::FOK_None) {
13425         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13426           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13427             // A merged copy of the same function, instantiated as a member of
13428             // the same class, is OK.
13429             if (declaresSameEntity(OrigFD, Original) &&
13430                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13431                                    cast<Decl>(FD->getLexicalDeclContext())))
13432               continue;
13433           }
13434 
13435           if (Original->isThisDeclarationADefinition()) {
13436             Definition = I;
13437             break;
13438           }
13439         }
13440       }
13441     }
13442   }
13443 
13444   if (!Definition)
13445     // Similar to friend functions a friend function template may be a
13446     // definition and do not have a body if it is instantiated in a class
13447     // template.
13448     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13449       for (auto I : FTD->redecls()) {
13450         auto D = cast<FunctionTemplateDecl>(I);
13451         if (D != FTD) {
13452           assert(!D->isThisDeclarationADefinition() &&
13453                  "More than one definition in redeclaration chain");
13454           if (D->getFriendObjectKind() != Decl::FOK_None)
13455             if (FunctionTemplateDecl *FT =
13456                                        D->getInstantiatedFromMemberTemplate()) {
13457               if (FT->isThisDeclarationADefinition()) {
13458                 Definition = D->getTemplatedDecl();
13459                 break;
13460               }
13461             }
13462         }
13463       }
13464     }
13465 
13466   if (!Definition)
13467     return;
13468 
13469   if (canRedefineFunction(Definition, getLangOpts()))
13470     return;
13471 
13472   // Don't emit an error when this is redefinition of a typo-corrected
13473   // definition.
13474   if (TypoCorrectedFunctionDefinitions.count(Definition))
13475     return;
13476 
13477   // If we don't have a visible definition of the function, and it's inline or
13478   // a template, skip the new definition.
13479   if (SkipBody && !hasVisibleDefinition(Definition) &&
13480       (Definition->getFormalLinkage() == InternalLinkage ||
13481        Definition->isInlined() ||
13482        Definition->getDescribedFunctionTemplate() ||
13483        Definition->getNumTemplateParameterLists())) {
13484     SkipBody->ShouldSkip = true;
13485     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13486     if (auto *TD = Definition->getDescribedFunctionTemplate())
13487       makeMergedDefinitionVisible(TD);
13488     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13489     return;
13490   }
13491 
13492   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13493       Definition->getStorageClass() == SC_Extern)
13494     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13495         << FD->getDeclName() << getLangOpts().CPlusPlus;
13496   else
13497     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13498 
13499   Diag(Definition->getLocation(), diag::note_previous_definition);
13500   FD->setInvalidDecl();
13501 }
13502 
13503 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13504                                    Sema &S) {
13505   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13506 
13507   LambdaScopeInfo *LSI = S.PushLambdaScope();
13508   LSI->CallOperator = CallOperator;
13509   LSI->Lambda = LambdaClass;
13510   LSI->ReturnType = CallOperator->getReturnType();
13511   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13512 
13513   if (LCD == LCD_None)
13514     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13515   else if (LCD == LCD_ByCopy)
13516     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13517   else if (LCD == LCD_ByRef)
13518     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13519   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13520 
13521   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13522   LSI->Mutable = !CallOperator->isConst();
13523 
13524   // Add the captures to the LSI so they can be noted as already
13525   // captured within tryCaptureVar.
13526   auto I = LambdaClass->field_begin();
13527   for (const auto &C : LambdaClass->captures()) {
13528     if (C.capturesVariable()) {
13529       VarDecl *VD = C.getCapturedVar();
13530       if (VD->isInitCapture())
13531         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13532       QualType CaptureType = VD->getType();
13533       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13534       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13535           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13536           /*EllipsisLoc*/C.isPackExpansion()
13537                          ? C.getEllipsisLoc() : SourceLocation(),
13538           CaptureType, /*Invalid*/false);
13539 
13540     } else if (C.capturesThis()) {
13541       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13542                           C.getCaptureKind() == LCK_StarThis);
13543     } else {
13544       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13545                              I->getType());
13546     }
13547     ++I;
13548   }
13549 }
13550 
13551 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13552                                     SkipBodyInfo *SkipBody) {
13553   if (!D) {
13554     // Parsing the function declaration failed in some way. Push on a fake scope
13555     // anyway so we can try to parse the function body.
13556     PushFunctionScope();
13557     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13558     return D;
13559   }
13560 
13561   FunctionDecl *FD = nullptr;
13562 
13563   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13564     FD = FunTmpl->getTemplatedDecl();
13565   else
13566     FD = cast<FunctionDecl>(D);
13567 
13568   // Do not push if it is a lambda because one is already pushed when building
13569   // the lambda in ActOnStartOfLambdaDefinition().
13570   if (!isLambdaCallOperator(FD))
13571     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13572 
13573   // Check for defining attributes before the check for redefinition.
13574   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13575     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13576     FD->dropAttr<AliasAttr>();
13577     FD->setInvalidDecl();
13578   }
13579   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13580     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13581     FD->dropAttr<IFuncAttr>();
13582     FD->setInvalidDecl();
13583   }
13584 
13585   // See if this is a redefinition. If 'will have body' is already set, then
13586   // these checks were already performed when it was set.
13587   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13588     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13589 
13590     // If we're skipping the body, we're done. Don't enter the scope.
13591     if (SkipBody && SkipBody->ShouldSkip)
13592       return D;
13593   }
13594 
13595   // Mark this function as "will have a body eventually".  This lets users to
13596   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13597   // this function.
13598   FD->setWillHaveBody();
13599 
13600   // If we are instantiating a generic lambda call operator, push
13601   // a LambdaScopeInfo onto the function stack.  But use the information
13602   // that's already been calculated (ActOnLambdaExpr) to prime the current
13603   // LambdaScopeInfo.
13604   // When the template operator is being specialized, the LambdaScopeInfo,
13605   // has to be properly restored so that tryCaptureVariable doesn't try
13606   // and capture any new variables. In addition when calculating potential
13607   // captures during transformation of nested lambdas, it is necessary to
13608   // have the LSI properly restored.
13609   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13610     assert(inTemplateInstantiation() &&
13611            "There should be an active template instantiation on the stack "
13612            "when instantiating a generic lambda!");
13613     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13614   } else {
13615     // Enter a new function scope
13616     PushFunctionScope();
13617   }
13618 
13619   // Builtin functions cannot be defined.
13620   if (unsigned BuiltinID = FD->getBuiltinID()) {
13621     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13622         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13623       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13624       FD->setInvalidDecl();
13625     }
13626   }
13627 
13628   // The return type of a function definition must be complete
13629   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13630   QualType ResultType = FD->getReturnType();
13631   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13632       !FD->isInvalidDecl() &&
13633       RequireCompleteType(FD->getLocation(), ResultType,
13634                           diag::err_func_def_incomplete_result))
13635     FD->setInvalidDecl();
13636 
13637   if (FnBodyScope)
13638     PushDeclContext(FnBodyScope, FD);
13639 
13640   // Check the validity of our function parameters
13641   CheckParmsForFunctionDef(FD->parameters(),
13642                            /*CheckParameterNames=*/true);
13643 
13644   // Add non-parameter declarations already in the function to the current
13645   // scope.
13646   if (FnBodyScope) {
13647     for (Decl *NPD : FD->decls()) {
13648       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13649       if (!NonParmDecl)
13650         continue;
13651       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13652              "parameters should not be in newly created FD yet");
13653 
13654       // If the decl has a name, make it accessible in the current scope.
13655       if (NonParmDecl->getDeclName())
13656         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13657 
13658       // Similarly, dive into enums and fish their constants out, making them
13659       // accessible in this scope.
13660       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13661         for (auto *EI : ED->enumerators())
13662           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13663       }
13664     }
13665   }
13666 
13667   // Introduce our parameters into the function scope
13668   for (auto Param : FD->parameters()) {
13669     Param->setOwningFunction(FD);
13670 
13671     // If this has an identifier, add it to the scope stack.
13672     if (Param->getIdentifier() && FnBodyScope) {
13673       CheckShadow(FnBodyScope, Param);
13674 
13675       PushOnScopeChains(Param, FnBodyScope);
13676     }
13677   }
13678 
13679   // Ensure that the function's exception specification is instantiated.
13680   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13681     ResolveExceptionSpec(D->getLocation(), FPT);
13682 
13683   // dllimport cannot be applied to non-inline function definitions.
13684   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13685       !FD->isTemplateInstantiation()) {
13686     assert(!FD->hasAttr<DLLExportAttr>());
13687     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13688     FD->setInvalidDecl();
13689     return D;
13690   }
13691   // We want to attach documentation to original Decl (which might be
13692   // a function template).
13693   ActOnDocumentableDecl(D);
13694   if (getCurLexicalContext()->isObjCContainer() &&
13695       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13696       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13697     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13698 
13699   return D;
13700 }
13701 
13702 /// Given the set of return statements within a function body,
13703 /// compute the variables that are subject to the named return value
13704 /// optimization.
13705 ///
13706 /// Each of the variables that is subject to the named return value
13707 /// optimization will be marked as NRVO variables in the AST, and any
13708 /// return statement that has a marked NRVO variable as its NRVO candidate can
13709 /// use the named return value optimization.
13710 ///
13711 /// This function applies a very simplistic algorithm for NRVO: if every return
13712 /// statement in the scope of a variable has the same NRVO candidate, that
13713 /// candidate is an NRVO variable.
13714 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13715   ReturnStmt **Returns = Scope->Returns.data();
13716 
13717   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13718     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13719       if (!NRVOCandidate->isNRVOVariable())
13720         Returns[I]->setNRVOCandidate(nullptr);
13721     }
13722   }
13723 }
13724 
13725 bool Sema::canDelayFunctionBody(const Declarator &D) {
13726   // We can't delay parsing the body of a constexpr function template (yet).
13727   if (D.getDeclSpec().hasConstexprSpecifier())
13728     return false;
13729 
13730   // We can't delay parsing the body of a function template with a deduced
13731   // return type (yet).
13732   if (D.getDeclSpec().hasAutoTypeSpec()) {
13733     // If the placeholder introduces a non-deduced trailing return type,
13734     // we can still delay parsing it.
13735     if (D.getNumTypeObjects()) {
13736       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13737       if (Outer.Kind == DeclaratorChunk::Function &&
13738           Outer.Fun.hasTrailingReturnType()) {
13739         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13740         return Ty.isNull() || !Ty->isUndeducedType();
13741       }
13742     }
13743     return false;
13744   }
13745 
13746   return true;
13747 }
13748 
13749 bool Sema::canSkipFunctionBody(Decl *D) {
13750   // We cannot skip the body of a function (or function template) which is
13751   // constexpr, since we may need to evaluate its body in order to parse the
13752   // rest of the file.
13753   // We cannot skip the body of a function with an undeduced return type,
13754   // because any callers of that function need to know the type.
13755   if (const FunctionDecl *FD = D->getAsFunction()) {
13756     if (FD->isConstexpr())
13757       return false;
13758     // We can't simply call Type::isUndeducedType here, because inside template
13759     // auto can be deduced to a dependent type, which is not considered
13760     // "undeduced".
13761     if (FD->getReturnType()->getContainedDeducedType())
13762       return false;
13763   }
13764   return Consumer.shouldSkipFunctionBody(D);
13765 }
13766 
13767 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13768   if (!Decl)
13769     return nullptr;
13770   if (FunctionDecl *FD = Decl->getAsFunction())
13771     FD->setHasSkippedBody();
13772   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13773     MD->setHasSkippedBody();
13774   return Decl;
13775 }
13776 
13777 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13778   return ActOnFinishFunctionBody(D, BodyArg, false);
13779 }
13780 
13781 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13782 /// body.
13783 class ExitFunctionBodyRAII {
13784 public:
13785   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13786   ~ExitFunctionBodyRAII() {
13787     if (!IsLambda)
13788       S.PopExpressionEvaluationContext();
13789   }
13790 
13791 private:
13792   Sema &S;
13793   bool IsLambda = false;
13794 };
13795 
13796 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13797   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13798 
13799   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13800     if (EscapeInfo.count(BD))
13801       return EscapeInfo[BD];
13802 
13803     bool R = false;
13804     const BlockDecl *CurBD = BD;
13805 
13806     do {
13807       R = !CurBD->doesNotEscape();
13808       if (R)
13809         break;
13810       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13811     } while (CurBD);
13812 
13813     return EscapeInfo[BD] = R;
13814   };
13815 
13816   // If the location where 'self' is implicitly retained is inside a escaping
13817   // block, emit a diagnostic.
13818   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13819        S.ImplicitlyRetainedSelfLocs)
13820     if (IsOrNestedInEscapingBlock(P.second))
13821       S.Diag(P.first, diag::warn_implicitly_retains_self)
13822           << FixItHint::CreateInsertion(P.first, "self->");
13823 }
13824 
13825 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13826                                     bool IsInstantiation) {
13827   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13828 
13829   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13830   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13831 
13832   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13833     CheckCompletedCoroutineBody(FD, Body);
13834 
13835   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13836   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13837   // meant to pop the context added in ActOnStartOfFunctionDef().
13838   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13839 
13840   if (FD) {
13841     FD->setBody(Body);
13842     FD->setWillHaveBody(false);
13843 
13844     if (getLangOpts().CPlusPlus14) {
13845       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13846           FD->getReturnType()->isUndeducedType()) {
13847         // If the function has a deduced result type but contains no 'return'
13848         // statements, the result type as written must be exactly 'auto', and
13849         // the deduced result type is 'void'.
13850         if (!FD->getReturnType()->getAs<AutoType>()) {
13851           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13852               << FD->getReturnType();
13853           FD->setInvalidDecl();
13854         } else {
13855           // Substitute 'void' for the 'auto' in the type.
13856           TypeLoc ResultType = getReturnTypeLoc(FD);
13857           Context.adjustDeducedFunctionResultType(
13858               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13859         }
13860       }
13861     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13862       // In C++11, we don't use 'auto' deduction rules for lambda call
13863       // operators because we don't support return type deduction.
13864       auto *LSI = getCurLambda();
13865       if (LSI->HasImplicitReturnType) {
13866         deduceClosureReturnType(*LSI);
13867 
13868         // C++11 [expr.prim.lambda]p4:
13869         //   [...] if there are no return statements in the compound-statement
13870         //   [the deduced type is] the type void
13871         QualType RetType =
13872             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13873 
13874         // Update the return type to the deduced type.
13875         const FunctionProtoType *Proto =
13876             FD->getType()->getAs<FunctionProtoType>();
13877         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13878                                             Proto->getExtProtoInfo()));
13879       }
13880     }
13881 
13882     // If the function implicitly returns zero (like 'main') or is naked,
13883     // don't complain about missing return statements.
13884     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13885       WP.disableCheckFallThrough();
13886 
13887     // MSVC permits the use of pure specifier (=0) on function definition,
13888     // defined at class scope, warn about this non-standard construct.
13889     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13890       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13891 
13892     if (!FD->isInvalidDecl()) {
13893       // Don't diagnose unused parameters of defaulted or deleted functions.
13894       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13895         DiagnoseUnusedParameters(FD->parameters());
13896       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13897                                              FD->getReturnType(), FD);
13898 
13899       // If this is a structor, we need a vtable.
13900       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13901         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13902       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13903         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13904 
13905       // Try to apply the named return value optimization. We have to check
13906       // if we can do this here because lambdas keep return statements around
13907       // to deduce an implicit return type.
13908       if (FD->getReturnType()->isRecordType() &&
13909           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13910         computeNRVO(Body, getCurFunction());
13911     }
13912 
13913     // GNU warning -Wmissing-prototypes:
13914     //   Warn if a global function is defined without a previous
13915     //   prototype declaration. This warning is issued even if the
13916     //   definition itself provides a prototype. The aim is to detect
13917     //   global functions that fail to be declared in header files.
13918     const FunctionDecl *PossiblePrototype = nullptr;
13919     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13920       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13921 
13922       if (PossiblePrototype) {
13923         // We found a declaration that is not a prototype,
13924         // but that could be a zero-parameter prototype
13925         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13926           TypeLoc TL = TI->getTypeLoc();
13927           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13928             Diag(PossiblePrototype->getLocation(),
13929                  diag::note_declaration_not_a_prototype)
13930                 << (FD->getNumParams() != 0)
13931                 << (FD->getNumParams() == 0
13932                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13933                         : FixItHint{});
13934         }
13935       } else {
13936         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13937             << /* function */ 1
13938             << (FD->getStorageClass() == SC_None
13939                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13940                                                  "static ")
13941                     : FixItHint{});
13942       }
13943 
13944       // GNU warning -Wstrict-prototypes
13945       //   Warn if K&R function is defined without a previous declaration.
13946       //   This warning is issued only if the definition itself does not provide
13947       //   a prototype. Only K&R definitions do not provide a prototype.
13948       //   An empty list in a function declarator that is part of a definition
13949       //   of that function specifies that the function has no parameters
13950       //   (C99 6.7.5.3p14)
13951       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13952           !LangOpts.CPlusPlus) {
13953         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13954         TypeLoc TL = TI->getTypeLoc();
13955         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13956         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13957       }
13958     }
13959 
13960     // Warn on CPUDispatch with an actual body.
13961     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13962       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13963         if (!CmpndBody->body_empty())
13964           Diag(CmpndBody->body_front()->getBeginLoc(),
13965                diag::warn_dispatch_body_ignored);
13966 
13967     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13968       const CXXMethodDecl *KeyFunction;
13969       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13970           MD->isVirtual() &&
13971           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13972           MD == KeyFunction->getCanonicalDecl()) {
13973         // Update the key-function state if necessary for this ABI.
13974         if (FD->isInlined() &&
13975             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13976           Context.setNonKeyFunction(MD);
13977 
13978           // If the newly-chosen key function is already defined, then we
13979           // need to mark the vtable as used retroactively.
13980           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13981           const FunctionDecl *Definition;
13982           if (KeyFunction && KeyFunction->isDefined(Definition))
13983             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13984         } else {
13985           // We just defined they key function; mark the vtable as used.
13986           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13987         }
13988       }
13989     }
13990 
13991     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13992            "Function parsing confused");
13993   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13994     assert(MD == getCurMethodDecl() && "Method parsing confused");
13995     MD->setBody(Body);
13996     if (!MD->isInvalidDecl()) {
13997       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13998                                              MD->getReturnType(), MD);
13999 
14000       if (Body)
14001         computeNRVO(Body, getCurFunction());
14002     }
14003     if (getCurFunction()->ObjCShouldCallSuper) {
14004       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14005           << MD->getSelector().getAsString();
14006       getCurFunction()->ObjCShouldCallSuper = false;
14007     }
14008     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14009       const ObjCMethodDecl *InitMethod = nullptr;
14010       bool isDesignated =
14011           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14012       assert(isDesignated && InitMethod);
14013       (void)isDesignated;
14014 
14015       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14016         auto IFace = MD->getClassInterface();
14017         if (!IFace)
14018           return false;
14019         auto SuperD = IFace->getSuperClass();
14020         if (!SuperD)
14021           return false;
14022         return SuperD->getIdentifier() ==
14023             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14024       };
14025       // Don't issue this warning for unavailable inits or direct subclasses
14026       // of NSObject.
14027       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14028         Diag(MD->getLocation(),
14029              diag::warn_objc_designated_init_missing_super_call);
14030         Diag(InitMethod->getLocation(),
14031              diag::note_objc_designated_init_marked_here);
14032       }
14033       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14034     }
14035     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14036       // Don't issue this warning for unavaialable inits.
14037       if (!MD->isUnavailable())
14038         Diag(MD->getLocation(),
14039              diag::warn_objc_secondary_init_missing_init_call);
14040       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14041     }
14042 
14043     diagnoseImplicitlyRetainedSelf(*this);
14044   } else {
14045     // Parsing the function declaration failed in some way. Pop the fake scope
14046     // we pushed on.
14047     PopFunctionScopeInfo(ActivePolicy, dcl);
14048     return nullptr;
14049   }
14050 
14051   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14052     DiagnoseUnguardedAvailabilityViolations(dcl);
14053 
14054   assert(!getCurFunction()->ObjCShouldCallSuper &&
14055          "This should only be set for ObjC methods, which should have been "
14056          "handled in the block above.");
14057 
14058   // Verify and clean out per-function state.
14059   if (Body && (!FD || !FD->isDefaulted())) {
14060     // C++ constructors that have function-try-blocks can't have return
14061     // statements in the handlers of that block. (C++ [except.handle]p14)
14062     // Verify this.
14063     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14064       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14065 
14066     // Verify that gotos and switch cases don't jump into scopes illegally.
14067     if (getCurFunction()->NeedsScopeChecking() &&
14068         !PP.isCodeCompletionEnabled())
14069       DiagnoseInvalidJumps(Body);
14070 
14071     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14072       if (!Destructor->getParent()->isDependentType())
14073         CheckDestructor(Destructor);
14074 
14075       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14076                                              Destructor->getParent());
14077     }
14078 
14079     // If any errors have occurred, clear out any temporaries that may have
14080     // been leftover. This ensures that these temporaries won't be picked up for
14081     // deletion in some later function.
14082     if (getDiagnostics().hasErrorOccurred() ||
14083         getDiagnostics().getSuppressAllDiagnostics()) {
14084       DiscardCleanupsInEvaluationContext();
14085     }
14086     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14087         !isa<FunctionTemplateDecl>(dcl)) {
14088       // Since the body is valid, issue any analysis-based warnings that are
14089       // enabled.
14090       ActivePolicy = &WP;
14091     }
14092 
14093     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14094         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14095       FD->setInvalidDecl();
14096 
14097     if (FD && FD->hasAttr<NakedAttr>()) {
14098       for (const Stmt *S : Body->children()) {
14099         // Allow local register variables without initializer as they don't
14100         // require prologue.
14101         bool RegisterVariables = false;
14102         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14103           for (const auto *Decl : DS->decls()) {
14104             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14105               RegisterVariables =
14106                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14107               if (!RegisterVariables)
14108                 break;
14109             }
14110           }
14111         }
14112         if (RegisterVariables)
14113           continue;
14114         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14115           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14116           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14117           FD->setInvalidDecl();
14118           break;
14119         }
14120       }
14121     }
14122 
14123     assert(ExprCleanupObjects.size() ==
14124                ExprEvalContexts.back().NumCleanupObjects &&
14125            "Leftover temporaries in function");
14126     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14127     assert(MaybeODRUseExprs.empty() &&
14128            "Leftover expressions for odr-use checking");
14129   }
14130 
14131   if (!IsInstantiation)
14132     PopDeclContext();
14133 
14134   PopFunctionScopeInfo(ActivePolicy, dcl);
14135   // If any errors have occurred, clear out any temporaries that may have
14136   // been leftover. This ensures that these temporaries won't be picked up for
14137   // deletion in some later function.
14138   if (getDiagnostics().hasErrorOccurred()) {
14139     DiscardCleanupsInEvaluationContext();
14140   }
14141 
14142   return dcl;
14143 }
14144 
14145 /// When we finish delayed parsing of an attribute, we must attach it to the
14146 /// relevant Decl.
14147 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14148                                        ParsedAttributes &Attrs) {
14149   // Always attach attributes to the underlying decl.
14150   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14151     D = TD->getTemplatedDecl();
14152   ProcessDeclAttributeList(S, D, Attrs);
14153 
14154   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14155     if (Method->isStatic())
14156       checkThisInStaticMemberFunctionAttributes(Method);
14157 }
14158 
14159 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14160 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14161 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14162                                           IdentifierInfo &II, Scope *S) {
14163   // Find the scope in which the identifier is injected and the corresponding
14164   // DeclContext.
14165   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14166   // In that case, we inject the declaration into the translation unit scope
14167   // instead.
14168   Scope *BlockScope = S;
14169   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14170     BlockScope = BlockScope->getParent();
14171 
14172   Scope *ContextScope = BlockScope;
14173   while (!ContextScope->getEntity())
14174     ContextScope = ContextScope->getParent();
14175   ContextRAII SavedContext(*this, ContextScope->getEntity());
14176 
14177   // Before we produce a declaration for an implicitly defined
14178   // function, see whether there was a locally-scoped declaration of
14179   // this name as a function or variable. If so, use that
14180   // (non-visible) declaration, and complain about it.
14181   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14182   if (ExternCPrev) {
14183     // We still need to inject the function into the enclosing block scope so
14184     // that later (non-call) uses can see it.
14185     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14186 
14187     // C89 footnote 38:
14188     //   If in fact it is not defined as having type "function returning int",
14189     //   the behavior is undefined.
14190     if (!isa<FunctionDecl>(ExternCPrev) ||
14191         !Context.typesAreCompatible(
14192             cast<FunctionDecl>(ExternCPrev)->getType(),
14193             Context.getFunctionNoProtoType(Context.IntTy))) {
14194       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14195           << ExternCPrev << !getLangOpts().C99;
14196       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14197       return ExternCPrev;
14198     }
14199   }
14200 
14201   // Extension in C99.  Legal in C90, but warn about it.
14202   unsigned diag_id;
14203   if (II.getName().startswith("__builtin_"))
14204     diag_id = diag::warn_builtin_unknown;
14205   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14206   else if (getLangOpts().OpenCL)
14207     diag_id = diag::err_opencl_implicit_function_decl;
14208   else if (getLangOpts().C99)
14209     diag_id = diag::ext_implicit_function_decl;
14210   else
14211     diag_id = diag::warn_implicit_function_decl;
14212   Diag(Loc, diag_id) << &II;
14213 
14214   // If we found a prior declaration of this function, don't bother building
14215   // another one. We've already pushed that one into scope, so there's nothing
14216   // more to do.
14217   if (ExternCPrev)
14218     return ExternCPrev;
14219 
14220   // Because typo correction is expensive, only do it if the implicit
14221   // function declaration is going to be treated as an error.
14222   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14223     TypoCorrection Corrected;
14224     DeclFilterCCC<FunctionDecl> CCC{};
14225     if (S && (Corrected =
14226                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14227                               S, nullptr, CCC, CTK_NonError)))
14228       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14229                    /*ErrorRecovery*/false);
14230   }
14231 
14232   // Set a Declarator for the implicit definition: int foo();
14233   const char *Dummy;
14234   AttributeFactory attrFactory;
14235   DeclSpec DS(attrFactory);
14236   unsigned DiagID;
14237   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14238                                   Context.getPrintingPolicy());
14239   (void)Error; // Silence warning.
14240   assert(!Error && "Error setting up implicit decl!");
14241   SourceLocation NoLoc;
14242   Declarator D(DS, DeclaratorContext::BlockContext);
14243   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14244                                              /*IsAmbiguous=*/false,
14245                                              /*LParenLoc=*/NoLoc,
14246                                              /*Params=*/nullptr,
14247                                              /*NumParams=*/0,
14248                                              /*EllipsisLoc=*/NoLoc,
14249                                              /*RParenLoc=*/NoLoc,
14250                                              /*RefQualifierIsLvalueRef=*/true,
14251                                              /*RefQualifierLoc=*/NoLoc,
14252                                              /*MutableLoc=*/NoLoc, EST_None,
14253                                              /*ESpecRange=*/SourceRange(),
14254                                              /*Exceptions=*/nullptr,
14255                                              /*ExceptionRanges=*/nullptr,
14256                                              /*NumExceptions=*/0,
14257                                              /*NoexceptExpr=*/nullptr,
14258                                              /*ExceptionSpecTokens=*/nullptr,
14259                                              /*DeclsInPrototype=*/None, Loc,
14260                                              Loc, D),
14261                 std::move(DS.getAttributes()), SourceLocation());
14262   D.SetIdentifier(&II, Loc);
14263 
14264   // Insert this function into the enclosing block scope.
14265   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14266   FD->setImplicit();
14267 
14268   AddKnownFunctionAttributes(FD);
14269 
14270   return FD;
14271 }
14272 
14273 /// Adds any function attributes that we know a priori based on
14274 /// the declaration of this function.
14275 ///
14276 /// These attributes can apply both to implicitly-declared builtins
14277 /// (like __builtin___printf_chk) or to library-declared functions
14278 /// like NSLog or printf.
14279 ///
14280 /// We need to check for duplicate attributes both here and where user-written
14281 /// attributes are applied to declarations.
14282 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14283   if (FD->isInvalidDecl())
14284     return;
14285 
14286   // If this is a built-in function, map its builtin attributes to
14287   // actual attributes.
14288   if (unsigned BuiltinID = FD->getBuiltinID()) {
14289     // Handle printf-formatting attributes.
14290     unsigned FormatIdx;
14291     bool HasVAListArg;
14292     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14293       if (!FD->hasAttr<FormatAttr>()) {
14294         const char *fmt = "printf";
14295         unsigned int NumParams = FD->getNumParams();
14296         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14297             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14298           fmt = "NSString";
14299         FD->addAttr(FormatAttr::CreateImplicit(Context,
14300                                                &Context.Idents.get(fmt),
14301                                                FormatIdx+1,
14302                                                HasVAListArg ? 0 : FormatIdx+2,
14303                                                FD->getLocation()));
14304       }
14305     }
14306     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14307                                              HasVAListArg)) {
14308      if (!FD->hasAttr<FormatAttr>())
14309        FD->addAttr(FormatAttr::CreateImplicit(Context,
14310                                               &Context.Idents.get("scanf"),
14311                                               FormatIdx+1,
14312                                               HasVAListArg ? 0 : FormatIdx+2,
14313                                               FD->getLocation()));
14314     }
14315 
14316     // Handle automatically recognized callbacks.
14317     SmallVector<int, 4> Encoding;
14318     if (!FD->hasAttr<CallbackAttr>() &&
14319         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14320       FD->addAttr(CallbackAttr::CreateImplicit(
14321           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14322 
14323     // Mark const if we don't care about errno and that is the only thing
14324     // preventing the function from being const. This allows IRgen to use LLVM
14325     // intrinsics for such functions.
14326     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14327         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14328       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14329 
14330     // We make "fma" on some platforms const because we know it does not set
14331     // errno in those environments even though it could set errno based on the
14332     // C standard.
14333     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14334     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14335         !FD->hasAttr<ConstAttr>()) {
14336       switch (BuiltinID) {
14337       case Builtin::BI__builtin_fma:
14338       case Builtin::BI__builtin_fmaf:
14339       case Builtin::BI__builtin_fmal:
14340       case Builtin::BIfma:
14341       case Builtin::BIfmaf:
14342       case Builtin::BIfmal:
14343         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14344         break;
14345       default:
14346         break;
14347       }
14348     }
14349 
14350     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14351         !FD->hasAttr<ReturnsTwiceAttr>())
14352       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14353                                          FD->getLocation()));
14354     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14355       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14356     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14357       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14358     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14359       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14360     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14361         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14362       // Add the appropriate attribute, depending on the CUDA compilation mode
14363       // and which target the builtin belongs to. For example, during host
14364       // compilation, aux builtins are __device__, while the rest are __host__.
14365       if (getLangOpts().CUDAIsDevice !=
14366           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14367         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14368       else
14369         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14370     }
14371   }
14372 
14373   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14374   // throw, add an implicit nothrow attribute to any extern "C" function we come
14375   // across.
14376   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14377       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14378     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14379     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14380       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14381   }
14382 
14383   IdentifierInfo *Name = FD->getIdentifier();
14384   if (!Name)
14385     return;
14386   if ((!getLangOpts().CPlusPlus &&
14387        FD->getDeclContext()->isTranslationUnit()) ||
14388       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14389        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14390        LinkageSpecDecl::lang_c)) {
14391     // Okay: this could be a libc/libm/Objective-C function we know
14392     // about.
14393   } else
14394     return;
14395 
14396   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14397     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14398     // target-specific builtins, perhaps?
14399     if (!FD->hasAttr<FormatAttr>())
14400       FD->addAttr(FormatAttr::CreateImplicit(Context,
14401                                              &Context.Idents.get("printf"), 2,
14402                                              Name->isStr("vasprintf") ? 0 : 3,
14403                                              FD->getLocation()));
14404   }
14405 
14406   if (Name->isStr("__CFStringMakeConstantString")) {
14407     // We already have a __builtin___CFStringMakeConstantString,
14408     // but builds that use -fno-constant-cfstrings don't go through that.
14409     if (!FD->hasAttr<FormatArgAttr>())
14410       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14411                                                 FD->getLocation()));
14412   }
14413 }
14414 
14415 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14416                                     TypeSourceInfo *TInfo) {
14417   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14418   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14419 
14420   if (!TInfo) {
14421     assert(D.isInvalidType() && "no declarator info for valid type");
14422     TInfo = Context.getTrivialTypeSourceInfo(T);
14423   }
14424 
14425   // Scope manipulation handled by caller.
14426   TypedefDecl *NewTD =
14427       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14428                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14429 
14430   // Bail out immediately if we have an invalid declaration.
14431   if (D.isInvalidType()) {
14432     NewTD->setInvalidDecl();
14433     return NewTD;
14434   }
14435 
14436   if (D.getDeclSpec().isModulePrivateSpecified()) {
14437     if (CurContext->isFunctionOrMethod())
14438       Diag(NewTD->getLocation(), diag::err_module_private_local)
14439         << 2 << NewTD->getDeclName()
14440         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14441         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14442     else
14443       NewTD->setModulePrivate();
14444   }
14445 
14446   // C++ [dcl.typedef]p8:
14447   //   If the typedef declaration defines an unnamed class (or
14448   //   enum), the first typedef-name declared by the declaration
14449   //   to be that class type (or enum type) is used to denote the
14450   //   class type (or enum type) for linkage purposes only.
14451   // We need to check whether the type was declared in the declaration.
14452   switch (D.getDeclSpec().getTypeSpecType()) {
14453   case TST_enum:
14454   case TST_struct:
14455   case TST_interface:
14456   case TST_union:
14457   case TST_class: {
14458     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14459     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14460     break;
14461   }
14462 
14463   default:
14464     break;
14465   }
14466 
14467   return NewTD;
14468 }
14469 
14470 /// Check that this is a valid underlying type for an enum declaration.
14471 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14472   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14473   QualType T = TI->getType();
14474 
14475   if (T->isDependentType())
14476     return false;
14477 
14478   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14479     if (BT->isInteger())
14480       return false;
14481 
14482   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14483   return true;
14484 }
14485 
14486 /// Check whether this is a valid redeclaration of a previous enumeration.
14487 /// \return true if the redeclaration was invalid.
14488 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14489                                   QualType EnumUnderlyingTy, bool IsFixed,
14490                                   const EnumDecl *Prev) {
14491   if (IsScoped != Prev->isScoped()) {
14492     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14493       << Prev->isScoped();
14494     Diag(Prev->getLocation(), diag::note_previous_declaration);
14495     return true;
14496   }
14497 
14498   if (IsFixed && Prev->isFixed()) {
14499     if (!EnumUnderlyingTy->isDependentType() &&
14500         !Prev->getIntegerType()->isDependentType() &&
14501         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14502                                         Prev->getIntegerType())) {
14503       // TODO: Highlight the underlying type of the redeclaration.
14504       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14505         << EnumUnderlyingTy << Prev->getIntegerType();
14506       Diag(Prev->getLocation(), diag::note_previous_declaration)
14507           << Prev->getIntegerTypeRange();
14508       return true;
14509     }
14510   } else if (IsFixed != Prev->isFixed()) {
14511     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14512       << Prev->isFixed();
14513     Diag(Prev->getLocation(), diag::note_previous_declaration);
14514     return true;
14515   }
14516 
14517   return false;
14518 }
14519 
14520 /// Get diagnostic %select index for tag kind for
14521 /// redeclaration diagnostic message.
14522 /// WARNING: Indexes apply to particular diagnostics only!
14523 ///
14524 /// \returns diagnostic %select index.
14525 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14526   switch (Tag) {
14527   case TTK_Struct: return 0;
14528   case TTK_Interface: return 1;
14529   case TTK_Class:  return 2;
14530   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14531   }
14532 }
14533 
14534 /// Determine if tag kind is a class-key compatible with
14535 /// class for redeclaration (class, struct, or __interface).
14536 ///
14537 /// \returns true iff the tag kind is compatible.
14538 static bool isClassCompatTagKind(TagTypeKind Tag)
14539 {
14540   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14541 }
14542 
14543 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14544                                              TagTypeKind TTK) {
14545   if (isa<TypedefDecl>(PrevDecl))
14546     return NTK_Typedef;
14547   else if (isa<TypeAliasDecl>(PrevDecl))
14548     return NTK_TypeAlias;
14549   else if (isa<ClassTemplateDecl>(PrevDecl))
14550     return NTK_Template;
14551   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14552     return NTK_TypeAliasTemplate;
14553   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14554     return NTK_TemplateTemplateArgument;
14555   switch (TTK) {
14556   case TTK_Struct:
14557   case TTK_Interface:
14558   case TTK_Class:
14559     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14560   case TTK_Union:
14561     return NTK_NonUnion;
14562   case TTK_Enum:
14563     return NTK_NonEnum;
14564   }
14565   llvm_unreachable("invalid TTK");
14566 }
14567 
14568 /// Determine whether a tag with a given kind is acceptable
14569 /// as a redeclaration of the given tag declaration.
14570 ///
14571 /// \returns true if the new tag kind is acceptable, false otherwise.
14572 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14573                                         TagTypeKind NewTag, bool isDefinition,
14574                                         SourceLocation NewTagLoc,
14575                                         const IdentifierInfo *Name) {
14576   // C++ [dcl.type.elab]p3:
14577   //   The class-key or enum keyword present in the
14578   //   elaborated-type-specifier shall agree in kind with the
14579   //   declaration to which the name in the elaborated-type-specifier
14580   //   refers. This rule also applies to the form of
14581   //   elaborated-type-specifier that declares a class-name or
14582   //   friend class since it can be construed as referring to the
14583   //   definition of the class. Thus, in any
14584   //   elaborated-type-specifier, the enum keyword shall be used to
14585   //   refer to an enumeration (7.2), the union class-key shall be
14586   //   used to refer to a union (clause 9), and either the class or
14587   //   struct class-key shall be used to refer to a class (clause 9)
14588   //   declared using the class or struct class-key.
14589   TagTypeKind OldTag = Previous->getTagKind();
14590   if (OldTag != NewTag &&
14591       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14592     return false;
14593 
14594   // Tags are compatible, but we might still want to warn on mismatched tags.
14595   // Non-class tags can't be mismatched at this point.
14596   if (!isClassCompatTagKind(NewTag))
14597     return true;
14598 
14599   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14600   // by our warning analysis. We don't want to warn about mismatches with (eg)
14601   // declarations in system headers that are designed to be specialized, but if
14602   // a user asks us to warn, we should warn if their code contains mismatched
14603   // declarations.
14604   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14605     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14606                                       Loc);
14607   };
14608   if (IsIgnoredLoc(NewTagLoc))
14609     return true;
14610 
14611   auto IsIgnored = [&](const TagDecl *Tag) {
14612     return IsIgnoredLoc(Tag->getLocation());
14613   };
14614   while (IsIgnored(Previous)) {
14615     Previous = Previous->getPreviousDecl();
14616     if (!Previous)
14617       return true;
14618     OldTag = Previous->getTagKind();
14619   }
14620 
14621   bool isTemplate = false;
14622   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14623     isTemplate = Record->getDescribedClassTemplate();
14624 
14625   if (inTemplateInstantiation()) {
14626     if (OldTag != NewTag) {
14627       // In a template instantiation, do not offer fix-its for tag mismatches
14628       // since they usually mess up the template instead of fixing the problem.
14629       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14630         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14631         << getRedeclDiagFromTagKind(OldTag);
14632       // FIXME: Note previous location?
14633     }
14634     return true;
14635   }
14636 
14637   if (isDefinition) {
14638     // On definitions, check all previous tags and issue a fix-it for each
14639     // one that doesn't match the current tag.
14640     if (Previous->getDefinition()) {
14641       // Don't suggest fix-its for redefinitions.
14642       return true;
14643     }
14644 
14645     bool previousMismatch = false;
14646     for (const TagDecl *I : Previous->redecls()) {
14647       if (I->getTagKind() != NewTag) {
14648         // Ignore previous declarations for which the warning was disabled.
14649         if (IsIgnored(I))
14650           continue;
14651 
14652         if (!previousMismatch) {
14653           previousMismatch = true;
14654           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14655             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14656             << getRedeclDiagFromTagKind(I->getTagKind());
14657         }
14658         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14659           << getRedeclDiagFromTagKind(NewTag)
14660           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14661                TypeWithKeyword::getTagTypeKindName(NewTag));
14662       }
14663     }
14664     return true;
14665   }
14666 
14667   // Identify the prevailing tag kind: this is the kind of the definition (if
14668   // there is a non-ignored definition), or otherwise the kind of the prior
14669   // (non-ignored) declaration.
14670   const TagDecl *PrevDef = Previous->getDefinition();
14671   if (PrevDef && IsIgnored(PrevDef))
14672     PrevDef = nullptr;
14673   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14674   if (Redecl->getTagKind() != NewTag) {
14675     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14676       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14677       << getRedeclDiagFromTagKind(OldTag);
14678     Diag(Redecl->getLocation(), diag::note_previous_use);
14679 
14680     // If there is a previous definition, suggest a fix-it.
14681     if (PrevDef) {
14682       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14683         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14684         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14685              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14686     }
14687   }
14688 
14689   return true;
14690 }
14691 
14692 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14693 /// from an outer enclosing namespace or file scope inside a friend declaration.
14694 /// This should provide the commented out code in the following snippet:
14695 ///   namespace N {
14696 ///     struct X;
14697 ///     namespace M {
14698 ///       struct Y { friend struct /*N::*/ X; };
14699 ///     }
14700 ///   }
14701 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14702                                          SourceLocation NameLoc) {
14703   // While the decl is in a namespace, do repeated lookup of that name and see
14704   // if we get the same namespace back.  If we do not, continue until
14705   // translation unit scope, at which point we have a fully qualified NNS.
14706   SmallVector<IdentifierInfo *, 4> Namespaces;
14707   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14708   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14709     // This tag should be declared in a namespace, which can only be enclosed by
14710     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14711     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14712     if (!Namespace || Namespace->isAnonymousNamespace())
14713       return FixItHint();
14714     IdentifierInfo *II = Namespace->getIdentifier();
14715     Namespaces.push_back(II);
14716     NamedDecl *Lookup = SemaRef.LookupSingleName(
14717         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14718     if (Lookup == Namespace)
14719       break;
14720   }
14721 
14722   // Once we have all the namespaces, reverse them to go outermost first, and
14723   // build an NNS.
14724   SmallString<64> Insertion;
14725   llvm::raw_svector_ostream OS(Insertion);
14726   if (DC->isTranslationUnit())
14727     OS << "::";
14728   std::reverse(Namespaces.begin(), Namespaces.end());
14729   for (auto *II : Namespaces)
14730     OS << II->getName() << "::";
14731   return FixItHint::CreateInsertion(NameLoc, Insertion);
14732 }
14733 
14734 /// Determine whether a tag originally declared in context \p OldDC can
14735 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14736 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14737 /// using-declaration).
14738 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14739                                          DeclContext *NewDC) {
14740   OldDC = OldDC->getRedeclContext();
14741   NewDC = NewDC->getRedeclContext();
14742 
14743   if (OldDC->Equals(NewDC))
14744     return true;
14745 
14746   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14747   // encloses the other).
14748   if (S.getLangOpts().MSVCCompat &&
14749       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14750     return true;
14751 
14752   return false;
14753 }
14754 
14755 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14756 /// former case, Name will be non-null.  In the later case, Name will be null.
14757 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14758 /// reference/declaration/definition of a tag.
14759 ///
14760 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14761 /// trailing-type-specifier) other than one in an alias-declaration.
14762 ///
14763 /// \param SkipBody If non-null, will be set to indicate if the caller should
14764 /// skip the definition of this tag and treat it as if it were a declaration.
14765 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14766                      SourceLocation KWLoc, CXXScopeSpec &SS,
14767                      IdentifierInfo *Name, SourceLocation NameLoc,
14768                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14769                      SourceLocation ModulePrivateLoc,
14770                      MultiTemplateParamsArg TemplateParameterLists,
14771                      bool &OwnedDecl, bool &IsDependent,
14772                      SourceLocation ScopedEnumKWLoc,
14773                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14774                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14775                      SkipBodyInfo *SkipBody) {
14776   // If this is not a definition, it must have a name.
14777   IdentifierInfo *OrigName = Name;
14778   assert((Name != nullptr || TUK == TUK_Definition) &&
14779          "Nameless record must be a definition!");
14780   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14781 
14782   OwnedDecl = false;
14783   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14784   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14785 
14786   // FIXME: Check member specializations more carefully.
14787   bool isMemberSpecialization = false;
14788   bool Invalid = false;
14789 
14790   // We only need to do this matching if we have template parameters
14791   // or a scope specifier, which also conveniently avoids this work
14792   // for non-C++ cases.
14793   if (TemplateParameterLists.size() > 0 ||
14794       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14795     if (TemplateParameterList *TemplateParams =
14796             MatchTemplateParametersToScopeSpecifier(
14797                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14798                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14799       if (Kind == TTK_Enum) {
14800         Diag(KWLoc, diag::err_enum_template);
14801         return nullptr;
14802       }
14803 
14804       if (TemplateParams->size() > 0) {
14805         // This is a declaration or definition of a class template (which may
14806         // be a member of another template).
14807 
14808         if (Invalid)
14809           return nullptr;
14810 
14811         OwnedDecl = false;
14812         DeclResult Result = CheckClassTemplate(
14813             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14814             AS, ModulePrivateLoc,
14815             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14816             TemplateParameterLists.data(), SkipBody);
14817         return Result.get();
14818       } else {
14819         // The "template<>" header is extraneous.
14820         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14821           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14822         isMemberSpecialization = true;
14823       }
14824     }
14825   }
14826 
14827   // Figure out the underlying type if this a enum declaration. We need to do
14828   // this early, because it's needed to detect if this is an incompatible
14829   // redeclaration.
14830   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14831   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14832 
14833   if (Kind == TTK_Enum) {
14834     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14835       // No underlying type explicitly specified, or we failed to parse the
14836       // type, default to int.
14837       EnumUnderlying = Context.IntTy.getTypePtr();
14838     } else if (UnderlyingType.get()) {
14839       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14840       // integral type; any cv-qualification is ignored.
14841       TypeSourceInfo *TI = nullptr;
14842       GetTypeFromParser(UnderlyingType.get(), &TI);
14843       EnumUnderlying = TI;
14844 
14845       if (CheckEnumUnderlyingType(TI))
14846         // Recover by falling back to int.
14847         EnumUnderlying = Context.IntTy.getTypePtr();
14848 
14849       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14850                                           UPPC_FixedUnderlyingType))
14851         EnumUnderlying = Context.IntTy.getTypePtr();
14852 
14853     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14854       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14855       // of 'int'. However, if this is an unfixed forward declaration, don't set
14856       // the underlying type unless the user enables -fms-compatibility. This
14857       // makes unfixed forward declared enums incomplete and is more conforming.
14858       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14859         EnumUnderlying = Context.IntTy.getTypePtr();
14860     }
14861   }
14862 
14863   DeclContext *SearchDC = CurContext;
14864   DeclContext *DC = CurContext;
14865   bool isStdBadAlloc = false;
14866   bool isStdAlignValT = false;
14867 
14868   RedeclarationKind Redecl = forRedeclarationInCurContext();
14869   if (TUK == TUK_Friend || TUK == TUK_Reference)
14870     Redecl = NotForRedeclaration;
14871 
14872   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14873   /// implemented asks for structural equivalence checking, the returned decl
14874   /// here is passed back to the parser, allowing the tag body to be parsed.
14875   auto createTagFromNewDecl = [&]() -> TagDecl * {
14876     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14877     // If there is an identifier, use the location of the identifier as the
14878     // location of the decl, otherwise use the location of the struct/union
14879     // keyword.
14880     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14881     TagDecl *New = nullptr;
14882 
14883     if (Kind == TTK_Enum) {
14884       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14885                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14886       // If this is an undefined enum, bail.
14887       if (TUK != TUK_Definition && !Invalid)
14888         return nullptr;
14889       if (EnumUnderlying) {
14890         EnumDecl *ED = cast<EnumDecl>(New);
14891         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14892           ED->setIntegerTypeSourceInfo(TI);
14893         else
14894           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14895         ED->setPromotionType(ED->getIntegerType());
14896       }
14897     } else { // struct/union
14898       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14899                                nullptr);
14900     }
14901 
14902     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14903       // Add alignment attributes if necessary; these attributes are checked
14904       // when the ASTContext lays out the structure.
14905       //
14906       // It is important for implementing the correct semantics that this
14907       // happen here (in ActOnTag). The #pragma pack stack is
14908       // maintained as a result of parser callbacks which can occur at
14909       // many points during the parsing of a struct declaration (because
14910       // the #pragma tokens are effectively skipped over during the
14911       // parsing of the struct).
14912       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14913         AddAlignmentAttributesForRecord(RD);
14914         AddMsStructLayoutForRecord(RD);
14915       }
14916     }
14917     New->setLexicalDeclContext(CurContext);
14918     return New;
14919   };
14920 
14921   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14922   if (Name && SS.isNotEmpty()) {
14923     // We have a nested-name tag ('struct foo::bar').
14924 
14925     // Check for invalid 'foo::'.
14926     if (SS.isInvalid()) {
14927       Name = nullptr;
14928       goto CreateNewDecl;
14929     }
14930 
14931     // If this is a friend or a reference to a class in a dependent
14932     // context, don't try to make a decl for it.
14933     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14934       DC = computeDeclContext(SS, false);
14935       if (!DC) {
14936         IsDependent = true;
14937         return nullptr;
14938       }
14939     } else {
14940       DC = computeDeclContext(SS, true);
14941       if (!DC) {
14942         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14943           << SS.getRange();
14944         return nullptr;
14945       }
14946     }
14947 
14948     if (RequireCompleteDeclContext(SS, DC))
14949       return nullptr;
14950 
14951     SearchDC = DC;
14952     // Look-up name inside 'foo::'.
14953     LookupQualifiedName(Previous, DC);
14954 
14955     if (Previous.isAmbiguous())
14956       return nullptr;
14957 
14958     if (Previous.empty()) {
14959       // Name lookup did not find anything. However, if the
14960       // nested-name-specifier refers to the current instantiation,
14961       // and that current instantiation has any dependent base
14962       // classes, we might find something at instantiation time: treat
14963       // this as a dependent elaborated-type-specifier.
14964       // But this only makes any sense for reference-like lookups.
14965       if (Previous.wasNotFoundInCurrentInstantiation() &&
14966           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14967         IsDependent = true;
14968         return nullptr;
14969       }
14970 
14971       // A tag 'foo::bar' must already exist.
14972       Diag(NameLoc, diag::err_not_tag_in_scope)
14973         << Kind << Name << DC << SS.getRange();
14974       Name = nullptr;
14975       Invalid = true;
14976       goto CreateNewDecl;
14977     }
14978   } else if (Name) {
14979     // C++14 [class.mem]p14:
14980     //   If T is the name of a class, then each of the following shall have a
14981     //   name different from T:
14982     //    -- every member of class T that is itself a type
14983     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14984         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14985       return nullptr;
14986 
14987     // If this is a named struct, check to see if there was a previous forward
14988     // declaration or definition.
14989     // FIXME: We're looking into outer scopes here, even when we
14990     // shouldn't be. Doing so can result in ambiguities that we
14991     // shouldn't be diagnosing.
14992     LookupName(Previous, S);
14993 
14994     // When declaring or defining a tag, ignore ambiguities introduced
14995     // by types using'ed into this scope.
14996     if (Previous.isAmbiguous() &&
14997         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14998       LookupResult::Filter F = Previous.makeFilter();
14999       while (F.hasNext()) {
15000         NamedDecl *ND = F.next();
15001         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15002                 SearchDC->getRedeclContext()))
15003           F.erase();
15004       }
15005       F.done();
15006     }
15007 
15008     // C++11 [namespace.memdef]p3:
15009     //   If the name in a friend declaration is neither qualified nor
15010     //   a template-id and the declaration is a function or an
15011     //   elaborated-type-specifier, the lookup to determine whether
15012     //   the entity has been previously declared shall not consider
15013     //   any scopes outside the innermost enclosing namespace.
15014     //
15015     // MSVC doesn't implement the above rule for types, so a friend tag
15016     // declaration may be a redeclaration of a type declared in an enclosing
15017     // scope.  They do implement this rule for friend functions.
15018     //
15019     // Does it matter that this should be by scope instead of by
15020     // semantic context?
15021     if (!Previous.empty() && TUK == TUK_Friend) {
15022       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15023       LookupResult::Filter F = Previous.makeFilter();
15024       bool FriendSawTagOutsideEnclosingNamespace = false;
15025       while (F.hasNext()) {
15026         NamedDecl *ND = F.next();
15027         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15028         if (DC->isFileContext() &&
15029             !EnclosingNS->Encloses(ND->getDeclContext())) {
15030           if (getLangOpts().MSVCCompat)
15031             FriendSawTagOutsideEnclosingNamespace = true;
15032           else
15033             F.erase();
15034         }
15035       }
15036       F.done();
15037 
15038       // Diagnose this MSVC extension in the easy case where lookup would have
15039       // unambiguously found something outside the enclosing namespace.
15040       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15041         NamedDecl *ND = Previous.getFoundDecl();
15042         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15043             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15044       }
15045     }
15046 
15047     // Note:  there used to be some attempt at recovery here.
15048     if (Previous.isAmbiguous())
15049       return nullptr;
15050 
15051     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15052       // FIXME: This makes sure that we ignore the contexts associated
15053       // with C structs, unions, and enums when looking for a matching
15054       // tag declaration or definition. See the similar lookup tweak
15055       // in Sema::LookupName; is there a better way to deal with this?
15056       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15057         SearchDC = SearchDC->getParent();
15058     }
15059   }
15060 
15061   if (Previous.isSingleResult() &&
15062       Previous.getFoundDecl()->isTemplateParameter()) {
15063     // Maybe we will complain about the shadowed template parameter.
15064     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15065     // Just pretend that we didn't see the previous declaration.
15066     Previous.clear();
15067   }
15068 
15069   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15070       DC->Equals(getStdNamespace())) {
15071     if (Name->isStr("bad_alloc")) {
15072       // This is a declaration of or a reference to "std::bad_alloc".
15073       isStdBadAlloc = true;
15074 
15075       // If std::bad_alloc has been implicitly declared (but made invisible to
15076       // name lookup), fill in this implicit declaration as the previous
15077       // declaration, so that the declarations get chained appropriately.
15078       if (Previous.empty() && StdBadAlloc)
15079         Previous.addDecl(getStdBadAlloc());
15080     } else if (Name->isStr("align_val_t")) {
15081       isStdAlignValT = true;
15082       if (Previous.empty() && StdAlignValT)
15083         Previous.addDecl(getStdAlignValT());
15084     }
15085   }
15086 
15087   // If we didn't find a previous declaration, and this is a reference
15088   // (or friend reference), move to the correct scope.  In C++, we
15089   // also need to do a redeclaration lookup there, just in case
15090   // there's a shadow friend decl.
15091   if (Name && Previous.empty() &&
15092       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15093     if (Invalid) goto CreateNewDecl;
15094     assert(SS.isEmpty());
15095 
15096     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15097       // C++ [basic.scope.pdecl]p5:
15098       //   -- for an elaborated-type-specifier of the form
15099       //
15100       //          class-key identifier
15101       //
15102       //      if the elaborated-type-specifier is used in the
15103       //      decl-specifier-seq or parameter-declaration-clause of a
15104       //      function defined in namespace scope, the identifier is
15105       //      declared as a class-name in the namespace that contains
15106       //      the declaration; otherwise, except as a friend
15107       //      declaration, the identifier is declared in the smallest
15108       //      non-class, non-function-prototype scope that contains the
15109       //      declaration.
15110       //
15111       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15112       // C structs and unions.
15113       //
15114       // It is an error in C++ to declare (rather than define) an enum
15115       // type, including via an elaborated type specifier.  We'll
15116       // diagnose that later; for now, declare the enum in the same
15117       // scope as we would have picked for any other tag type.
15118       //
15119       // GNU C also supports this behavior as part of its incomplete
15120       // enum types extension, while GNU C++ does not.
15121       //
15122       // Find the context where we'll be declaring the tag.
15123       // FIXME: We would like to maintain the current DeclContext as the
15124       // lexical context,
15125       SearchDC = getTagInjectionContext(SearchDC);
15126 
15127       // Find the scope where we'll be declaring the tag.
15128       S = getTagInjectionScope(S, getLangOpts());
15129     } else {
15130       assert(TUK == TUK_Friend);
15131       // C++ [namespace.memdef]p3:
15132       //   If a friend declaration in a non-local class first declares a
15133       //   class or function, the friend class or function is a member of
15134       //   the innermost enclosing namespace.
15135       SearchDC = SearchDC->getEnclosingNamespaceContext();
15136     }
15137 
15138     // In C++, we need to do a redeclaration lookup to properly
15139     // diagnose some problems.
15140     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15141     // hidden declaration so that we don't get ambiguity errors when using a
15142     // type declared by an elaborated-type-specifier.  In C that is not correct
15143     // and we should instead merge compatible types found by lookup.
15144     if (getLangOpts().CPlusPlus) {
15145       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15146       LookupQualifiedName(Previous, SearchDC);
15147     } else {
15148       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15149       LookupName(Previous, S);
15150     }
15151   }
15152 
15153   // If we have a known previous declaration to use, then use it.
15154   if (Previous.empty() && SkipBody && SkipBody->Previous)
15155     Previous.addDecl(SkipBody->Previous);
15156 
15157   if (!Previous.empty()) {
15158     NamedDecl *PrevDecl = Previous.getFoundDecl();
15159     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15160 
15161     // It's okay to have a tag decl in the same scope as a typedef
15162     // which hides a tag decl in the same scope.  Finding this
15163     // insanity with a redeclaration lookup can only actually happen
15164     // in C++.
15165     //
15166     // This is also okay for elaborated-type-specifiers, which is
15167     // technically forbidden by the current standard but which is
15168     // okay according to the likely resolution of an open issue;
15169     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15170     if (getLangOpts().CPlusPlus) {
15171       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15172         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15173           TagDecl *Tag = TT->getDecl();
15174           if (Tag->getDeclName() == Name &&
15175               Tag->getDeclContext()->getRedeclContext()
15176                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15177             PrevDecl = Tag;
15178             Previous.clear();
15179             Previous.addDecl(Tag);
15180             Previous.resolveKind();
15181           }
15182         }
15183       }
15184     }
15185 
15186     // If this is a redeclaration of a using shadow declaration, it must
15187     // declare a tag in the same context. In MSVC mode, we allow a
15188     // redefinition if either context is within the other.
15189     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15190       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15191       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15192           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15193           !(OldTag && isAcceptableTagRedeclContext(
15194                           *this, OldTag->getDeclContext(), SearchDC))) {
15195         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15196         Diag(Shadow->getTargetDecl()->getLocation(),
15197              diag::note_using_decl_target);
15198         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15199             << 0;
15200         // Recover by ignoring the old declaration.
15201         Previous.clear();
15202         goto CreateNewDecl;
15203       }
15204     }
15205 
15206     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15207       // If this is a use of a previous tag, or if the tag is already declared
15208       // in the same scope (so that the definition/declaration completes or
15209       // rementions the tag), reuse the decl.
15210       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15211           isDeclInScope(DirectPrevDecl, SearchDC, S,
15212                         SS.isNotEmpty() || isMemberSpecialization)) {
15213         // Make sure that this wasn't declared as an enum and now used as a
15214         // struct or something similar.
15215         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15216                                           TUK == TUK_Definition, KWLoc,
15217                                           Name)) {
15218           bool SafeToContinue
15219             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15220                Kind != TTK_Enum);
15221           if (SafeToContinue)
15222             Diag(KWLoc, diag::err_use_with_wrong_tag)
15223               << Name
15224               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15225                                               PrevTagDecl->getKindName());
15226           else
15227             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15228           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15229 
15230           if (SafeToContinue)
15231             Kind = PrevTagDecl->getTagKind();
15232           else {
15233             // Recover by making this an anonymous redefinition.
15234             Name = nullptr;
15235             Previous.clear();
15236             Invalid = true;
15237           }
15238         }
15239 
15240         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15241           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15242 
15243           // If this is an elaborated-type-specifier for a scoped enumeration,
15244           // the 'class' keyword is not necessary and not permitted.
15245           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15246             if (ScopedEnum)
15247               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15248                 << PrevEnum->isScoped()
15249                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15250             return PrevTagDecl;
15251           }
15252 
15253           QualType EnumUnderlyingTy;
15254           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15255             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15256           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15257             EnumUnderlyingTy = QualType(T, 0);
15258 
15259           // All conflicts with previous declarations are recovered by
15260           // returning the previous declaration, unless this is a definition,
15261           // in which case we want the caller to bail out.
15262           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15263                                      ScopedEnum, EnumUnderlyingTy,
15264                                      IsFixed, PrevEnum))
15265             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15266         }
15267 
15268         // C++11 [class.mem]p1:
15269         //   A member shall not be declared twice in the member-specification,
15270         //   except that a nested class or member class template can be declared
15271         //   and then later defined.
15272         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15273             S->isDeclScope(PrevDecl)) {
15274           Diag(NameLoc, diag::ext_member_redeclared);
15275           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15276         }
15277 
15278         if (!Invalid) {
15279           // If this is a use, just return the declaration we found, unless
15280           // we have attributes.
15281           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15282             if (!Attrs.empty()) {
15283               // FIXME: Diagnose these attributes. For now, we create a new
15284               // declaration to hold them.
15285             } else if (TUK == TUK_Reference &&
15286                        (PrevTagDecl->getFriendObjectKind() ==
15287                             Decl::FOK_Undeclared ||
15288                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15289                        SS.isEmpty()) {
15290               // This declaration is a reference to an existing entity, but
15291               // has different visibility from that entity: it either makes
15292               // a friend visible or it makes a type visible in a new module.
15293               // In either case, create a new declaration. We only do this if
15294               // the declaration would have meant the same thing if no prior
15295               // declaration were found, that is, if it was found in the same
15296               // scope where we would have injected a declaration.
15297               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15298                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15299                 return PrevTagDecl;
15300               // This is in the injected scope, create a new declaration in
15301               // that scope.
15302               S = getTagInjectionScope(S, getLangOpts());
15303             } else {
15304               return PrevTagDecl;
15305             }
15306           }
15307 
15308           // Diagnose attempts to redefine a tag.
15309           if (TUK == TUK_Definition) {
15310             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15311               // If we're defining a specialization and the previous definition
15312               // is from an implicit instantiation, don't emit an error
15313               // here; we'll catch this in the general case below.
15314               bool IsExplicitSpecializationAfterInstantiation = false;
15315               if (isMemberSpecialization) {
15316                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15317                   IsExplicitSpecializationAfterInstantiation =
15318                     RD->getTemplateSpecializationKind() !=
15319                     TSK_ExplicitSpecialization;
15320                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15321                   IsExplicitSpecializationAfterInstantiation =
15322                     ED->getTemplateSpecializationKind() !=
15323                     TSK_ExplicitSpecialization;
15324               }
15325 
15326               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15327               // not keep more that one definition around (merge them). However,
15328               // ensure the decl passes the structural compatibility check in
15329               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15330               NamedDecl *Hidden = nullptr;
15331               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15332                 // There is a definition of this tag, but it is not visible. We
15333                 // explicitly make use of C++'s one definition rule here, and
15334                 // assume that this definition is identical to the hidden one
15335                 // we already have. Make the existing definition visible and
15336                 // use it in place of this one.
15337                 if (!getLangOpts().CPlusPlus) {
15338                   // Postpone making the old definition visible until after we
15339                   // complete parsing the new one and do the structural
15340                   // comparison.
15341                   SkipBody->CheckSameAsPrevious = true;
15342                   SkipBody->New = createTagFromNewDecl();
15343                   SkipBody->Previous = Def;
15344                   return Def;
15345                 } else {
15346                   SkipBody->ShouldSkip = true;
15347                   SkipBody->Previous = Def;
15348                   makeMergedDefinitionVisible(Hidden);
15349                   // Carry on and handle it like a normal definition. We'll
15350                   // skip starting the definitiion later.
15351                 }
15352               } else if (!IsExplicitSpecializationAfterInstantiation) {
15353                 // A redeclaration in function prototype scope in C isn't
15354                 // visible elsewhere, so merely issue a warning.
15355                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15356                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15357                 else
15358                   Diag(NameLoc, diag::err_redefinition) << Name;
15359                 notePreviousDefinition(Def,
15360                                        NameLoc.isValid() ? NameLoc : KWLoc);
15361                 // If this is a redefinition, recover by making this
15362                 // struct be anonymous, which will make any later
15363                 // references get the previous definition.
15364                 Name = nullptr;
15365                 Previous.clear();
15366                 Invalid = true;
15367               }
15368             } else {
15369               // If the type is currently being defined, complain
15370               // about a nested redefinition.
15371               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15372               if (TD->isBeingDefined()) {
15373                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15374                 Diag(PrevTagDecl->getLocation(),
15375                      diag::note_previous_definition);
15376                 Name = nullptr;
15377                 Previous.clear();
15378                 Invalid = true;
15379               }
15380             }
15381 
15382             // Okay, this is definition of a previously declared or referenced
15383             // tag. We're going to create a new Decl for it.
15384           }
15385 
15386           // Okay, we're going to make a redeclaration.  If this is some kind
15387           // of reference, make sure we build the redeclaration in the same DC
15388           // as the original, and ignore the current access specifier.
15389           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15390             SearchDC = PrevTagDecl->getDeclContext();
15391             AS = AS_none;
15392           }
15393         }
15394         // If we get here we have (another) forward declaration or we
15395         // have a definition.  Just create a new decl.
15396 
15397       } else {
15398         // If we get here, this is a definition of a new tag type in a nested
15399         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15400         // new decl/type.  We set PrevDecl to NULL so that the entities
15401         // have distinct types.
15402         Previous.clear();
15403       }
15404       // If we get here, we're going to create a new Decl. If PrevDecl
15405       // is non-NULL, it's a definition of the tag declared by
15406       // PrevDecl. If it's NULL, we have a new definition.
15407 
15408     // Otherwise, PrevDecl is not a tag, but was found with tag
15409     // lookup.  This is only actually possible in C++, where a few
15410     // things like templates still live in the tag namespace.
15411     } else {
15412       // Use a better diagnostic if an elaborated-type-specifier
15413       // found the wrong kind of type on the first
15414       // (non-redeclaration) lookup.
15415       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15416           !Previous.isForRedeclaration()) {
15417         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15418         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15419                                                        << Kind;
15420         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15421         Invalid = true;
15422 
15423       // Otherwise, only diagnose if the declaration is in scope.
15424       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15425                                 SS.isNotEmpty() || isMemberSpecialization)) {
15426         // do nothing
15427 
15428       // Diagnose implicit declarations introduced by elaborated types.
15429       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15430         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15431         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15432         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15433         Invalid = true;
15434 
15435       // Otherwise it's a declaration.  Call out a particularly common
15436       // case here.
15437       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15438         unsigned Kind = 0;
15439         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15440         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15441           << Name << Kind << TND->getUnderlyingType();
15442         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15443         Invalid = true;
15444 
15445       // Otherwise, diagnose.
15446       } else {
15447         // The tag name clashes with something else in the target scope,
15448         // issue an error and recover by making this tag be anonymous.
15449         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15450         notePreviousDefinition(PrevDecl, NameLoc);
15451         Name = nullptr;
15452         Invalid = true;
15453       }
15454 
15455       // The existing declaration isn't relevant to us; we're in a
15456       // new scope, so clear out the previous declaration.
15457       Previous.clear();
15458     }
15459   }
15460 
15461 CreateNewDecl:
15462 
15463   TagDecl *PrevDecl = nullptr;
15464   if (Previous.isSingleResult())
15465     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15466 
15467   // If there is an identifier, use the location of the identifier as the
15468   // location of the decl, otherwise use the location of the struct/union
15469   // keyword.
15470   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15471 
15472   // Otherwise, create a new declaration. If there is a previous
15473   // declaration of the same entity, the two will be linked via
15474   // PrevDecl.
15475   TagDecl *New;
15476 
15477   if (Kind == TTK_Enum) {
15478     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15479     // enum X { A, B, C } D;    D should chain to X.
15480     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15481                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15482                            ScopedEnumUsesClassTag, IsFixed);
15483 
15484     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15485       StdAlignValT = cast<EnumDecl>(New);
15486 
15487     // If this is an undefined enum, warn.
15488     if (TUK != TUK_Definition && !Invalid) {
15489       TagDecl *Def;
15490       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15491         // C++0x: 7.2p2: opaque-enum-declaration.
15492         // Conflicts are diagnosed above. Do nothing.
15493       }
15494       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15495         Diag(Loc, diag::ext_forward_ref_enum_def)
15496           << New;
15497         Diag(Def->getLocation(), diag::note_previous_definition);
15498       } else {
15499         unsigned DiagID = diag::ext_forward_ref_enum;
15500         if (getLangOpts().MSVCCompat)
15501           DiagID = diag::ext_ms_forward_ref_enum;
15502         else if (getLangOpts().CPlusPlus)
15503           DiagID = diag::err_forward_ref_enum;
15504         Diag(Loc, DiagID);
15505       }
15506     }
15507 
15508     if (EnumUnderlying) {
15509       EnumDecl *ED = cast<EnumDecl>(New);
15510       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15511         ED->setIntegerTypeSourceInfo(TI);
15512       else
15513         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15514       ED->setPromotionType(ED->getIntegerType());
15515       assert(ED->isComplete() && "enum with type should be complete");
15516     }
15517   } else {
15518     // struct/union/class
15519 
15520     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15521     // struct X { int A; } D;    D should chain to X.
15522     if (getLangOpts().CPlusPlus) {
15523       // FIXME: Look for a way to use RecordDecl for simple structs.
15524       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15525                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15526 
15527       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15528         StdBadAlloc = cast<CXXRecordDecl>(New);
15529     } else
15530       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15531                                cast_or_null<RecordDecl>(PrevDecl));
15532   }
15533 
15534   // C++11 [dcl.type]p3:
15535   //   A type-specifier-seq shall not define a class or enumeration [...].
15536   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15537       TUK == TUK_Definition) {
15538     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15539       << Context.getTagDeclType(New);
15540     Invalid = true;
15541   }
15542 
15543   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15544       DC->getDeclKind() == Decl::Enum) {
15545     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15546       << Context.getTagDeclType(New);
15547     Invalid = true;
15548   }
15549 
15550   // Maybe add qualifier info.
15551   if (SS.isNotEmpty()) {
15552     if (SS.isSet()) {
15553       // If this is either a declaration or a definition, check the
15554       // nested-name-specifier against the current context.
15555       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15556           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15557                                        isMemberSpecialization))
15558         Invalid = true;
15559 
15560       New->setQualifierInfo(SS.getWithLocInContext(Context));
15561       if (TemplateParameterLists.size() > 0) {
15562         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15563       }
15564     }
15565     else
15566       Invalid = true;
15567   }
15568 
15569   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15570     // Add alignment attributes if necessary; these attributes are checked when
15571     // the ASTContext lays out the structure.
15572     //
15573     // It is important for implementing the correct semantics that this
15574     // happen here (in ActOnTag). The #pragma pack stack is
15575     // maintained as a result of parser callbacks which can occur at
15576     // many points during the parsing of a struct declaration (because
15577     // the #pragma tokens are effectively skipped over during the
15578     // parsing of the struct).
15579     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15580       AddAlignmentAttributesForRecord(RD);
15581       AddMsStructLayoutForRecord(RD);
15582     }
15583   }
15584 
15585   if (ModulePrivateLoc.isValid()) {
15586     if (isMemberSpecialization)
15587       Diag(New->getLocation(), diag::err_module_private_specialization)
15588         << 2
15589         << FixItHint::CreateRemoval(ModulePrivateLoc);
15590     // __module_private__ does not apply to local classes. However, we only
15591     // diagnose this as an error when the declaration specifiers are
15592     // freestanding. Here, we just ignore the __module_private__.
15593     else if (!SearchDC->isFunctionOrMethod())
15594       New->setModulePrivate();
15595   }
15596 
15597   // If this is a specialization of a member class (of a class template),
15598   // check the specialization.
15599   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15600     Invalid = true;
15601 
15602   // If we're declaring or defining a tag in function prototype scope in C,
15603   // note that this type can only be used within the function and add it to
15604   // the list of decls to inject into the function definition scope.
15605   if ((Name || Kind == TTK_Enum) &&
15606       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15607     if (getLangOpts().CPlusPlus) {
15608       // C++ [dcl.fct]p6:
15609       //   Types shall not be defined in return or parameter types.
15610       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15611         Diag(Loc, diag::err_type_defined_in_param_type)
15612             << Name;
15613         Invalid = true;
15614       }
15615     } else if (!PrevDecl) {
15616       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15617     }
15618   }
15619 
15620   if (Invalid)
15621     New->setInvalidDecl();
15622 
15623   // Set the lexical context. If the tag has a C++ scope specifier, the
15624   // lexical context will be different from the semantic context.
15625   New->setLexicalDeclContext(CurContext);
15626 
15627   // Mark this as a friend decl if applicable.
15628   // In Microsoft mode, a friend declaration also acts as a forward
15629   // declaration so we always pass true to setObjectOfFriendDecl to make
15630   // the tag name visible.
15631   if (TUK == TUK_Friend)
15632     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15633 
15634   // Set the access specifier.
15635   if (!Invalid && SearchDC->isRecord())
15636     SetMemberAccessSpecifier(New, PrevDecl, AS);
15637 
15638   if (PrevDecl)
15639     CheckRedeclarationModuleOwnership(New, PrevDecl);
15640 
15641   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15642     New->startDefinition();
15643 
15644   ProcessDeclAttributeList(S, New, Attrs);
15645   AddPragmaAttributes(S, New);
15646 
15647   // If this has an identifier, add it to the scope stack.
15648   if (TUK == TUK_Friend) {
15649     // We might be replacing an existing declaration in the lookup tables;
15650     // if so, borrow its access specifier.
15651     if (PrevDecl)
15652       New->setAccess(PrevDecl->getAccess());
15653 
15654     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15655     DC->makeDeclVisibleInContext(New);
15656     if (Name) // can be null along some error paths
15657       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15658         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15659   } else if (Name) {
15660     S = getNonFieldDeclScope(S);
15661     PushOnScopeChains(New, S, true);
15662   } else {
15663     CurContext->addDecl(New);
15664   }
15665 
15666   // If this is the C FILE type, notify the AST context.
15667   if (IdentifierInfo *II = New->getIdentifier())
15668     if (!New->isInvalidDecl() &&
15669         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15670         II->isStr("FILE"))
15671       Context.setFILEDecl(New);
15672 
15673   if (PrevDecl)
15674     mergeDeclAttributes(New, PrevDecl);
15675 
15676   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15677     inferGslOwnerPointerAttribute(CXXRD);
15678 
15679   // If there's a #pragma GCC visibility in scope, set the visibility of this
15680   // record.
15681   AddPushedVisibilityAttribute(New);
15682 
15683   if (isMemberSpecialization && !New->isInvalidDecl())
15684     CompleteMemberSpecialization(New, Previous);
15685 
15686   OwnedDecl = true;
15687   // In C++, don't return an invalid declaration. We can't recover well from
15688   // the cases where we make the type anonymous.
15689   if (Invalid && getLangOpts().CPlusPlus) {
15690     if (New->isBeingDefined())
15691       if (auto RD = dyn_cast<RecordDecl>(New))
15692         RD->completeDefinition();
15693     return nullptr;
15694   } else if (SkipBody && SkipBody->ShouldSkip) {
15695     return SkipBody->Previous;
15696   } else {
15697     return New;
15698   }
15699 }
15700 
15701 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15702   AdjustDeclIfTemplate(TagD);
15703   TagDecl *Tag = cast<TagDecl>(TagD);
15704 
15705   // Enter the tag context.
15706   PushDeclContext(S, Tag);
15707 
15708   ActOnDocumentableDecl(TagD);
15709 
15710   // If there's a #pragma GCC visibility in scope, set the visibility of this
15711   // record.
15712   AddPushedVisibilityAttribute(Tag);
15713 }
15714 
15715 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15716                                     SkipBodyInfo &SkipBody) {
15717   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15718     return false;
15719 
15720   // Make the previous decl visible.
15721   makeMergedDefinitionVisible(SkipBody.Previous);
15722   return true;
15723 }
15724 
15725 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15726   assert(isa<ObjCContainerDecl>(IDecl) &&
15727          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15728   DeclContext *OCD = cast<DeclContext>(IDecl);
15729   assert(getContainingDC(OCD) == CurContext &&
15730       "The next DeclContext should be lexically contained in the current one.");
15731   CurContext = OCD;
15732   return IDecl;
15733 }
15734 
15735 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15736                                            SourceLocation FinalLoc,
15737                                            bool IsFinalSpelledSealed,
15738                                            SourceLocation LBraceLoc) {
15739   AdjustDeclIfTemplate(TagD);
15740   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15741 
15742   FieldCollector->StartClass();
15743 
15744   if (!Record->getIdentifier())
15745     return;
15746 
15747   if (FinalLoc.isValid())
15748     Record->addAttr(FinalAttr::Create(
15749         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15750         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15751 
15752   // C++ [class]p2:
15753   //   [...] The class-name is also inserted into the scope of the
15754   //   class itself; this is known as the injected-class-name. For
15755   //   purposes of access checking, the injected-class-name is treated
15756   //   as if it were a public member name.
15757   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15758       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15759       Record->getLocation(), Record->getIdentifier(),
15760       /*PrevDecl=*/nullptr,
15761       /*DelayTypeCreation=*/true);
15762   Context.getTypeDeclType(InjectedClassName, Record);
15763   InjectedClassName->setImplicit();
15764   InjectedClassName->setAccess(AS_public);
15765   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15766       InjectedClassName->setDescribedClassTemplate(Template);
15767   PushOnScopeChains(InjectedClassName, S);
15768   assert(InjectedClassName->isInjectedClassName() &&
15769          "Broken injected-class-name");
15770 }
15771 
15772 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15773                                     SourceRange BraceRange) {
15774   AdjustDeclIfTemplate(TagD);
15775   TagDecl *Tag = cast<TagDecl>(TagD);
15776   Tag->setBraceRange(BraceRange);
15777 
15778   // Make sure we "complete" the definition even it is invalid.
15779   if (Tag->isBeingDefined()) {
15780     assert(Tag->isInvalidDecl() && "We should already have completed it");
15781     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15782       RD->completeDefinition();
15783   }
15784 
15785   if (isa<CXXRecordDecl>(Tag)) {
15786     FieldCollector->FinishClass();
15787   }
15788 
15789   // Exit this scope of this tag's definition.
15790   PopDeclContext();
15791 
15792   if (getCurLexicalContext()->isObjCContainer() &&
15793       Tag->getDeclContext()->isFileContext())
15794     Tag->setTopLevelDeclInObjCContainer();
15795 
15796   // Notify the consumer that we've defined a tag.
15797   if (!Tag->isInvalidDecl())
15798     Consumer.HandleTagDeclDefinition(Tag);
15799 }
15800 
15801 void Sema::ActOnObjCContainerFinishDefinition() {
15802   // Exit this scope of this interface definition.
15803   PopDeclContext();
15804 }
15805 
15806 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15807   assert(DC == CurContext && "Mismatch of container contexts");
15808   OriginalLexicalContext = DC;
15809   ActOnObjCContainerFinishDefinition();
15810 }
15811 
15812 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15813   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15814   OriginalLexicalContext = nullptr;
15815 }
15816 
15817 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15818   AdjustDeclIfTemplate(TagD);
15819   TagDecl *Tag = cast<TagDecl>(TagD);
15820   Tag->setInvalidDecl();
15821 
15822   // Make sure we "complete" the definition even it is invalid.
15823   if (Tag->isBeingDefined()) {
15824     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15825       RD->completeDefinition();
15826   }
15827 
15828   // We're undoing ActOnTagStartDefinition here, not
15829   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15830   // the FieldCollector.
15831 
15832   PopDeclContext();
15833 }
15834 
15835 // Note that FieldName may be null for anonymous bitfields.
15836 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15837                                 IdentifierInfo *FieldName,
15838                                 QualType FieldTy, bool IsMsStruct,
15839                                 Expr *BitWidth, bool *ZeroWidth) {
15840   // Default to true; that shouldn't confuse checks for emptiness
15841   if (ZeroWidth)
15842     *ZeroWidth = true;
15843 
15844   // C99 6.7.2.1p4 - verify the field type.
15845   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15846   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15847     // Handle incomplete types with specific error.
15848     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15849       return ExprError();
15850     if (FieldName)
15851       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15852         << FieldName << FieldTy << BitWidth->getSourceRange();
15853     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15854       << FieldTy << BitWidth->getSourceRange();
15855   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15856                                              UPPC_BitFieldWidth))
15857     return ExprError();
15858 
15859   // If the bit-width is type- or value-dependent, don't try to check
15860   // it now.
15861   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15862     return BitWidth;
15863 
15864   llvm::APSInt Value;
15865   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15866   if (ICE.isInvalid())
15867     return ICE;
15868   BitWidth = ICE.get();
15869 
15870   if (Value != 0 && ZeroWidth)
15871     *ZeroWidth = false;
15872 
15873   // Zero-width bitfield is ok for anonymous field.
15874   if (Value == 0 && FieldName)
15875     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15876 
15877   if (Value.isSigned() && Value.isNegative()) {
15878     if (FieldName)
15879       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15880                << FieldName << Value.toString(10);
15881     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15882       << Value.toString(10);
15883   }
15884 
15885   if (!FieldTy->isDependentType()) {
15886     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15887     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15888     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15889 
15890     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15891     // ABI.
15892     bool CStdConstraintViolation =
15893         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15894     bool MSBitfieldViolation =
15895         Value.ugt(TypeStorageSize) &&
15896         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15897     if (CStdConstraintViolation || MSBitfieldViolation) {
15898       unsigned DiagWidth =
15899           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15900       if (FieldName)
15901         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15902                << FieldName << (unsigned)Value.getZExtValue()
15903                << !CStdConstraintViolation << DiagWidth;
15904 
15905       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15906              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15907              << DiagWidth;
15908     }
15909 
15910     // Warn on types where the user might conceivably expect to get all
15911     // specified bits as value bits: that's all integral types other than
15912     // 'bool'.
15913     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15914       if (FieldName)
15915         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15916             << FieldName << (unsigned)Value.getZExtValue()
15917             << (unsigned)TypeWidth;
15918       else
15919         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15920             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15921     }
15922   }
15923 
15924   return BitWidth;
15925 }
15926 
15927 /// ActOnField - Each field of a C struct/union is passed into this in order
15928 /// to create a FieldDecl object for it.
15929 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15930                        Declarator &D, Expr *BitfieldWidth) {
15931   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15932                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15933                                /*InitStyle=*/ICIS_NoInit, AS_public);
15934   return Res;
15935 }
15936 
15937 /// HandleField - Analyze a field of a C struct or a C++ data member.
15938 ///
15939 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15940                              SourceLocation DeclStart,
15941                              Declarator &D, Expr *BitWidth,
15942                              InClassInitStyle InitStyle,
15943                              AccessSpecifier AS) {
15944   if (D.isDecompositionDeclarator()) {
15945     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15946     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15947       << Decomp.getSourceRange();
15948     return nullptr;
15949   }
15950 
15951   IdentifierInfo *II = D.getIdentifier();
15952   SourceLocation Loc = DeclStart;
15953   if (II) Loc = D.getIdentifierLoc();
15954 
15955   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15956   QualType T = TInfo->getType();
15957   if (getLangOpts().CPlusPlus) {
15958     CheckExtraCXXDefaultArguments(D);
15959 
15960     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15961                                         UPPC_DataMemberType)) {
15962       D.setInvalidType();
15963       T = Context.IntTy;
15964       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15965     }
15966   }
15967 
15968   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15969 
15970   if (D.getDeclSpec().isInlineSpecified())
15971     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15972         << getLangOpts().CPlusPlus17;
15973   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15974     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15975          diag::err_invalid_thread)
15976       << DeclSpec::getSpecifierName(TSCS);
15977 
15978   // Check to see if this name was declared as a member previously
15979   NamedDecl *PrevDecl = nullptr;
15980   LookupResult Previous(*this, II, Loc, LookupMemberName,
15981                         ForVisibleRedeclaration);
15982   LookupName(Previous, S);
15983   switch (Previous.getResultKind()) {
15984     case LookupResult::Found:
15985     case LookupResult::FoundUnresolvedValue:
15986       PrevDecl = Previous.getAsSingle<NamedDecl>();
15987       break;
15988 
15989     case LookupResult::FoundOverloaded:
15990       PrevDecl = Previous.getRepresentativeDecl();
15991       break;
15992 
15993     case LookupResult::NotFound:
15994     case LookupResult::NotFoundInCurrentInstantiation:
15995     case LookupResult::Ambiguous:
15996       break;
15997   }
15998   Previous.suppressDiagnostics();
15999 
16000   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16001     // Maybe we will complain about the shadowed template parameter.
16002     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16003     // Just pretend that we didn't see the previous declaration.
16004     PrevDecl = nullptr;
16005   }
16006 
16007   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16008     PrevDecl = nullptr;
16009 
16010   bool Mutable
16011     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16012   SourceLocation TSSL = D.getBeginLoc();
16013   FieldDecl *NewFD
16014     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16015                      TSSL, AS, PrevDecl, &D);
16016 
16017   if (NewFD->isInvalidDecl())
16018     Record->setInvalidDecl();
16019 
16020   if (D.getDeclSpec().isModulePrivateSpecified())
16021     NewFD->setModulePrivate();
16022 
16023   if (NewFD->isInvalidDecl() && PrevDecl) {
16024     // Don't introduce NewFD into scope; there's already something
16025     // with the same name in the same scope.
16026   } else if (II) {
16027     PushOnScopeChains(NewFD, S);
16028   } else
16029     Record->addDecl(NewFD);
16030 
16031   return NewFD;
16032 }
16033 
16034 /// Build a new FieldDecl and check its well-formedness.
16035 ///
16036 /// This routine builds a new FieldDecl given the fields name, type,
16037 /// record, etc. \p PrevDecl should refer to any previous declaration
16038 /// with the same name and in the same scope as the field to be
16039 /// created.
16040 ///
16041 /// \returns a new FieldDecl.
16042 ///
16043 /// \todo The Declarator argument is a hack. It will be removed once
16044 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16045                                 TypeSourceInfo *TInfo,
16046                                 RecordDecl *Record, SourceLocation Loc,
16047                                 bool Mutable, Expr *BitWidth,
16048                                 InClassInitStyle InitStyle,
16049                                 SourceLocation TSSL,
16050                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16051                                 Declarator *D) {
16052   IdentifierInfo *II = Name.getAsIdentifierInfo();
16053   bool InvalidDecl = false;
16054   if (D) InvalidDecl = D->isInvalidType();
16055 
16056   // If we receive a broken type, recover by assuming 'int' and
16057   // marking this declaration as invalid.
16058   if (T.isNull()) {
16059     InvalidDecl = true;
16060     T = Context.IntTy;
16061   }
16062 
16063   QualType EltTy = Context.getBaseElementType(T);
16064   if (!EltTy->isDependentType()) {
16065     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16066       // Fields of incomplete type force their record to be invalid.
16067       Record->setInvalidDecl();
16068       InvalidDecl = true;
16069     } else {
16070       NamedDecl *Def;
16071       EltTy->isIncompleteType(&Def);
16072       if (Def && Def->isInvalidDecl()) {
16073         Record->setInvalidDecl();
16074         InvalidDecl = true;
16075       }
16076     }
16077   }
16078 
16079   // TR 18037 does not allow fields to be declared with address space
16080   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
16081       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16082     Diag(Loc, diag::err_field_with_address_space);
16083     Record->setInvalidDecl();
16084     InvalidDecl = true;
16085   }
16086 
16087   if (LangOpts.OpenCL) {
16088     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16089     // used as structure or union field: image, sampler, event or block types.
16090     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16091         T->isBlockPointerType()) {
16092       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16093       Record->setInvalidDecl();
16094       InvalidDecl = true;
16095     }
16096     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16097     if (BitWidth) {
16098       Diag(Loc, diag::err_opencl_bitfields);
16099       InvalidDecl = true;
16100     }
16101   }
16102 
16103   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16104   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16105       T.hasQualifiers()) {
16106     InvalidDecl = true;
16107     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16108   }
16109 
16110   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16111   // than a variably modified type.
16112   if (!InvalidDecl && T->isVariablyModifiedType()) {
16113     bool SizeIsNegative;
16114     llvm::APSInt Oversized;
16115 
16116     TypeSourceInfo *FixedTInfo =
16117       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16118                                                     SizeIsNegative,
16119                                                     Oversized);
16120     if (FixedTInfo) {
16121       Diag(Loc, diag::warn_illegal_constant_array_size);
16122       TInfo = FixedTInfo;
16123       T = FixedTInfo->getType();
16124     } else {
16125       if (SizeIsNegative)
16126         Diag(Loc, diag::err_typecheck_negative_array_size);
16127       else if (Oversized.getBoolValue())
16128         Diag(Loc, diag::err_array_too_large)
16129           << Oversized.toString(10);
16130       else
16131         Diag(Loc, diag::err_typecheck_field_variable_size);
16132       InvalidDecl = true;
16133     }
16134   }
16135 
16136   // Fields can not have abstract class types
16137   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16138                                              diag::err_abstract_type_in_decl,
16139                                              AbstractFieldType))
16140     InvalidDecl = true;
16141 
16142   bool ZeroWidth = false;
16143   if (InvalidDecl)
16144     BitWidth = nullptr;
16145   // If this is declared as a bit-field, check the bit-field.
16146   if (BitWidth) {
16147     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16148                               &ZeroWidth).get();
16149     if (!BitWidth) {
16150       InvalidDecl = true;
16151       BitWidth = nullptr;
16152       ZeroWidth = false;
16153     }
16154   }
16155 
16156   // Check that 'mutable' is consistent with the type of the declaration.
16157   if (!InvalidDecl && Mutable) {
16158     unsigned DiagID = 0;
16159     if (T->isReferenceType())
16160       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16161                                         : diag::err_mutable_reference;
16162     else if (T.isConstQualified())
16163       DiagID = diag::err_mutable_const;
16164 
16165     if (DiagID) {
16166       SourceLocation ErrLoc = Loc;
16167       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16168         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16169       Diag(ErrLoc, DiagID);
16170       if (DiagID != diag::ext_mutable_reference) {
16171         Mutable = false;
16172         InvalidDecl = true;
16173       }
16174     }
16175   }
16176 
16177   // C++11 [class.union]p8 (DR1460):
16178   //   At most one variant member of a union may have a
16179   //   brace-or-equal-initializer.
16180   if (InitStyle != ICIS_NoInit)
16181     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16182 
16183   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16184                                        BitWidth, Mutable, InitStyle);
16185   if (InvalidDecl)
16186     NewFD->setInvalidDecl();
16187 
16188   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16189     Diag(Loc, diag::err_duplicate_member) << II;
16190     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16191     NewFD->setInvalidDecl();
16192   }
16193 
16194   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16195     if (Record->isUnion()) {
16196       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16197         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16198         if (RDecl->getDefinition()) {
16199           // C++ [class.union]p1: An object of a class with a non-trivial
16200           // constructor, a non-trivial copy constructor, a non-trivial
16201           // destructor, or a non-trivial copy assignment operator
16202           // cannot be a member of a union, nor can an array of such
16203           // objects.
16204           if (CheckNontrivialField(NewFD))
16205             NewFD->setInvalidDecl();
16206         }
16207       }
16208 
16209       // C++ [class.union]p1: If a union contains a member of reference type,
16210       // the program is ill-formed, except when compiling with MSVC extensions
16211       // enabled.
16212       if (EltTy->isReferenceType()) {
16213         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16214                                     diag::ext_union_member_of_reference_type :
16215                                     diag::err_union_member_of_reference_type)
16216           << NewFD->getDeclName() << EltTy;
16217         if (!getLangOpts().MicrosoftExt)
16218           NewFD->setInvalidDecl();
16219       }
16220     }
16221   }
16222 
16223   // FIXME: We need to pass in the attributes given an AST
16224   // representation, not a parser representation.
16225   if (D) {
16226     // FIXME: The current scope is almost... but not entirely... correct here.
16227     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16228 
16229     if (NewFD->hasAttrs())
16230       CheckAlignasUnderalignment(NewFD);
16231   }
16232 
16233   // In auto-retain/release, infer strong retension for fields of
16234   // retainable type.
16235   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16236     NewFD->setInvalidDecl();
16237 
16238   if (T.isObjCGCWeak())
16239     Diag(Loc, diag::warn_attribute_weak_on_field);
16240 
16241   NewFD->setAccess(AS);
16242   return NewFD;
16243 }
16244 
16245 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16246   assert(FD);
16247   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16248 
16249   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16250     return false;
16251 
16252   QualType EltTy = Context.getBaseElementType(FD->getType());
16253   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16254     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16255     if (RDecl->getDefinition()) {
16256       // We check for copy constructors before constructors
16257       // because otherwise we'll never get complaints about
16258       // copy constructors.
16259 
16260       CXXSpecialMember member = CXXInvalid;
16261       // We're required to check for any non-trivial constructors. Since the
16262       // implicit default constructor is suppressed if there are any
16263       // user-declared constructors, we just need to check that there is a
16264       // trivial default constructor and a trivial copy constructor. (We don't
16265       // worry about move constructors here, since this is a C++98 check.)
16266       if (RDecl->hasNonTrivialCopyConstructor())
16267         member = CXXCopyConstructor;
16268       else if (!RDecl->hasTrivialDefaultConstructor())
16269         member = CXXDefaultConstructor;
16270       else if (RDecl->hasNonTrivialCopyAssignment())
16271         member = CXXCopyAssignment;
16272       else if (RDecl->hasNonTrivialDestructor())
16273         member = CXXDestructor;
16274 
16275       if (member != CXXInvalid) {
16276         if (!getLangOpts().CPlusPlus11 &&
16277             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16278           // Objective-C++ ARC: it is an error to have a non-trivial field of
16279           // a union. However, system headers in Objective-C programs
16280           // occasionally have Objective-C lifetime objects within unions,
16281           // and rather than cause the program to fail, we make those
16282           // members unavailable.
16283           SourceLocation Loc = FD->getLocation();
16284           if (getSourceManager().isInSystemHeader(Loc)) {
16285             if (!FD->hasAttr<UnavailableAttr>())
16286               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16287                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16288             return false;
16289           }
16290         }
16291 
16292         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16293                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16294                diag::err_illegal_union_or_anon_struct_member)
16295           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16296         DiagnoseNontrivial(RDecl, member);
16297         return !getLangOpts().CPlusPlus11;
16298       }
16299     }
16300   }
16301 
16302   return false;
16303 }
16304 
16305 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16306 ///  AST enum value.
16307 static ObjCIvarDecl::AccessControl
16308 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16309   switch (ivarVisibility) {
16310   default: llvm_unreachable("Unknown visitibility kind");
16311   case tok::objc_private: return ObjCIvarDecl::Private;
16312   case tok::objc_public: return ObjCIvarDecl::Public;
16313   case tok::objc_protected: return ObjCIvarDecl::Protected;
16314   case tok::objc_package: return ObjCIvarDecl::Package;
16315   }
16316 }
16317 
16318 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16319 /// in order to create an IvarDecl object for it.
16320 Decl *Sema::ActOnIvar(Scope *S,
16321                                 SourceLocation DeclStart,
16322                                 Declarator &D, Expr *BitfieldWidth,
16323                                 tok::ObjCKeywordKind Visibility) {
16324 
16325   IdentifierInfo *II = D.getIdentifier();
16326   Expr *BitWidth = (Expr*)BitfieldWidth;
16327   SourceLocation Loc = DeclStart;
16328   if (II) Loc = D.getIdentifierLoc();
16329 
16330   // FIXME: Unnamed fields can be handled in various different ways, for
16331   // example, unnamed unions inject all members into the struct namespace!
16332 
16333   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16334   QualType T = TInfo->getType();
16335 
16336   if (BitWidth) {
16337     // 6.7.2.1p3, 6.7.2.1p4
16338     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16339     if (!BitWidth)
16340       D.setInvalidType();
16341   } else {
16342     // Not a bitfield.
16343 
16344     // validate II.
16345 
16346   }
16347   if (T->isReferenceType()) {
16348     Diag(Loc, diag::err_ivar_reference_type);
16349     D.setInvalidType();
16350   }
16351   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16352   // than a variably modified type.
16353   else if (T->isVariablyModifiedType()) {
16354     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16355     D.setInvalidType();
16356   }
16357 
16358   // Get the visibility (access control) for this ivar.
16359   ObjCIvarDecl::AccessControl ac =
16360     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16361                                         : ObjCIvarDecl::None;
16362   // Must set ivar's DeclContext to its enclosing interface.
16363   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16364   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16365     return nullptr;
16366   ObjCContainerDecl *EnclosingContext;
16367   if (ObjCImplementationDecl *IMPDecl =
16368       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16369     if (LangOpts.ObjCRuntime.isFragile()) {
16370     // Case of ivar declared in an implementation. Context is that of its class.
16371       EnclosingContext = IMPDecl->getClassInterface();
16372       assert(EnclosingContext && "Implementation has no class interface!");
16373     }
16374     else
16375       EnclosingContext = EnclosingDecl;
16376   } else {
16377     if (ObjCCategoryDecl *CDecl =
16378         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16379       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16380         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16381         return nullptr;
16382       }
16383     }
16384     EnclosingContext = EnclosingDecl;
16385   }
16386 
16387   // Construct the decl.
16388   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16389                                              DeclStart, Loc, II, T,
16390                                              TInfo, ac, (Expr *)BitfieldWidth);
16391 
16392   if (II) {
16393     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16394                                            ForVisibleRedeclaration);
16395     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16396         && !isa<TagDecl>(PrevDecl)) {
16397       Diag(Loc, diag::err_duplicate_member) << II;
16398       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16399       NewID->setInvalidDecl();
16400     }
16401   }
16402 
16403   // Process attributes attached to the ivar.
16404   ProcessDeclAttributes(S, NewID, D);
16405 
16406   if (D.isInvalidType())
16407     NewID->setInvalidDecl();
16408 
16409   // In ARC, infer 'retaining' for ivars of retainable type.
16410   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16411     NewID->setInvalidDecl();
16412 
16413   if (D.getDeclSpec().isModulePrivateSpecified())
16414     NewID->setModulePrivate();
16415 
16416   if (II) {
16417     // FIXME: When interfaces are DeclContexts, we'll need to add
16418     // these to the interface.
16419     S->AddDecl(NewID);
16420     IdResolver.AddDecl(NewID);
16421   }
16422 
16423   if (LangOpts.ObjCRuntime.isNonFragile() &&
16424       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16425     Diag(Loc, diag::warn_ivars_in_interface);
16426 
16427   return NewID;
16428 }
16429 
16430 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16431 /// class and class extensions. For every class \@interface and class
16432 /// extension \@interface, if the last ivar is a bitfield of any type,
16433 /// then add an implicit `char :0` ivar to the end of that interface.
16434 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16435                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16436   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16437     return;
16438 
16439   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16440   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16441 
16442   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16443     return;
16444   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16445   if (!ID) {
16446     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16447       if (!CD->IsClassExtension())
16448         return;
16449     }
16450     // No need to add this to end of @implementation.
16451     else
16452       return;
16453   }
16454   // All conditions are met. Add a new bitfield to the tail end of ivars.
16455   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16456   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16457 
16458   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16459                               DeclLoc, DeclLoc, nullptr,
16460                               Context.CharTy,
16461                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16462                                                                DeclLoc),
16463                               ObjCIvarDecl::Private, BW,
16464                               true);
16465   AllIvarDecls.push_back(Ivar);
16466 }
16467 
16468 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16469                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16470                        SourceLocation RBrac,
16471                        const ParsedAttributesView &Attrs) {
16472   assert(EnclosingDecl && "missing record or interface decl");
16473 
16474   // If this is an Objective-C @implementation or category and we have
16475   // new fields here we should reset the layout of the interface since
16476   // it will now change.
16477   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16478     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16479     switch (DC->getKind()) {
16480     default: break;
16481     case Decl::ObjCCategory:
16482       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16483       break;
16484     case Decl::ObjCImplementation:
16485       Context.
16486         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16487       break;
16488     }
16489   }
16490 
16491   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16492   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16493 
16494   // Start counting up the number of named members; make sure to include
16495   // members of anonymous structs and unions in the total.
16496   unsigned NumNamedMembers = 0;
16497   if (Record) {
16498     for (const auto *I : Record->decls()) {
16499       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16500         if (IFD->getDeclName())
16501           ++NumNamedMembers;
16502     }
16503   }
16504 
16505   // Verify that all the fields are okay.
16506   SmallVector<FieldDecl*, 32> RecFields;
16507 
16508   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16509        i != end; ++i) {
16510     FieldDecl *FD = cast<FieldDecl>(*i);
16511 
16512     // Get the type for the field.
16513     const Type *FDTy = FD->getType().getTypePtr();
16514 
16515     if (!FD->isAnonymousStructOrUnion()) {
16516       // Remember all fields written by the user.
16517       RecFields.push_back(FD);
16518     }
16519 
16520     // If the field is already invalid for some reason, don't emit more
16521     // diagnostics about it.
16522     if (FD->isInvalidDecl()) {
16523       EnclosingDecl->setInvalidDecl();
16524       continue;
16525     }
16526 
16527     // C99 6.7.2.1p2:
16528     //   A structure or union shall not contain a member with
16529     //   incomplete or function type (hence, a structure shall not
16530     //   contain an instance of itself, but may contain a pointer to
16531     //   an instance of itself), except that the last member of a
16532     //   structure with more than one named member may have incomplete
16533     //   array type; such a structure (and any union containing,
16534     //   possibly recursively, a member that is such a structure)
16535     //   shall not be a member of a structure or an element of an
16536     //   array.
16537     bool IsLastField = (i + 1 == Fields.end());
16538     if (FDTy->isFunctionType()) {
16539       // Field declared as a function.
16540       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16541         << FD->getDeclName();
16542       FD->setInvalidDecl();
16543       EnclosingDecl->setInvalidDecl();
16544       continue;
16545     } else if (FDTy->isIncompleteArrayType() &&
16546                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16547       if (Record) {
16548         // Flexible array member.
16549         // Microsoft and g++ is more permissive regarding flexible array.
16550         // It will accept flexible array in union and also
16551         // as the sole element of a struct/class.
16552         unsigned DiagID = 0;
16553         if (!Record->isUnion() && !IsLastField) {
16554           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16555             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16556           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16557           FD->setInvalidDecl();
16558           EnclosingDecl->setInvalidDecl();
16559           continue;
16560         } else if (Record->isUnion())
16561           DiagID = getLangOpts().MicrosoftExt
16562                        ? diag::ext_flexible_array_union_ms
16563                        : getLangOpts().CPlusPlus
16564                              ? diag::ext_flexible_array_union_gnu
16565                              : diag::err_flexible_array_union;
16566         else if (NumNamedMembers < 1)
16567           DiagID = getLangOpts().MicrosoftExt
16568                        ? diag::ext_flexible_array_empty_aggregate_ms
16569                        : getLangOpts().CPlusPlus
16570                              ? diag::ext_flexible_array_empty_aggregate_gnu
16571                              : diag::err_flexible_array_empty_aggregate;
16572 
16573         if (DiagID)
16574           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16575                                           << Record->getTagKind();
16576         // While the layout of types that contain virtual bases is not specified
16577         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16578         // virtual bases after the derived members.  This would make a flexible
16579         // array member declared at the end of an object not adjacent to the end
16580         // of the type.
16581         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16582           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16583               << FD->getDeclName() << Record->getTagKind();
16584         if (!getLangOpts().C99)
16585           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16586             << FD->getDeclName() << Record->getTagKind();
16587 
16588         // If the element type has a non-trivial destructor, we would not
16589         // implicitly destroy the elements, so disallow it for now.
16590         //
16591         // FIXME: GCC allows this. We should probably either implicitly delete
16592         // the destructor of the containing class, or just allow this.
16593         QualType BaseElem = Context.getBaseElementType(FD->getType());
16594         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16595           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16596             << FD->getDeclName() << FD->getType();
16597           FD->setInvalidDecl();
16598           EnclosingDecl->setInvalidDecl();
16599           continue;
16600         }
16601         // Okay, we have a legal flexible array member at the end of the struct.
16602         Record->setHasFlexibleArrayMember(true);
16603       } else {
16604         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16605         // unless they are followed by another ivar. That check is done
16606         // elsewhere, after synthesized ivars are known.
16607       }
16608     } else if (!FDTy->isDependentType() &&
16609                RequireCompleteType(FD->getLocation(), FD->getType(),
16610                                    diag::err_field_incomplete)) {
16611       // Incomplete type
16612       FD->setInvalidDecl();
16613       EnclosingDecl->setInvalidDecl();
16614       continue;
16615     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16616       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16617         // A type which contains a flexible array member is considered to be a
16618         // flexible array member.
16619         Record->setHasFlexibleArrayMember(true);
16620         if (!Record->isUnion()) {
16621           // If this is a struct/class and this is not the last element, reject
16622           // it.  Note that GCC supports variable sized arrays in the middle of
16623           // structures.
16624           if (!IsLastField)
16625             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16626               << FD->getDeclName() << FD->getType();
16627           else {
16628             // We support flexible arrays at the end of structs in
16629             // other structs as an extension.
16630             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16631               << FD->getDeclName();
16632           }
16633         }
16634       }
16635       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16636           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16637                                  diag::err_abstract_type_in_decl,
16638                                  AbstractIvarType)) {
16639         // Ivars can not have abstract class types
16640         FD->setInvalidDecl();
16641       }
16642       if (Record && FDTTy->getDecl()->hasObjectMember())
16643         Record->setHasObjectMember(true);
16644       if (Record && FDTTy->getDecl()->hasVolatileMember())
16645         Record->setHasVolatileMember(true);
16646     } else if (FDTy->isObjCObjectType()) {
16647       /// A field cannot be an Objective-c object
16648       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16649         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16650       QualType T = Context.getObjCObjectPointerType(FD->getType());
16651       FD->setType(T);
16652     } else if (Record && Record->isUnion() &&
16653                FD->getType().hasNonTrivialObjCLifetime() &&
16654                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16655                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16656                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16657                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16658       // For backward compatibility, fields of C unions declared in system
16659       // headers that have non-trivial ObjC ownership qualifications are marked
16660       // as unavailable unless the qualifier is explicit and __strong. This can
16661       // break ABI compatibility between programs compiled with ARC and MRR, but
16662       // is a better option than rejecting programs using those unions under
16663       // ARC.
16664       FD->addAttr(UnavailableAttr::CreateImplicit(
16665           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16666           FD->getLocation()));
16667     } else if (getLangOpts().ObjC &&
16668                getLangOpts().getGC() != LangOptions::NonGC &&
16669                Record && !Record->hasObjectMember()) {
16670       if (FD->getType()->isObjCObjectPointerType() ||
16671           FD->getType().isObjCGCStrong())
16672         Record->setHasObjectMember(true);
16673       else if (Context.getAsArrayType(FD->getType())) {
16674         QualType BaseType = Context.getBaseElementType(FD->getType());
16675         if (BaseType->isRecordType() &&
16676             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16677           Record->setHasObjectMember(true);
16678         else if (BaseType->isObjCObjectPointerType() ||
16679                  BaseType.isObjCGCStrong())
16680                Record->setHasObjectMember(true);
16681       }
16682     }
16683 
16684     if (Record && !getLangOpts().CPlusPlus &&
16685         !shouldIgnoreForRecordTriviality(FD)) {
16686       QualType FT = FD->getType();
16687       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16688         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16689         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16690             Record->isUnion())
16691           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16692       }
16693       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16694       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16695         Record->setNonTrivialToPrimitiveCopy(true);
16696         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16697           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16698       }
16699       if (FT.isDestructedType()) {
16700         Record->setNonTrivialToPrimitiveDestroy(true);
16701         Record->setParamDestroyedInCallee(true);
16702         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16703           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16704       }
16705 
16706       if (const auto *RT = FT->getAs<RecordType>()) {
16707         if (RT->getDecl()->getArgPassingRestrictions() ==
16708             RecordDecl::APK_CanNeverPassInRegs)
16709           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16710       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16711         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16712     }
16713 
16714     if (Record && FD->getType().isVolatileQualified())
16715       Record->setHasVolatileMember(true);
16716     // Keep track of the number of named members.
16717     if (FD->getIdentifier())
16718       ++NumNamedMembers;
16719   }
16720 
16721   // Okay, we successfully defined 'Record'.
16722   if (Record) {
16723     bool Completed = false;
16724     if (CXXRecord) {
16725       if (!CXXRecord->isInvalidDecl()) {
16726         // Set access bits correctly on the directly-declared conversions.
16727         for (CXXRecordDecl::conversion_iterator
16728                I = CXXRecord->conversion_begin(),
16729                E = CXXRecord->conversion_end(); I != E; ++I)
16730           I.setAccess((*I)->getAccess());
16731       }
16732 
16733       if (!CXXRecord->isDependentType()) {
16734         // Add any implicitly-declared members to this class.
16735         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16736 
16737         if (!CXXRecord->isInvalidDecl()) {
16738           // If we have virtual base classes, we may end up finding multiple
16739           // final overriders for a given virtual function. Check for this
16740           // problem now.
16741           if (CXXRecord->getNumVBases()) {
16742             CXXFinalOverriderMap FinalOverriders;
16743             CXXRecord->getFinalOverriders(FinalOverriders);
16744 
16745             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16746                                              MEnd = FinalOverriders.end();
16747                  M != MEnd; ++M) {
16748               for (OverridingMethods::iterator SO = M->second.begin(),
16749                                             SOEnd = M->second.end();
16750                    SO != SOEnd; ++SO) {
16751                 assert(SO->second.size() > 0 &&
16752                        "Virtual function without overriding functions?");
16753                 if (SO->second.size() == 1)
16754                   continue;
16755 
16756                 // C++ [class.virtual]p2:
16757                 //   In a derived class, if a virtual member function of a base
16758                 //   class subobject has more than one final overrider the
16759                 //   program is ill-formed.
16760                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16761                   << (const NamedDecl *)M->first << Record;
16762                 Diag(M->first->getLocation(),
16763                      diag::note_overridden_virtual_function);
16764                 for (OverridingMethods::overriding_iterator
16765                           OM = SO->second.begin(),
16766                        OMEnd = SO->second.end();
16767                      OM != OMEnd; ++OM)
16768                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16769                     << (const NamedDecl *)M->first << OM->Method->getParent();
16770 
16771                 Record->setInvalidDecl();
16772               }
16773             }
16774             CXXRecord->completeDefinition(&FinalOverriders);
16775             Completed = true;
16776           }
16777         }
16778       }
16779     }
16780 
16781     if (!Completed)
16782       Record->completeDefinition();
16783 
16784     // Handle attributes before checking the layout.
16785     ProcessDeclAttributeList(S, Record, Attrs);
16786 
16787     // We may have deferred checking for a deleted destructor. Check now.
16788     if (CXXRecord) {
16789       auto *Dtor = CXXRecord->getDestructor();
16790       if (Dtor && Dtor->isImplicit() &&
16791           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16792         CXXRecord->setImplicitDestructorIsDeleted();
16793         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16794       }
16795     }
16796 
16797     if (Record->hasAttrs()) {
16798       CheckAlignasUnderalignment(Record);
16799 
16800       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16801         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16802                                            IA->getRange(), IA->getBestCase(),
16803                                            IA->getInheritanceModel());
16804     }
16805 
16806     // Check if the structure/union declaration is a type that can have zero
16807     // size in C. For C this is a language extension, for C++ it may cause
16808     // compatibility problems.
16809     bool CheckForZeroSize;
16810     if (!getLangOpts().CPlusPlus) {
16811       CheckForZeroSize = true;
16812     } else {
16813       // For C++ filter out types that cannot be referenced in C code.
16814       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16815       CheckForZeroSize =
16816           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16817           !CXXRecord->isDependentType() &&
16818           CXXRecord->isCLike();
16819     }
16820     if (CheckForZeroSize) {
16821       bool ZeroSize = true;
16822       bool IsEmpty = true;
16823       unsigned NonBitFields = 0;
16824       for (RecordDecl::field_iterator I = Record->field_begin(),
16825                                       E = Record->field_end();
16826            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16827         IsEmpty = false;
16828         if (I->isUnnamedBitfield()) {
16829           if (!I->isZeroLengthBitField(Context))
16830             ZeroSize = false;
16831         } else {
16832           ++NonBitFields;
16833           QualType FieldType = I->getType();
16834           if (FieldType->isIncompleteType() ||
16835               !Context.getTypeSizeInChars(FieldType).isZero())
16836             ZeroSize = false;
16837         }
16838       }
16839 
16840       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16841       // allowed in C++, but warn if its declaration is inside
16842       // extern "C" block.
16843       if (ZeroSize) {
16844         Diag(RecLoc, getLangOpts().CPlusPlus ?
16845                          diag::warn_zero_size_struct_union_in_extern_c :
16846                          diag::warn_zero_size_struct_union_compat)
16847           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16848       }
16849 
16850       // Structs without named members are extension in C (C99 6.7.2.1p7),
16851       // but are accepted by GCC.
16852       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16853         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16854                                diag::ext_no_named_members_in_struct_union)
16855           << Record->isUnion();
16856       }
16857     }
16858   } else {
16859     ObjCIvarDecl **ClsFields =
16860       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16861     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16862       ID->setEndOfDefinitionLoc(RBrac);
16863       // Add ivar's to class's DeclContext.
16864       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16865         ClsFields[i]->setLexicalDeclContext(ID);
16866         ID->addDecl(ClsFields[i]);
16867       }
16868       // Must enforce the rule that ivars in the base classes may not be
16869       // duplicates.
16870       if (ID->getSuperClass())
16871         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16872     } else if (ObjCImplementationDecl *IMPDecl =
16873                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16874       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16875       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16876         // Ivar declared in @implementation never belongs to the implementation.
16877         // Only it is in implementation's lexical context.
16878         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16879       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16880       IMPDecl->setIvarLBraceLoc(LBrac);
16881       IMPDecl->setIvarRBraceLoc(RBrac);
16882     } else if (ObjCCategoryDecl *CDecl =
16883                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16884       // case of ivars in class extension; all other cases have been
16885       // reported as errors elsewhere.
16886       // FIXME. Class extension does not have a LocEnd field.
16887       // CDecl->setLocEnd(RBrac);
16888       // Add ivar's to class extension's DeclContext.
16889       // Diagnose redeclaration of private ivars.
16890       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16891       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16892         if (IDecl) {
16893           if (const ObjCIvarDecl *ClsIvar =
16894               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16895             Diag(ClsFields[i]->getLocation(),
16896                  diag::err_duplicate_ivar_declaration);
16897             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16898             continue;
16899           }
16900           for (const auto *Ext : IDecl->known_extensions()) {
16901             if (const ObjCIvarDecl *ClsExtIvar
16902                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16903               Diag(ClsFields[i]->getLocation(),
16904                    diag::err_duplicate_ivar_declaration);
16905               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16906               continue;
16907             }
16908           }
16909         }
16910         ClsFields[i]->setLexicalDeclContext(CDecl);
16911         CDecl->addDecl(ClsFields[i]);
16912       }
16913       CDecl->setIvarLBraceLoc(LBrac);
16914       CDecl->setIvarRBraceLoc(RBrac);
16915     }
16916   }
16917 }
16918 
16919 /// Determine whether the given integral value is representable within
16920 /// the given type T.
16921 static bool isRepresentableIntegerValue(ASTContext &Context,
16922                                         llvm::APSInt &Value,
16923                                         QualType T) {
16924   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16925          "Integral type required!");
16926   unsigned BitWidth = Context.getIntWidth(T);
16927 
16928   if (Value.isUnsigned() || Value.isNonNegative()) {
16929     if (T->isSignedIntegerOrEnumerationType())
16930       --BitWidth;
16931     return Value.getActiveBits() <= BitWidth;
16932   }
16933   return Value.getMinSignedBits() <= BitWidth;
16934 }
16935 
16936 // Given an integral type, return the next larger integral type
16937 // (or a NULL type of no such type exists).
16938 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16939   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16940   // enum checking below.
16941   assert((T->isIntegralType(Context) ||
16942          T->isEnumeralType()) && "Integral type required!");
16943   const unsigned NumTypes = 4;
16944   QualType SignedIntegralTypes[NumTypes] = {
16945     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16946   };
16947   QualType UnsignedIntegralTypes[NumTypes] = {
16948     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16949     Context.UnsignedLongLongTy
16950   };
16951 
16952   unsigned BitWidth = Context.getTypeSize(T);
16953   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16954                                                         : UnsignedIntegralTypes;
16955   for (unsigned I = 0; I != NumTypes; ++I)
16956     if (Context.getTypeSize(Types[I]) > BitWidth)
16957       return Types[I];
16958 
16959   return QualType();
16960 }
16961 
16962 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16963                                           EnumConstantDecl *LastEnumConst,
16964                                           SourceLocation IdLoc,
16965                                           IdentifierInfo *Id,
16966                                           Expr *Val) {
16967   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16968   llvm::APSInt EnumVal(IntWidth);
16969   QualType EltTy;
16970 
16971   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16972     Val = nullptr;
16973 
16974   if (Val)
16975     Val = DefaultLvalueConversion(Val).get();
16976 
16977   if (Val) {
16978     if (Enum->isDependentType() || Val->isTypeDependent())
16979       EltTy = Context.DependentTy;
16980     else {
16981       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
16982         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16983         // constant-expression in the enumerator-definition shall be a converted
16984         // constant expression of the underlying type.
16985         EltTy = Enum->getIntegerType();
16986         ExprResult Converted =
16987           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16988                                            CCEK_Enumerator);
16989         if (Converted.isInvalid())
16990           Val = nullptr;
16991         else
16992           Val = Converted.get();
16993       } else if (!Val->isValueDependent() &&
16994                  !(Val = VerifyIntegerConstantExpression(Val,
16995                                                          &EnumVal).get())) {
16996         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16997       } else {
16998         if (Enum->isComplete()) {
16999           EltTy = Enum->getIntegerType();
17000 
17001           // In Obj-C and Microsoft mode, require the enumeration value to be
17002           // representable in the underlying type of the enumeration. In C++11,
17003           // we perform a non-narrowing conversion as part of converted constant
17004           // expression checking.
17005           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17006             if (Context.getTargetInfo()
17007                     .getTriple()
17008                     .isWindowsMSVCEnvironment()) {
17009               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17010             } else {
17011               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17012             }
17013           }
17014 
17015           // Cast to the underlying type.
17016           Val = ImpCastExprToType(Val, EltTy,
17017                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17018                                                          : CK_IntegralCast)
17019                     .get();
17020         } else if (getLangOpts().CPlusPlus) {
17021           // C++11 [dcl.enum]p5:
17022           //   If the underlying type is not fixed, the type of each enumerator
17023           //   is the type of its initializing value:
17024           //     - If an initializer is specified for an enumerator, the
17025           //       initializing value has the same type as the expression.
17026           EltTy = Val->getType();
17027         } else {
17028           // C99 6.7.2.2p2:
17029           //   The expression that defines the value of an enumeration constant
17030           //   shall be an integer constant expression that has a value
17031           //   representable as an int.
17032 
17033           // Complain if the value is not representable in an int.
17034           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17035             Diag(IdLoc, diag::ext_enum_value_not_int)
17036               << EnumVal.toString(10) << Val->getSourceRange()
17037               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17038           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17039             // Force the type of the expression to 'int'.
17040             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17041           }
17042           EltTy = Val->getType();
17043         }
17044       }
17045     }
17046   }
17047 
17048   if (!Val) {
17049     if (Enum->isDependentType())
17050       EltTy = Context.DependentTy;
17051     else if (!LastEnumConst) {
17052       // C++0x [dcl.enum]p5:
17053       //   If the underlying type is not fixed, the type of each enumerator
17054       //   is the type of its initializing value:
17055       //     - If no initializer is specified for the first enumerator, the
17056       //       initializing value has an unspecified integral type.
17057       //
17058       // GCC uses 'int' for its unspecified integral type, as does
17059       // C99 6.7.2.2p3.
17060       if (Enum->isFixed()) {
17061         EltTy = Enum->getIntegerType();
17062       }
17063       else {
17064         EltTy = Context.IntTy;
17065       }
17066     } else {
17067       // Assign the last value + 1.
17068       EnumVal = LastEnumConst->getInitVal();
17069       ++EnumVal;
17070       EltTy = LastEnumConst->getType();
17071 
17072       // Check for overflow on increment.
17073       if (EnumVal < LastEnumConst->getInitVal()) {
17074         // C++0x [dcl.enum]p5:
17075         //   If the underlying type is not fixed, the type of each enumerator
17076         //   is the type of its initializing value:
17077         //
17078         //     - Otherwise the type of the initializing value is the same as
17079         //       the type of the initializing value of the preceding enumerator
17080         //       unless the incremented value is not representable in that type,
17081         //       in which case the type is an unspecified integral type
17082         //       sufficient to contain the incremented value. If no such type
17083         //       exists, the program is ill-formed.
17084         QualType T = getNextLargerIntegralType(Context, EltTy);
17085         if (T.isNull() || Enum->isFixed()) {
17086           // There is no integral type larger enough to represent this
17087           // value. Complain, then allow the value to wrap around.
17088           EnumVal = LastEnumConst->getInitVal();
17089           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17090           ++EnumVal;
17091           if (Enum->isFixed())
17092             // When the underlying type is fixed, this is ill-formed.
17093             Diag(IdLoc, diag::err_enumerator_wrapped)
17094               << EnumVal.toString(10)
17095               << EltTy;
17096           else
17097             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17098               << EnumVal.toString(10);
17099         } else {
17100           EltTy = T;
17101         }
17102 
17103         // Retrieve the last enumerator's value, extent that type to the
17104         // type that is supposed to be large enough to represent the incremented
17105         // value, then increment.
17106         EnumVal = LastEnumConst->getInitVal();
17107         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17108         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17109         ++EnumVal;
17110 
17111         // If we're not in C++, diagnose the overflow of enumerator values,
17112         // which in C99 means that the enumerator value is not representable in
17113         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17114         // permits enumerator values that are representable in some larger
17115         // integral type.
17116         if (!getLangOpts().CPlusPlus && !T.isNull())
17117           Diag(IdLoc, diag::warn_enum_value_overflow);
17118       } else if (!getLangOpts().CPlusPlus &&
17119                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17120         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17121         Diag(IdLoc, diag::ext_enum_value_not_int)
17122           << EnumVal.toString(10) << 1;
17123       }
17124     }
17125   }
17126 
17127   if (!EltTy->isDependentType()) {
17128     // Make the enumerator value match the signedness and size of the
17129     // enumerator's type.
17130     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17131     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17132   }
17133 
17134   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17135                                   Val, EnumVal);
17136 }
17137 
17138 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17139                                                 SourceLocation IILoc) {
17140   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17141       !getLangOpts().CPlusPlus)
17142     return SkipBodyInfo();
17143 
17144   // We have an anonymous enum definition. Look up the first enumerator to
17145   // determine if we should merge the definition with an existing one and
17146   // skip the body.
17147   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17148                                          forRedeclarationInCurContext());
17149   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17150   if (!PrevECD)
17151     return SkipBodyInfo();
17152 
17153   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17154   NamedDecl *Hidden;
17155   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17156     SkipBodyInfo Skip;
17157     Skip.Previous = Hidden;
17158     return Skip;
17159   }
17160 
17161   return SkipBodyInfo();
17162 }
17163 
17164 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17165                               SourceLocation IdLoc, IdentifierInfo *Id,
17166                               const ParsedAttributesView &Attrs,
17167                               SourceLocation EqualLoc, Expr *Val) {
17168   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17169   EnumConstantDecl *LastEnumConst =
17170     cast_or_null<EnumConstantDecl>(lastEnumConst);
17171 
17172   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17173   // we find one that is.
17174   S = getNonFieldDeclScope(S);
17175 
17176   // Verify that there isn't already something declared with this name in this
17177   // scope.
17178   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17179   LookupName(R, S);
17180   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17181 
17182   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17183     // Maybe we will complain about the shadowed template parameter.
17184     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17185     // Just pretend that we didn't see the previous declaration.
17186     PrevDecl = nullptr;
17187   }
17188 
17189   // C++ [class.mem]p15:
17190   // If T is the name of a class, then each of the following shall have a name
17191   // different from T:
17192   // - every enumerator of every member of class T that is an unscoped
17193   // enumerated type
17194   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17195     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17196                             DeclarationNameInfo(Id, IdLoc));
17197 
17198   EnumConstantDecl *New =
17199     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17200   if (!New)
17201     return nullptr;
17202 
17203   if (PrevDecl) {
17204     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17205       // Check for other kinds of shadowing not already handled.
17206       CheckShadow(New, PrevDecl, R);
17207     }
17208 
17209     // When in C++, we may get a TagDecl with the same name; in this case the
17210     // enum constant will 'hide' the tag.
17211     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17212            "Received TagDecl when not in C++!");
17213     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17214       if (isa<EnumConstantDecl>(PrevDecl))
17215         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17216       else
17217         Diag(IdLoc, diag::err_redefinition) << Id;
17218       notePreviousDefinition(PrevDecl, IdLoc);
17219       return nullptr;
17220     }
17221   }
17222 
17223   // Process attributes.
17224   ProcessDeclAttributeList(S, New, Attrs);
17225   AddPragmaAttributes(S, New);
17226 
17227   // Register this decl in the current scope stack.
17228   New->setAccess(TheEnumDecl->getAccess());
17229   PushOnScopeChains(New, S);
17230 
17231   ActOnDocumentableDecl(New);
17232 
17233   return New;
17234 }
17235 
17236 // Returns true when the enum initial expression does not trigger the
17237 // duplicate enum warning.  A few common cases are exempted as follows:
17238 // Element2 = Element1
17239 // Element2 = Element1 + 1
17240 // Element2 = Element1 - 1
17241 // Where Element2 and Element1 are from the same enum.
17242 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17243   Expr *InitExpr = ECD->getInitExpr();
17244   if (!InitExpr)
17245     return true;
17246   InitExpr = InitExpr->IgnoreImpCasts();
17247 
17248   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17249     if (!BO->isAdditiveOp())
17250       return true;
17251     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17252     if (!IL)
17253       return true;
17254     if (IL->getValue() != 1)
17255       return true;
17256 
17257     InitExpr = BO->getLHS();
17258   }
17259 
17260   // This checks if the elements are from the same enum.
17261   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17262   if (!DRE)
17263     return true;
17264 
17265   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17266   if (!EnumConstant)
17267     return true;
17268 
17269   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17270       Enum)
17271     return true;
17272 
17273   return false;
17274 }
17275 
17276 // Emits a warning when an element is implicitly set a value that
17277 // a previous element has already been set to.
17278 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17279                                         EnumDecl *Enum, QualType EnumType) {
17280   // Avoid anonymous enums
17281   if (!Enum->getIdentifier())
17282     return;
17283 
17284   // Only check for small enums.
17285   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17286     return;
17287 
17288   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17289     return;
17290 
17291   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17292   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17293 
17294   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17295   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17296 
17297   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17298   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17299     llvm::APSInt Val = D->getInitVal();
17300     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17301   };
17302 
17303   DuplicatesVector DupVector;
17304   ValueToVectorMap EnumMap;
17305 
17306   // Populate the EnumMap with all values represented by enum constants without
17307   // an initializer.
17308   for (auto *Element : Elements) {
17309     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17310 
17311     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17312     // this constant.  Skip this enum since it may be ill-formed.
17313     if (!ECD) {
17314       return;
17315     }
17316 
17317     // Constants with initalizers are handled in the next loop.
17318     if (ECD->getInitExpr())
17319       continue;
17320 
17321     // Duplicate values are handled in the next loop.
17322     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17323   }
17324 
17325   if (EnumMap.size() == 0)
17326     return;
17327 
17328   // Create vectors for any values that has duplicates.
17329   for (auto *Element : Elements) {
17330     // The last loop returned if any constant was null.
17331     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17332     if (!ValidDuplicateEnum(ECD, Enum))
17333       continue;
17334 
17335     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17336     if (Iter == EnumMap.end())
17337       continue;
17338 
17339     DeclOrVector& Entry = Iter->second;
17340     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17341       // Ensure constants are different.
17342       if (D == ECD)
17343         continue;
17344 
17345       // Create new vector and push values onto it.
17346       auto Vec = std::make_unique<ECDVector>();
17347       Vec->push_back(D);
17348       Vec->push_back(ECD);
17349 
17350       // Update entry to point to the duplicates vector.
17351       Entry = Vec.get();
17352 
17353       // Store the vector somewhere we can consult later for quick emission of
17354       // diagnostics.
17355       DupVector.emplace_back(std::move(Vec));
17356       continue;
17357     }
17358 
17359     ECDVector *Vec = Entry.get<ECDVector*>();
17360     // Make sure constants are not added more than once.
17361     if (*Vec->begin() == ECD)
17362       continue;
17363 
17364     Vec->push_back(ECD);
17365   }
17366 
17367   // Emit diagnostics.
17368   for (const auto &Vec : DupVector) {
17369     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17370 
17371     // Emit warning for one enum constant.
17372     auto *FirstECD = Vec->front();
17373     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17374       << FirstECD << FirstECD->getInitVal().toString(10)
17375       << FirstECD->getSourceRange();
17376 
17377     // Emit one note for each of the remaining enum constants with
17378     // the same value.
17379     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17380       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17381         << ECD << ECD->getInitVal().toString(10)
17382         << ECD->getSourceRange();
17383   }
17384 }
17385 
17386 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17387                              bool AllowMask) const {
17388   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17389   assert(ED->isCompleteDefinition() && "expected enum definition");
17390 
17391   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17392   llvm::APInt &FlagBits = R.first->second;
17393 
17394   if (R.second) {
17395     for (auto *E : ED->enumerators()) {
17396       const auto &EVal = E->getInitVal();
17397       // Only single-bit enumerators introduce new flag values.
17398       if (EVal.isPowerOf2())
17399         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17400     }
17401   }
17402 
17403   // A value is in a flag enum if either its bits are a subset of the enum's
17404   // flag bits (the first condition) or we are allowing masks and the same is
17405   // true of its complement (the second condition). When masks are allowed, we
17406   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17407   //
17408   // While it's true that any value could be used as a mask, the assumption is
17409   // that a mask will have all of the insignificant bits set. Anything else is
17410   // likely a logic error.
17411   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17412   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17413 }
17414 
17415 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17416                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17417                          const ParsedAttributesView &Attrs) {
17418   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17419   QualType EnumType = Context.getTypeDeclType(Enum);
17420 
17421   ProcessDeclAttributeList(S, Enum, Attrs);
17422 
17423   if (Enum->isDependentType()) {
17424     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17425       EnumConstantDecl *ECD =
17426         cast_or_null<EnumConstantDecl>(Elements[i]);
17427       if (!ECD) continue;
17428 
17429       ECD->setType(EnumType);
17430     }
17431 
17432     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17433     return;
17434   }
17435 
17436   // TODO: If the result value doesn't fit in an int, it must be a long or long
17437   // long value.  ISO C does not support this, but GCC does as an extension,
17438   // emit a warning.
17439   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17440   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17441   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17442 
17443   // Verify that all the values are okay, compute the size of the values, and
17444   // reverse the list.
17445   unsigned NumNegativeBits = 0;
17446   unsigned NumPositiveBits = 0;
17447 
17448   // Keep track of whether all elements have type int.
17449   bool AllElementsInt = true;
17450 
17451   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17452     EnumConstantDecl *ECD =
17453       cast_or_null<EnumConstantDecl>(Elements[i]);
17454     if (!ECD) continue;  // Already issued a diagnostic.
17455 
17456     const llvm::APSInt &InitVal = ECD->getInitVal();
17457 
17458     // Keep track of the size of positive and negative values.
17459     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17460       NumPositiveBits = std::max(NumPositiveBits,
17461                                  (unsigned)InitVal.getActiveBits());
17462     else
17463       NumNegativeBits = std::max(NumNegativeBits,
17464                                  (unsigned)InitVal.getMinSignedBits());
17465 
17466     // Keep track of whether every enum element has type int (very common).
17467     if (AllElementsInt)
17468       AllElementsInt = ECD->getType() == Context.IntTy;
17469   }
17470 
17471   // Figure out the type that should be used for this enum.
17472   QualType BestType;
17473   unsigned BestWidth;
17474 
17475   // C++0x N3000 [conv.prom]p3:
17476   //   An rvalue of an unscoped enumeration type whose underlying
17477   //   type is not fixed can be converted to an rvalue of the first
17478   //   of the following types that can represent all the values of
17479   //   the enumeration: int, unsigned int, long int, unsigned long
17480   //   int, long long int, or unsigned long long int.
17481   // C99 6.4.4.3p2:
17482   //   An identifier declared as an enumeration constant has type int.
17483   // The C99 rule is modified by a gcc extension
17484   QualType BestPromotionType;
17485 
17486   bool Packed = Enum->hasAttr<PackedAttr>();
17487   // -fshort-enums is the equivalent to specifying the packed attribute on all
17488   // enum definitions.
17489   if (LangOpts.ShortEnums)
17490     Packed = true;
17491 
17492   // If the enum already has a type because it is fixed or dictated by the
17493   // target, promote that type instead of analyzing the enumerators.
17494   if (Enum->isComplete()) {
17495     BestType = Enum->getIntegerType();
17496     if (BestType->isPromotableIntegerType())
17497       BestPromotionType = Context.getPromotedIntegerType(BestType);
17498     else
17499       BestPromotionType = BestType;
17500 
17501     BestWidth = Context.getIntWidth(BestType);
17502   }
17503   else if (NumNegativeBits) {
17504     // If there is a negative value, figure out the smallest integer type (of
17505     // int/long/longlong) that fits.
17506     // If it's packed, check also if it fits a char or a short.
17507     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17508       BestType = Context.SignedCharTy;
17509       BestWidth = CharWidth;
17510     } else if (Packed && NumNegativeBits <= ShortWidth &&
17511                NumPositiveBits < ShortWidth) {
17512       BestType = Context.ShortTy;
17513       BestWidth = ShortWidth;
17514     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17515       BestType = Context.IntTy;
17516       BestWidth = IntWidth;
17517     } else {
17518       BestWidth = Context.getTargetInfo().getLongWidth();
17519 
17520       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17521         BestType = Context.LongTy;
17522       } else {
17523         BestWidth = Context.getTargetInfo().getLongLongWidth();
17524 
17525         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17526           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17527         BestType = Context.LongLongTy;
17528       }
17529     }
17530     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17531   } else {
17532     // If there is no negative value, figure out the smallest type that fits
17533     // all of the enumerator values.
17534     // If it's packed, check also if it fits a char or a short.
17535     if (Packed && NumPositiveBits <= CharWidth) {
17536       BestType = Context.UnsignedCharTy;
17537       BestPromotionType = Context.IntTy;
17538       BestWidth = CharWidth;
17539     } else if (Packed && NumPositiveBits <= ShortWidth) {
17540       BestType = Context.UnsignedShortTy;
17541       BestPromotionType = Context.IntTy;
17542       BestWidth = ShortWidth;
17543     } else if (NumPositiveBits <= IntWidth) {
17544       BestType = Context.UnsignedIntTy;
17545       BestWidth = IntWidth;
17546       BestPromotionType
17547         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17548                            ? Context.UnsignedIntTy : Context.IntTy;
17549     } else if (NumPositiveBits <=
17550                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17551       BestType = Context.UnsignedLongTy;
17552       BestPromotionType
17553         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17554                            ? Context.UnsignedLongTy : Context.LongTy;
17555     } else {
17556       BestWidth = Context.getTargetInfo().getLongLongWidth();
17557       assert(NumPositiveBits <= BestWidth &&
17558              "How could an initializer get larger than ULL?");
17559       BestType = Context.UnsignedLongLongTy;
17560       BestPromotionType
17561         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17562                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17563     }
17564   }
17565 
17566   // Loop over all of the enumerator constants, changing their types to match
17567   // the type of the enum if needed.
17568   for (auto *D : Elements) {
17569     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17570     if (!ECD) continue;  // Already issued a diagnostic.
17571 
17572     // Standard C says the enumerators have int type, but we allow, as an
17573     // extension, the enumerators to be larger than int size.  If each
17574     // enumerator value fits in an int, type it as an int, otherwise type it the
17575     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17576     // that X has type 'int', not 'unsigned'.
17577 
17578     // Determine whether the value fits into an int.
17579     llvm::APSInt InitVal = ECD->getInitVal();
17580 
17581     // If it fits into an integer type, force it.  Otherwise force it to match
17582     // the enum decl type.
17583     QualType NewTy;
17584     unsigned NewWidth;
17585     bool NewSign;
17586     if (!getLangOpts().CPlusPlus &&
17587         !Enum->isFixed() &&
17588         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17589       NewTy = Context.IntTy;
17590       NewWidth = IntWidth;
17591       NewSign = true;
17592     } else if (ECD->getType() == BestType) {
17593       // Already the right type!
17594       if (getLangOpts().CPlusPlus)
17595         // C++ [dcl.enum]p4: Following the closing brace of an
17596         // enum-specifier, each enumerator has the type of its
17597         // enumeration.
17598         ECD->setType(EnumType);
17599       continue;
17600     } else {
17601       NewTy = BestType;
17602       NewWidth = BestWidth;
17603       NewSign = BestType->isSignedIntegerOrEnumerationType();
17604     }
17605 
17606     // Adjust the APSInt value.
17607     InitVal = InitVal.extOrTrunc(NewWidth);
17608     InitVal.setIsSigned(NewSign);
17609     ECD->setInitVal(InitVal);
17610 
17611     // Adjust the Expr initializer and type.
17612     if (ECD->getInitExpr() &&
17613         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17614       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17615                                                 CK_IntegralCast,
17616                                                 ECD->getInitExpr(),
17617                                                 /*base paths*/ nullptr,
17618                                                 VK_RValue));
17619     if (getLangOpts().CPlusPlus)
17620       // C++ [dcl.enum]p4: Following the closing brace of an
17621       // enum-specifier, each enumerator has the type of its
17622       // enumeration.
17623       ECD->setType(EnumType);
17624     else
17625       ECD->setType(NewTy);
17626   }
17627 
17628   Enum->completeDefinition(BestType, BestPromotionType,
17629                            NumPositiveBits, NumNegativeBits);
17630 
17631   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17632 
17633   if (Enum->isClosedFlag()) {
17634     for (Decl *D : Elements) {
17635       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17636       if (!ECD) continue;  // Already issued a diagnostic.
17637 
17638       llvm::APSInt InitVal = ECD->getInitVal();
17639       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17640           !IsValueInFlagEnum(Enum, InitVal, true))
17641         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17642           << ECD << Enum;
17643     }
17644   }
17645 
17646   // Now that the enum type is defined, ensure it's not been underaligned.
17647   if (Enum->hasAttrs())
17648     CheckAlignasUnderalignment(Enum);
17649 }
17650 
17651 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17652                                   SourceLocation StartLoc,
17653                                   SourceLocation EndLoc) {
17654   StringLiteral *AsmString = cast<StringLiteral>(expr);
17655 
17656   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17657                                                    AsmString, StartLoc,
17658                                                    EndLoc);
17659   CurContext->addDecl(New);
17660   return New;
17661 }
17662 
17663 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17664                                       IdentifierInfo* AliasName,
17665                                       SourceLocation PragmaLoc,
17666                                       SourceLocation NameLoc,
17667                                       SourceLocation AliasNameLoc) {
17668   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17669                                          LookupOrdinaryName);
17670   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17671                            AttributeCommonInfo::AS_Pragma);
17672   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17673       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17674 
17675   // If a declaration that:
17676   // 1) declares a function or a variable
17677   // 2) has external linkage
17678   // already exists, add a label attribute to it.
17679   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17680     if (isDeclExternC(PrevDecl))
17681       PrevDecl->addAttr(Attr);
17682     else
17683       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17684           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17685   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17686   } else
17687     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17688 }
17689 
17690 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17691                              SourceLocation PragmaLoc,
17692                              SourceLocation NameLoc) {
17693   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17694 
17695   if (PrevDecl) {
17696     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17697   } else {
17698     (void)WeakUndeclaredIdentifiers.insert(
17699       std::pair<IdentifierInfo*,WeakInfo>
17700         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17701   }
17702 }
17703 
17704 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17705                                 IdentifierInfo* AliasName,
17706                                 SourceLocation PragmaLoc,
17707                                 SourceLocation NameLoc,
17708                                 SourceLocation AliasNameLoc) {
17709   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17710                                     LookupOrdinaryName);
17711   WeakInfo W = WeakInfo(Name, NameLoc);
17712 
17713   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17714     if (!PrevDecl->hasAttr<AliasAttr>())
17715       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17716         DeclApplyPragmaWeak(TUScope, ND, W);
17717   } else {
17718     (void)WeakUndeclaredIdentifiers.insert(
17719       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17720   }
17721 }
17722 
17723 Decl *Sema::getObjCDeclContext() const {
17724   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17725 }
17726 
17727 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17728   // Templates are emitted when they're instantiated.
17729   if (FD->isDependentContext())
17730     return FunctionEmissionStatus::TemplateDiscarded;
17731 
17732   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17733   if (LangOpts.OpenMPIsDevice) {
17734     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17735         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17736     if (DevTy.hasValue()) {
17737       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17738         OMPES = FunctionEmissionStatus::OMPDiscarded;
17739       else if (DeviceKnownEmittedFns.count(FD) > 0)
17740         OMPES = FunctionEmissionStatus::Emitted;
17741     }
17742   } else if (LangOpts.OpenMP) {
17743     // In OpenMP 4.5 all the functions are host functions.
17744     if (LangOpts.OpenMP <= 45) {
17745       OMPES = FunctionEmissionStatus::Emitted;
17746     } else {
17747       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17748           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17749       // In OpenMP 5.0 or above, DevTy may be changed later by
17750       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17751       // having no value does not imply host. The emission status will be
17752       // checked again at the end of compilation unit.
17753       if (DevTy.hasValue()) {
17754         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17755           OMPES = FunctionEmissionStatus::OMPDiscarded;
17756         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17757           OMPES = FunctionEmissionStatus::Emitted;
17758         }
17759       }
17760     }
17761   }
17762   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17763       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17764     return OMPES;
17765 
17766   if (LangOpts.CUDA) {
17767     // When compiling for device, host functions are never emitted.  Similarly,
17768     // when compiling for host, device and global functions are never emitted.
17769     // (Technically, we do emit a host-side stub for global functions, but this
17770     // doesn't count for our purposes here.)
17771     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17772     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17773       return FunctionEmissionStatus::CUDADiscarded;
17774     if (!LangOpts.CUDAIsDevice &&
17775         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17776       return FunctionEmissionStatus::CUDADiscarded;
17777 
17778     // Check whether this function is externally visible -- if so, it's
17779     // known-emitted.
17780     //
17781     // We have to check the GVA linkage of the function's *definition* -- if we
17782     // only have a declaration, we don't know whether or not the function will
17783     // be emitted, because (say) the definition could include "inline".
17784     FunctionDecl *Def = FD->getDefinition();
17785 
17786     if (Def &&
17787         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17788         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17789       return FunctionEmissionStatus::Emitted;
17790   }
17791 
17792   // Otherwise, the function is known-emitted if it's in our set of
17793   // known-emitted functions.
17794   return (DeviceKnownEmittedFns.count(FD) > 0)
17795              ? FunctionEmissionStatus::Emitted
17796              : FunctionEmissionStatus::Unknown;
17797 }
17798 
17799 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17800   // Host-side references to a __global__ function refer to the stub, so the
17801   // function itself is never emitted and therefore should not be marked.
17802   // If we have host fn calls kernel fn calls host+device, the HD function
17803   // does not get instantiated on the host. We model this by omitting at the
17804   // call to the kernel from the callgraph. This ensures that, when compiling
17805   // for host, only HD functions actually called from the host get marked as
17806   // known-emitted.
17807   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17808          IdentifyCUDATarget(Callee) == CFT_Global;
17809 }
17810