]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb, and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
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 llvm::make_unique<TypeNameValidatorCCC>(*this);
111   }
112
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119
120 } // end anonymous namespace
121
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157
158   default:
159     break;
160   }
161
162   return false;
163 }
164
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229
230   return FoundTypeDecl;
231 }
232
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327
328       return nullptr;
329     }
330
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464
465   assert(IIDecl && "Didn't find decl");
466
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519
520   return ParsedType::make(T);
521 }
522
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623
624   return DeclSpec::TST_unspecified;
625 }
626
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645
646     const Type *Ty = SS->getScopeRep()->getAsType();
647
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706
707       if (!CanRecover)
708         return;
709
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780
781   return false;
782 }
783
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829
830   return false;
831 }
832
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847
848 Sema::NameClassification
849 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
850                    SourceLocation NameLoc, const Token &NextToken,
851                    bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920
921     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
922       // In C++20 onwards, this could be an ADL-only call to a function
923       // template, and we're required to assume that this is a template name.
924       //
925       // FIXME: Find a way to still do typo correction in this case.
926       TemplateName Template =
927           Context.getAssumedTemplateName(NameInfo.getName());
928       return NameClassification::UndeclaredTemplate(Template);
929     }
930
931     // In C, we first see whether there is a tag type by the same name, in
932     // which case it's likely that the user just forgot to write "enum",
933     // "struct", or "union".
934     if (!getLangOpts().CPlusPlus && !SecondTry &&
935         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
936       break;
937     }
938
939     // Perform typo correction to determine if there is another name that is
940     // close to this name.
941     if (!SecondTry && CCC) {
942       SecondTry = true;
943       if (TypoCorrection Corrected =
944               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
945                           &SS, *CCC, CTK_ErrorRecovery)) {
946         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
947         unsigned QualifiedDiag = diag::err_no_member_suggest;
948
949         NamedDecl *FirstDecl = Corrected.getFoundDecl();
950         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
951         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
952             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
953           UnqualifiedDiag = diag::err_no_template_suggest;
954           QualifiedDiag = diag::err_no_member_template_suggest;
955         } else if (UnderlyingFirstDecl &&
956                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
957                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
958                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
959           UnqualifiedDiag = diag::err_unknown_typename_suggest;
960           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
961         }
962
963         if (SS.isEmpty()) {
964           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
965         } else {// FIXME: is this even reachable? Test it.
966           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
967           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
968                                   Name->getName().equals(CorrectedStr);
969           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
970                                     << Name << computeDeclContext(SS, false)
971                                     << DroppedSpecifier << SS.getRange());
972         }
973
974         // Update the name, so that the caller has the new name.
975         Name = Corrected.getCorrectionAsIdentifierInfo();
976
977         // Typo correction corrected to a keyword.
978         if (Corrected.isKeyword())
979           return Name;
980
981         // Also update the LookupResult...
982         // FIXME: This should probably go away at some point
983         Result.clear();
984         Result.setLookupName(Corrected.getCorrection());
985         if (FirstDecl)
986           Result.addDecl(FirstDecl);
987
988         // If we found an Objective-C instance variable, let
989         // LookupInObjCMethod build the appropriate expression to
990         // reference the ivar.
991         // FIXME: This is a gross hack.
992         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
993           Result.clear();
994           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
995           return E;
996         }
997
998         goto Corrected;
999       }
1000     }
1001
1002     // We failed to correct; just fall through and let the parser deal with it.
1003     Result.suppressDiagnostics();
1004     return NameClassification::Unknown();
1005
1006   case LookupResult::NotFoundInCurrentInstantiation: {
1007     // We performed name lookup into the current instantiation, and there were
1008     // dependent bases, so we treat this result the same way as any other
1009     // dependent nested-name-specifier.
1010
1011     // C++ [temp.res]p2:
1012     //   A name used in a template declaration or definition and that is
1013     //   dependent on a template-parameter is assumed not to name a type
1014     //   unless the applicable name lookup finds a type name or the name is
1015     //   qualified by the keyword typename.
1016     //
1017     // FIXME: If the next token is '<', we might want to ask the parser to
1018     // perform some heroics to see if we actually have a
1019     // template-argument-list, which would indicate a missing 'template'
1020     // keyword here.
1021     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1022                                       NameInfo, IsAddressOfOperand,
1023                                       /*TemplateArgs=*/nullptr);
1024   }
1025
1026   case LookupResult::Found:
1027   case LookupResult::FoundOverloaded:
1028   case LookupResult::FoundUnresolvedValue:
1029     break;
1030
1031   case LookupResult::Ambiguous:
1032     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1033         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1034                                       /*AllowDependent=*/false)) {
1035       // C++ [temp.local]p3:
1036       //   A lookup that finds an injected-class-name (10.2) can result in an
1037       //   ambiguity in certain cases (for example, if it is found in more than
1038       //   one base class). If all of the injected-class-names that are found
1039       //   refer to specializations of the same class template, and if the name
1040       //   is followed by a template-argument-list, the reference refers to the
1041       //   class template itself and not a specialization thereof, and is not
1042       //   ambiguous.
1043       //
1044       // This filtering can make an ambiguous result into an unambiguous one,
1045       // so try again after filtering out template names.
1046       FilterAcceptableTemplateNames(Result);
1047       if (!Result.isAmbiguous()) {
1048         IsFilteredTemplateName = true;
1049         break;
1050       }
1051     }
1052
1053     // Diagnose the ambiguity and return an error.
1054     return NameClassification::Error();
1055   }
1056
1057   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058       (IsFilteredTemplateName ||
1059        hasAnyAcceptableTemplateNames(
1060            Result, /*AllowFunctionTemplates=*/true,
1061            /*AllowDependent=*/false,
1062            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1063                getLangOpts().CPlusPlus2a))) {
1064     // C++ [temp.names]p3:
1065     //   After name lookup (3.4) finds that a name is a template-name or that
1066     //   an operator-function-id or a literal- operator-id refers to a set of
1067     //   overloaded functions any member of which is a function template if
1068     //   this is followed by a <, the < is always taken as the delimiter of a
1069     //   template-argument-list and never as the less-than operator.
1070     // C++2a [temp.names]p2:
1071     //   A name is also considered to refer to a template if it is an
1072     //   unqualified-id followed by a < and name lookup finds either one
1073     //   or more functions or finds nothing.
1074     if (!IsFilteredTemplateName)
1075       FilterAcceptableTemplateNames(Result);
1076
1077     bool IsFunctionTemplate;
1078     bool IsVarTemplate;
1079     TemplateName Template;
1080     if (Result.end() - Result.begin() > 1) {
1081       IsFunctionTemplate = true;
1082       Template = Context.getOverloadedTemplateName(Result.begin(),
1083                                                    Result.end());
1084     } else if (!Result.empty()) {
1085       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1086           *Result.begin(), /*AllowFunctionTemplates=*/true,
1087           /*AllowDependent=*/false));
1088       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1089       IsVarTemplate = isa<VarTemplateDecl>(TD);
1090
1091       if (SS.isSet() && !SS.isInvalid())
1092         Template =
1093             Context.getQualifiedTemplateName(SS.getScopeRep(),
1094                                              /*TemplateKeyword=*/false, TD);
1095       else
1096         Template = TemplateName(TD);
1097     } else {
1098       // All results were non-template functions. This is a function template
1099       // name.
1100       IsFunctionTemplate = true;
1101       Template = Context.getAssumedTemplateName(NameInfo.getName());
1102     }
1103
1104     if (IsFunctionTemplate) {
1105       // Function templates always go through overload resolution, at which
1106       // point we'll perform the various checks (e.g., accessibility) we need
1107       // to based on which function we selected.
1108       Result.suppressDiagnostics();
1109
1110       return NameClassification::FunctionTemplate(Template);
1111     }
1112
1113     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1114                          : NameClassification::TypeTemplate(Template);
1115   }
1116
1117   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1118   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1119     DiagnoseUseOfDecl(Type, NameLoc);
1120     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1121     QualType T = Context.getTypeDeclType(Type);
1122     if (SS.isNotEmpty())
1123       return buildNestedType(*this, SS, T, NameLoc);
1124     return ParsedType::make(T);
1125   }
1126
1127   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1128   if (!Class) {
1129     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1130     if (ObjCCompatibleAliasDecl *Alias =
1131             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1132       Class = Alias->getClassInterface();
1133   }
1134
1135   if (Class) {
1136     DiagnoseUseOfDecl(Class, NameLoc);
1137
1138     if (NextToken.is(tok::period)) {
1139       // Interface. <something> is parsed as a property reference expression.
1140       // Just return "unknown" as a fall-through for now.
1141       Result.suppressDiagnostics();
1142       return NameClassification::Unknown();
1143     }
1144
1145     QualType T = Context.getObjCInterfaceType(Class);
1146     return ParsedType::make(T);
1147   }
1148
1149   // We can have a type template here if we're classifying a template argument.
1150   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1151       !isa<VarTemplateDecl>(FirstDecl))
1152     return NameClassification::TypeTemplate(
1153         TemplateName(cast<TemplateDecl>(FirstDecl)));
1154
1155   // Check for a tag type hidden by a non-type decl in a few cases where it
1156   // seems likely a type is wanted instead of the non-type that was found.
1157   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1158   if ((NextToken.is(tok::identifier) ||
1159        (NextIsOp &&
1160         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1161       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1162     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1163     DiagnoseUseOfDecl(Type, NameLoc);
1164     QualType T = Context.getTypeDeclType(Type);
1165     if (SS.isNotEmpty())
1166       return buildNestedType(*this, SS, T, NameLoc);
1167     return ParsedType::make(T);
1168   }
1169
1170   if (FirstDecl->isCXXClassMember())
1171     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1172                                            nullptr, S);
1173
1174   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1175   return BuildDeclarationNameExpr(SS, Result, ADL);
1176 }
1177
1178 Sema::TemplateNameKindForDiagnostics
1179 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1180   auto *TD = Name.getAsTemplateDecl();
1181   if (!TD)
1182     return TemplateNameKindForDiagnostics::DependentTemplate;
1183   if (isa<ClassTemplateDecl>(TD))
1184     return TemplateNameKindForDiagnostics::ClassTemplate;
1185   if (isa<FunctionTemplateDecl>(TD))
1186     return TemplateNameKindForDiagnostics::FunctionTemplate;
1187   if (isa<VarTemplateDecl>(TD))
1188     return TemplateNameKindForDiagnostics::VarTemplate;
1189   if (isa<TypeAliasTemplateDecl>(TD))
1190     return TemplateNameKindForDiagnostics::AliasTemplate;
1191   if (isa<TemplateTemplateParmDecl>(TD))
1192     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1193   if (isa<ConceptDecl>(TD))
1194     return TemplateNameKindForDiagnostics::Concept;
1195   return TemplateNameKindForDiagnostics::DependentTemplate;
1196 }
1197
1198 // Determines the context to return to after temporarily entering a
1199 // context.  This depends in an unnecessarily complicated way on the
1200 // exact ordering of callbacks from the parser.
1201 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1202
1203   // Functions defined inline within classes aren't parsed until we've
1204   // finished parsing the top-level class, so the top-level class is
1205   // the context we'll need to return to.
1206   // A Lambda call operator whose parent is a class must not be treated
1207   // as an inline member function.  A Lambda can be used legally
1208   // either as an in-class member initializer or a default argument.  These
1209   // are parsed once the class has been marked complete and so the containing
1210   // context would be the nested class (when the lambda is defined in one);
1211   // If the class is not complete, then the lambda is being used in an
1212   // ill-formed fashion (such as to specify the width of a bit-field, or
1213   // in an array-bound) - in which case we still want to return the
1214   // lexically containing DC (which could be a nested class).
1215   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1216     DC = DC->getLexicalParent();
1217
1218     // A function not defined within a class will always return to its
1219     // lexical context.
1220     if (!isa<CXXRecordDecl>(DC))
1221       return DC;
1222
1223     // A C++ inline method/friend is parsed *after* the topmost class
1224     // it was declared in is fully parsed ("complete");  the topmost
1225     // class is the context we need to return to.
1226     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1227       DC = RD;
1228
1229     // Return the declaration context of the topmost class the inline method is
1230     // declared in.
1231     return DC;
1232   }
1233
1234   return DC->getLexicalParent();
1235 }
1236
1237 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1238   assert(getContainingDC(DC) == CurContext &&
1239       "The next DeclContext should be lexically contained in the current one.");
1240   CurContext = DC;
1241   S->setEntity(DC);
1242 }
1243
1244 void Sema::PopDeclContext() {
1245   assert(CurContext && "DeclContext imbalance!");
1246
1247   CurContext = getContainingDC(CurContext);
1248   assert(CurContext && "Popped translation unit!");
1249 }
1250
1251 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1252                                                                     Decl *D) {
1253   // Unlike PushDeclContext, the context to which we return is not necessarily
1254   // the containing DC of TD, because the new context will be some pre-existing
1255   // TagDecl definition instead of a fresh one.
1256   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1257   CurContext = cast<TagDecl>(D)->getDefinition();
1258   assert(CurContext && "skipping definition of undefined tag");
1259   // Start lookups from the parent of the current context; we don't want to look
1260   // into the pre-existing complete definition.
1261   S->setEntity(CurContext->getLookupParent());
1262   return Result;
1263 }
1264
1265 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1266   CurContext = static_cast<decltype(CurContext)>(Context);
1267 }
1268
1269 /// EnterDeclaratorContext - Used when we must lookup names in the context
1270 /// of a declarator's nested name specifier.
1271 ///
1272 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1273   // C++0x [basic.lookup.unqual]p13:
1274   //   A name used in the definition of a static data member of class
1275   //   X (after the qualified-id of the static member) is looked up as
1276   //   if the name was used in a member function of X.
1277   // C++0x [basic.lookup.unqual]p14:
1278   //   If a variable member of a namespace is defined outside of the
1279   //   scope of its namespace then any name used in the definition of
1280   //   the variable member (after the declarator-id) is looked up as
1281   //   if the definition of the variable member occurred in its
1282   //   namespace.
1283   // Both of these imply that we should push a scope whose context
1284   // is the semantic context of the declaration.  We can't use
1285   // PushDeclContext here because that context is not necessarily
1286   // lexically contained in the current context.  Fortunately,
1287   // the containing scope should have the appropriate information.
1288
1289   assert(!S->getEntity() && "scope already has entity");
1290
1291 #ifndef NDEBUG
1292   Scope *Ancestor = S->getParent();
1293   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1294   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1295 #endif
1296
1297   CurContext = DC;
1298   S->setEntity(DC);
1299 }
1300
1301 void Sema::ExitDeclaratorContext(Scope *S) {
1302   assert(S->getEntity() == CurContext && "Context imbalance!");
1303
1304   // Switch back to the lexical context.  The safety of this is
1305   // enforced by an assert in EnterDeclaratorContext.
1306   Scope *Ancestor = S->getParent();
1307   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1308   CurContext = Ancestor->getEntity();
1309
1310   // We don't need to do anything with the scope, which is going to
1311   // disappear.
1312 }
1313
1314 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1315   // We assume that the caller has already called
1316   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1317   FunctionDecl *FD = D->getAsFunction();
1318   if (!FD)
1319     return;
1320
1321   // Same implementation as PushDeclContext, but enters the context
1322   // from the lexical parent, rather than the top-level class.
1323   assert(CurContext == FD->getLexicalParent() &&
1324     "The next DeclContext should be lexically contained in the current one.");
1325   CurContext = FD;
1326   S->setEntity(CurContext);
1327
1328   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1329     ParmVarDecl *Param = FD->getParamDecl(P);
1330     // If the parameter has an identifier, then add it to the scope
1331     if (Param->getIdentifier()) {
1332       S->AddDecl(Param);
1333       IdResolver.AddDecl(Param);
1334     }
1335   }
1336 }
1337
1338 void Sema::ActOnExitFunctionContext() {
1339   // Same implementation as PopDeclContext, but returns to the lexical parent,
1340   // rather than the top-level class.
1341   assert(CurContext && "DeclContext imbalance!");
1342   CurContext = CurContext->getLexicalParent();
1343   assert(CurContext && "Popped translation unit!");
1344 }
1345
1346 /// Determine whether we allow overloading of the function
1347 /// PrevDecl with another declaration.
1348 ///
1349 /// This routine determines whether overloading is possible, not
1350 /// whether some new function is actually an overload. It will return
1351 /// true in C++ (where we can always provide overloads) or, as an
1352 /// extension, in C when the previous function is already an
1353 /// overloaded function declaration or has the "overloadable"
1354 /// attribute.
1355 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1356                                        ASTContext &Context,
1357                                        const FunctionDecl *New) {
1358   if (Context.getLangOpts().CPlusPlus)
1359     return true;
1360
1361   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1362     return true;
1363
1364   return Previous.getResultKind() == LookupResult::Found &&
1365          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1366           New->hasAttr<OverloadableAttr>());
1367 }
1368
1369 /// Add this decl to the scope shadowed decl chains.
1370 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1371   // Move up the scope chain until we find the nearest enclosing
1372   // non-transparent context. The declaration will be introduced into this
1373   // scope.
1374   while (S->getEntity() && S->getEntity()->isTransparentContext())
1375     S = S->getParent();
1376
1377   // Add scoped declarations into their context, so that they can be
1378   // found later. Declarations without a context won't be inserted
1379   // into any context.
1380   if (AddToContext)
1381     CurContext->addDecl(D);
1382
1383   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1384   // are function-local declarations.
1385   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1386       !D->getDeclContext()->getRedeclContext()->Equals(
1387         D->getLexicalDeclContext()->getRedeclContext()) &&
1388       !D->getLexicalDeclContext()->isFunctionOrMethod())
1389     return;
1390
1391   // Template instantiations should also not be pushed into scope.
1392   if (isa<FunctionDecl>(D) &&
1393       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1394     return;
1395
1396   // If this replaces anything in the current scope,
1397   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1398                                IEnd = IdResolver.end();
1399   for (; I != IEnd; ++I) {
1400     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1401       S->RemoveDecl(*I);
1402       IdResolver.RemoveDecl(*I);
1403
1404       // Should only need to replace one decl.
1405       break;
1406     }
1407   }
1408
1409   S->AddDecl(D);
1410
1411   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1412     // Implicitly-generated labels may end up getting generated in an order that
1413     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1414     // the label at the appropriate place in the identifier chain.
1415     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1416       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1417       if (IDC == CurContext) {
1418         if (!S->isDeclScope(*I))
1419           continue;
1420       } else if (IDC->Encloses(CurContext))
1421         break;
1422     }
1423
1424     IdResolver.InsertDeclAfter(I, D);
1425   } else {
1426     IdResolver.AddDecl(D);
1427   }
1428 }
1429
1430 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1431                          bool AllowInlineNamespace) {
1432   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1433 }
1434
1435 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1436   DeclContext *TargetDC = DC->getPrimaryContext();
1437   do {
1438     if (DeclContext *ScopeDC = S->getEntity())
1439       if (ScopeDC->getPrimaryContext() == TargetDC)
1440         return S;
1441   } while ((S = S->getParent()));
1442
1443   return nullptr;
1444 }
1445
1446 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1447                                             DeclContext*,
1448                                             ASTContext&);
1449
1450 /// Filters out lookup results that don't fall within the given scope
1451 /// as determined by isDeclInScope.
1452 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1453                                 bool ConsiderLinkage,
1454                                 bool AllowInlineNamespace) {
1455   LookupResult::Filter F = R.makeFilter();
1456   while (F.hasNext()) {
1457     NamedDecl *D = F.next();
1458
1459     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1460       continue;
1461
1462     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1463       continue;
1464
1465     F.erase();
1466   }
1467
1468   F.done();
1469 }
1470
1471 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1472 /// have compatible owning modules.
1473 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1474   // FIXME: The Modules TS is not clear about how friend declarations are
1475   // to be treated. It's not meaningful to have different owning modules for
1476   // linkage in redeclarations of the same entity, so for now allow the
1477   // redeclaration and change the owning modules to match.
1478   if (New->getFriendObjectKind() &&
1479       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1480     New->setLocalOwningModule(Old->getOwningModule());
1481     makeMergedDefinitionVisible(New);
1482     return false;
1483   }
1484
1485   Module *NewM = New->getOwningModule();
1486   Module *OldM = Old->getOwningModule();
1487
1488   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1489     NewM = NewM->Parent;
1490   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1491     OldM = OldM->Parent;
1492
1493   if (NewM == OldM)
1494     return false;
1495
1496   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1497   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1498   if (NewIsModuleInterface || OldIsModuleInterface) {
1499     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1500     //   if a declaration of D [...] appears in the purview of a module, all
1501     //   other such declarations shall appear in the purview of the same module
1502     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1503       << New
1504       << NewIsModuleInterface
1505       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1506       << OldIsModuleInterface
1507       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1508     Diag(Old->getLocation(), diag::note_previous_declaration);
1509     New->setInvalidDecl();
1510     return true;
1511   }
1512
1513   return false;
1514 }
1515
1516 static bool isUsingDecl(NamedDecl *D) {
1517   return isa<UsingShadowDecl>(D) ||
1518          isa<UnresolvedUsingTypenameDecl>(D) ||
1519          isa<UnresolvedUsingValueDecl>(D);
1520 }
1521
1522 /// Removes using shadow declarations from the lookup results.
1523 static void RemoveUsingDecls(LookupResult &R) {
1524   LookupResult::Filter F = R.makeFilter();
1525   while (F.hasNext())
1526     if (isUsingDecl(F.next()))
1527       F.erase();
1528
1529   F.done();
1530 }
1531
1532 /// Check for this common pattern:
1533 /// @code
1534 /// class S {
1535 ///   S(const S&); // DO NOT IMPLEMENT
1536 ///   void operator=(const S&); // DO NOT IMPLEMENT
1537 /// };
1538 /// @endcode
1539 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1540   // FIXME: Should check for private access too but access is set after we get
1541   // the decl here.
1542   if (D->doesThisDeclarationHaveABody())
1543     return false;
1544
1545   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1546     return CD->isCopyConstructor();
1547   return D->isCopyAssignmentOperator();
1548 }
1549
1550 // We need this to handle
1551 //
1552 // typedef struct {
1553 //   void *foo() { return 0; }
1554 // } A;
1555 //
1556 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1557 // for example. If 'A', foo will have external linkage. If we have '*A',
1558 // foo will have no linkage. Since we can't know until we get to the end
1559 // of the typedef, this function finds out if D might have non-external linkage.
1560 // Callers should verify at the end of the TU if it D has external linkage or
1561 // not.
1562 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1563   const DeclContext *DC = D->getDeclContext();
1564   while (!DC->isTranslationUnit()) {
1565     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1566       if (!RD->hasNameForLinkage())
1567         return true;
1568     }
1569     DC = DC->getParent();
1570   }
1571
1572   return !D->isExternallyVisible();
1573 }
1574
1575 // FIXME: This needs to be refactored; some other isInMainFile users want
1576 // these semantics.
1577 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1578   if (S.TUKind != TU_Complete)
1579     return false;
1580   return S.SourceMgr.isInMainFile(Loc);
1581 }
1582
1583 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1584   assert(D);
1585
1586   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1587     return false;
1588
1589   // Ignore all entities declared within templates, and out-of-line definitions
1590   // of members of class templates.
1591   if (D->getDeclContext()->isDependentContext() ||
1592       D->getLexicalDeclContext()->isDependentContext())
1593     return false;
1594
1595   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1596     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1597       return false;
1598     // A non-out-of-line declaration of a member specialization was implicitly
1599     // instantiated; it's the out-of-line declaration that we're interested in.
1600     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1601         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1602       return false;
1603
1604     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1605       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1606         return false;
1607     } else {
1608       // 'static inline' functions are defined in headers; don't warn.
1609       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1610         return false;
1611     }
1612
1613     if (FD->doesThisDeclarationHaveABody() &&
1614         Context.DeclMustBeEmitted(FD))
1615       return false;
1616   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1617     // Constants and utility variables are defined in headers with internal
1618     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1619     // like "inline".)
1620     if (!isMainFileLoc(*this, VD->getLocation()))
1621       return false;
1622
1623     if (Context.DeclMustBeEmitted(VD))
1624       return false;
1625
1626     if (VD->isStaticDataMember() &&
1627         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1628       return false;
1629     if (VD->isStaticDataMember() &&
1630         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1631         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1632       return false;
1633
1634     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1635       return false;
1636   } else {
1637     return false;
1638   }
1639
1640   // Only warn for unused decls internal to the translation unit.
1641   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1642   // for inline functions defined in the main source file, for instance.
1643   return mightHaveNonExternalLinkage(D);
1644 }
1645
1646 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1647   if (!D)
1648     return;
1649
1650   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651     const FunctionDecl *First = FD->getFirstDecl();
1652     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1653       return; // First should already be in the vector.
1654   }
1655
1656   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1657     const VarDecl *First = VD->getFirstDecl();
1658     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1659       return; // First should already be in the vector.
1660   }
1661
1662   if (ShouldWarnIfUnusedFileScopedDecl(D))
1663     UnusedFileScopedDecls.push_back(D);
1664 }
1665
1666 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1667   if (D->isInvalidDecl())
1668     return false;
1669
1670   bool Referenced = false;
1671   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1672     // For a decomposition declaration, warn if none of the bindings are
1673     // referenced, instead of if the variable itself is referenced (which
1674     // it is, by the bindings' expressions).
1675     for (auto *BD : DD->bindings()) {
1676       if (BD->isReferenced()) {
1677         Referenced = true;
1678         break;
1679       }
1680     }
1681   } else if (!D->getDeclName()) {
1682     return false;
1683   } else if (D->isReferenced() || D->isUsed()) {
1684     Referenced = true;
1685   }
1686
1687   if (Referenced || D->hasAttr<UnusedAttr>() ||
1688       D->hasAttr<ObjCPreciseLifetimeAttr>())
1689     return false;
1690
1691   if (isa<LabelDecl>(D))
1692     return true;
1693
1694   // Except for labels, we only care about unused decls that are local to
1695   // functions.
1696   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1697   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1698     // For dependent types, the diagnostic is deferred.
1699     WithinFunction =
1700         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1701   if (!WithinFunction)
1702     return false;
1703
1704   if (isa<TypedefNameDecl>(D))
1705     return true;
1706
1707   // White-list anything that isn't a local variable.
1708   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1709     return false;
1710
1711   // Types of valid local variables should be complete, so this should succeed.
1712   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713
1714     // White-list anything with an __attribute__((unused)) type.
1715     const auto *Ty = VD->getType().getTypePtr();
1716
1717     // Only look at the outermost level of typedef.
1718     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1719       if (TT->getDecl()->hasAttr<UnusedAttr>())
1720         return false;
1721     }
1722
1723     // If we failed to complete the type for some reason, or if the type is
1724     // dependent, don't diagnose the variable.
1725     if (Ty->isIncompleteType() || Ty->isDependentType())
1726       return false;
1727
1728     // Look at the element type to ensure that the warning behaviour is
1729     // consistent for both scalars and arrays.
1730     Ty = Ty->getBaseElementTypeUnsafe();
1731
1732     if (const TagType *TT = Ty->getAs<TagType>()) {
1733       const TagDecl *Tag = TT->getDecl();
1734       if (Tag->hasAttr<UnusedAttr>())
1735         return false;
1736
1737       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1738         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1739           return false;
1740
1741         if (const Expr *Init = VD->getInit()) {
1742           if (const ExprWithCleanups *Cleanups =
1743                   dyn_cast<ExprWithCleanups>(Init))
1744             Init = Cleanups->getSubExpr();
1745           const CXXConstructExpr *Construct =
1746             dyn_cast<CXXConstructExpr>(Init);
1747           if (Construct && !Construct->isElidable()) {
1748             CXXConstructorDecl *CD = Construct->getConstructor();
1749             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1750                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1751               return false;
1752           }
1753         }
1754       }
1755     }
1756
1757     // TODO: __attribute__((unused)) templates?
1758   }
1759
1760   return true;
1761 }
1762
1763 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1764                                      FixItHint &Hint) {
1765   if (isa<LabelDecl>(D)) {
1766     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1767         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1768         true);
1769     if (AfterColon.isInvalid())
1770       return;
1771     Hint = FixItHint::CreateRemoval(
1772         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1773   }
1774 }
1775
1776 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1777   if (D->getTypeForDecl()->isDependentType())
1778     return;
1779
1780   for (auto *TmpD : D->decls()) {
1781     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1782       DiagnoseUnusedDecl(T);
1783     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1784       DiagnoseUnusedNestedTypedefs(R);
1785   }
1786 }
1787
1788 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1789 /// unless they are marked attr(unused).
1790 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1791   if (!ShouldDiagnoseUnusedDecl(D))
1792     return;
1793
1794   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1795     // typedefs can be referenced later on, so the diagnostics are emitted
1796     // at end-of-translation-unit.
1797     UnusedLocalTypedefNameCandidates.insert(TD);
1798     return;
1799   }
1800
1801   FixItHint Hint;
1802   GenerateFixForUnusedDecl(D, Context, Hint);
1803
1804   unsigned DiagID;
1805   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1806     DiagID = diag::warn_unused_exception_param;
1807   else if (isa<LabelDecl>(D))
1808     DiagID = diag::warn_unused_label;
1809   else
1810     DiagID = diag::warn_unused_variable;
1811
1812   Diag(D->getLocation(), DiagID) << D << Hint;
1813 }
1814
1815 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1816   // Verify that we have no forward references left.  If so, there was a goto
1817   // or address of a label taken, but no definition of it.  Label fwd
1818   // definitions are indicated with a null substmt which is also not a resolved
1819   // MS inline assembly label name.
1820   bool Diagnose = false;
1821   if (L->isMSAsmLabel())
1822     Diagnose = !L->isResolvedMSAsmLabel();
1823   else
1824     Diagnose = L->getStmt() == nullptr;
1825   if (Diagnose)
1826     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1827 }
1828
1829 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1830   S->mergeNRVOIntoParent();
1831
1832   if (S->decl_empty()) return;
1833   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1834          "Scope shouldn't contain decls!");
1835
1836   for (auto *TmpD : S->decls()) {
1837     assert(TmpD && "This decl didn't get pushed??");
1838
1839     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1840     NamedDecl *D = cast<NamedDecl>(TmpD);
1841
1842     // Diagnose unused variables in this scope.
1843     if (!S->hasUnrecoverableErrorOccurred()) {
1844       DiagnoseUnusedDecl(D);
1845       if (const auto *RD = dyn_cast<RecordDecl>(D))
1846         DiagnoseUnusedNestedTypedefs(RD);
1847     }
1848
1849     if (!D->getDeclName()) continue;
1850
1851     // If this was a forward reference to a label, verify it was defined.
1852     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1853       CheckPoppedLabel(LD, *this);
1854
1855     // Remove this name from our lexical scope, and warn on it if we haven't
1856     // already.
1857     IdResolver.RemoveDecl(D);
1858     auto ShadowI = ShadowingDecls.find(D);
1859     if (ShadowI != ShadowingDecls.end()) {
1860       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1861         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1862             << D << FD << FD->getParent();
1863         Diag(FD->getLocation(), diag::note_previous_declaration);
1864       }
1865       ShadowingDecls.erase(ShadowI);
1866     }
1867   }
1868 }
1869
1870 /// Look for an Objective-C class in the translation unit.
1871 ///
1872 /// \param Id The name of the Objective-C class we're looking for. If
1873 /// typo-correction fixes this name, the Id will be updated
1874 /// to the fixed name.
1875 ///
1876 /// \param IdLoc The location of the name in the translation unit.
1877 ///
1878 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1879 /// if there is no class with the given name.
1880 ///
1881 /// \returns The declaration of the named Objective-C class, or NULL if the
1882 /// class could not be found.
1883 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1884                                               SourceLocation IdLoc,
1885                                               bool DoTypoCorrection) {
1886   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1887   // creation from this context.
1888   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1889
1890   if (!IDecl && DoTypoCorrection) {
1891     // Perform typo correction at the given location, but only if we
1892     // find an Objective-C class name.
1893     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1894     if (TypoCorrection C =
1895             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1896                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1897       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1898       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1899       Id = IDecl->getIdentifier();
1900     }
1901   }
1902   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1903   // This routine must always return a class definition, if any.
1904   if (Def && Def->getDefinition())
1905       Def = Def->getDefinition();
1906   return Def;
1907 }
1908
1909 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1910 /// from S, where a non-field would be declared. This routine copes
1911 /// with the difference between C and C++ scoping rules in structs and
1912 /// unions. For example, the following code is well-formed in C but
1913 /// ill-formed in C++:
1914 /// @code
1915 /// struct S6 {
1916 ///   enum { BAR } e;
1917 /// };
1918 ///
1919 /// void test_S6() {
1920 ///   struct S6 a;
1921 ///   a.e = BAR;
1922 /// }
1923 /// @endcode
1924 /// For the declaration of BAR, this routine will return a different
1925 /// scope. The scope S will be the scope of the unnamed enumeration
1926 /// within S6. In C++, this routine will return the scope associated
1927 /// with S6, because the enumeration's scope is a transparent
1928 /// context but structures can contain non-field names. In C, this
1929 /// routine will return the translation unit scope, since the
1930 /// enumeration's scope is a transparent context and structures cannot
1931 /// contain non-field names.
1932 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1933   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1934          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1935          (S->isClassScope() && !getLangOpts().CPlusPlus))
1936     S = S->getParent();
1937   return S;
1938 }
1939
1940 /// Looks up the declaration of "struct objc_super" and
1941 /// saves it for later use in building builtin declaration of
1942 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1943 /// pre-existing declaration exists no action takes place.
1944 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1945                                         IdentifierInfo *II) {
1946   if (!II->isStr("objc_msgSendSuper"))
1947     return;
1948   ASTContext &Context = ThisSema.Context;
1949
1950   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1951                       SourceLocation(), Sema::LookupTagName);
1952   ThisSema.LookupName(Result, S);
1953   if (Result.getResultKind() == LookupResult::Found)
1954     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1955       Context.setObjCSuperType(Context.getTagDeclType(TD));
1956 }
1957
1958 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1959                                ASTContext::GetBuiltinTypeError Error) {
1960   switch (Error) {
1961   case ASTContext::GE_None:
1962     return "";
1963   case ASTContext::GE_Missing_type:
1964     return BuiltinInfo.getHeaderName(ID);
1965   case ASTContext::GE_Missing_stdio:
1966     return "stdio.h";
1967   case ASTContext::GE_Missing_setjmp:
1968     return "setjmp.h";
1969   case ASTContext::GE_Missing_ucontext:
1970     return "ucontext.h";
1971   }
1972   llvm_unreachable("unhandled error kind");
1973 }
1974
1975 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1976 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1977 /// if we're creating this built-in in anticipation of redeclaring the
1978 /// built-in.
1979 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1980                                      Scope *S, bool ForRedeclaration,
1981                                      SourceLocation Loc) {
1982   LookupPredefedObjCSuperType(*this, S, II);
1983
1984   ASTContext::GetBuiltinTypeError Error;
1985   QualType R = Context.GetBuiltinType(ID, Error);
1986   if (Error) {
1987     if (!ForRedeclaration)
1988       return nullptr;
1989
1990     // If we have a builtin without an associated type we should not emit a
1991     // warning when we were not able to find a type for it.
1992     if (Error == ASTContext::GE_Missing_type)
1993       return nullptr;
1994
1995     // If we could not find a type for setjmp it is because the jmp_buf type was
1996     // not defined prior to the setjmp declaration.
1997     if (Error == ASTContext::GE_Missing_setjmp) {
1998       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
1999           << Context.BuiltinInfo.getName(ID);
2000       return nullptr;
2001     }
2002
2003     // Generally, we emit a warning that the declaration requires the
2004     // appropriate header.
2005     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2006         << getHeaderName(Context.BuiltinInfo, ID, Error)
2007         << Context.BuiltinInfo.getName(ID);
2008     return nullptr;
2009   }
2010
2011   if (!ForRedeclaration &&
2012       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2013        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2014     Diag(Loc, diag::ext_implicit_lib_function_decl)
2015         << Context.BuiltinInfo.getName(ID) << R;
2016     if (Context.BuiltinInfo.getHeaderName(ID) &&
2017         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2018       Diag(Loc, diag::note_include_header_or_declare)
2019           << Context.BuiltinInfo.getHeaderName(ID)
2020           << Context.BuiltinInfo.getName(ID);
2021   }
2022
2023   if (R.isNull())
2024     return nullptr;
2025
2026   DeclContext *Parent = Context.getTranslationUnitDecl();
2027   if (getLangOpts().CPlusPlus) {
2028     LinkageSpecDecl *CLinkageDecl =
2029         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2030                                 LinkageSpecDecl::lang_c, false);
2031     CLinkageDecl->setImplicit();
2032     Parent->addDecl(CLinkageDecl);
2033     Parent = CLinkageDecl;
2034   }
2035
2036   FunctionDecl *New = FunctionDecl::Create(Context,
2037                                            Parent,
2038                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2039                                            SC_Extern,
2040                                            false,
2041                                            R->isFunctionProtoType());
2042   New->setImplicit();
2043
2044   // Create Decl objects for each parameter, adding them to the
2045   // FunctionDecl.
2046   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2047     SmallVector<ParmVarDecl*, 16> Params;
2048     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2049       ParmVarDecl *parm =
2050           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2051                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2052                               SC_None, nullptr);
2053       parm->setScopeInfo(0, i);
2054       Params.push_back(parm);
2055     }
2056     New->setParams(Params);
2057   }
2058
2059   AddKnownFunctionAttributes(New);
2060   RegisterLocallyScopedExternCDecl(New, S);
2061
2062   // TUScope is the translation-unit scope to insert this function into.
2063   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2064   // relate Scopes to DeclContexts, and probably eliminate CurContext
2065   // entirely, but we're not there yet.
2066   DeclContext *SavedContext = CurContext;
2067   CurContext = Parent;
2068   PushOnScopeChains(New, TUScope);
2069   CurContext = SavedContext;
2070   return New;
2071 }
2072
2073 /// Typedef declarations don't have linkage, but they still denote the same
2074 /// entity if their types are the same.
2075 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2076 /// isSameEntity.
2077 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2078                                                      TypedefNameDecl *Decl,
2079                                                      LookupResult &Previous) {
2080   // This is only interesting when modules are enabled.
2081   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2082     return;
2083
2084   // Empty sets are uninteresting.
2085   if (Previous.empty())
2086     return;
2087
2088   LookupResult::Filter Filter = Previous.makeFilter();
2089   while (Filter.hasNext()) {
2090     NamedDecl *Old = Filter.next();
2091
2092     // Non-hidden declarations are never ignored.
2093     if (S.isVisible(Old))
2094       continue;
2095
2096     // Declarations of the same entity are not ignored, even if they have
2097     // different linkages.
2098     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2099       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2100                                 Decl->getUnderlyingType()))
2101         continue;
2102
2103       // If both declarations give a tag declaration a typedef name for linkage
2104       // purposes, then they declare the same entity.
2105       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2106           Decl->getAnonDeclWithTypedefName())
2107         continue;
2108     }
2109
2110     Filter.erase();
2111   }
2112
2113   Filter.done();
2114 }
2115
2116 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2117   QualType OldType;
2118   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2119     OldType = OldTypedef->getUnderlyingType();
2120   else
2121     OldType = Context.getTypeDeclType(Old);
2122   QualType NewType = New->getUnderlyingType();
2123
2124   if (NewType->isVariablyModifiedType()) {
2125     // Must not redefine a typedef with a variably-modified type.
2126     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2127     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2128       << Kind << NewType;
2129     if (Old->getLocation().isValid())
2130       notePreviousDefinition(Old, New->getLocation());
2131     New->setInvalidDecl();
2132     return true;
2133   }
2134
2135   if (OldType != NewType &&
2136       !OldType->isDependentType() &&
2137       !NewType->isDependentType() &&
2138       !Context.hasSameType(OldType, NewType)) {
2139     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2140     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2141       << Kind << NewType << OldType;
2142     if (Old->getLocation().isValid())
2143       notePreviousDefinition(Old, New->getLocation());
2144     New->setInvalidDecl();
2145     return true;
2146   }
2147   return false;
2148 }
2149
2150 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2151 /// same name and scope as a previous declaration 'Old'.  Figure out
2152 /// how to resolve this situation, merging decls or emitting
2153 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2154 ///
2155 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2156                                 LookupResult &OldDecls) {
2157   // If the new decl is known invalid already, don't bother doing any
2158   // merging checks.
2159   if (New->isInvalidDecl()) return;
2160
2161   // Allow multiple definitions for ObjC built-in typedefs.
2162   // FIXME: Verify the underlying types are equivalent!
2163   if (getLangOpts().ObjC) {
2164     const IdentifierInfo *TypeID = New->getIdentifier();
2165     switch (TypeID->getLength()) {
2166     default: break;
2167     case 2:
2168       {
2169         if (!TypeID->isStr("id"))
2170           break;
2171         QualType T = New->getUnderlyingType();
2172         if (!T->isPointerType())
2173           break;
2174         if (!T->isVoidPointerType()) {
2175           QualType PT = T->getAs<PointerType>()->getPointeeType();
2176           if (!PT->isStructureType())
2177             break;
2178         }
2179         Context.setObjCIdRedefinitionType(T);
2180         // Install the built-in type for 'id', ignoring the current definition.
2181         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2182         return;
2183       }
2184     case 5:
2185       if (!TypeID->isStr("Class"))
2186         break;
2187       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2188       // Install the built-in type for 'Class', ignoring the current definition.
2189       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2190       return;
2191     case 3:
2192       if (!TypeID->isStr("SEL"))
2193         break;
2194       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2195       // Install the built-in type for 'SEL', ignoring the current definition.
2196       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2197       return;
2198     }
2199     // Fall through - the typedef name was not a builtin type.
2200   }
2201
2202   // Verify the old decl was also a type.
2203   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2204   if (!Old) {
2205     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2206       << New->getDeclName();
2207
2208     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2209     if (OldD->getLocation().isValid())
2210       notePreviousDefinition(OldD, New->getLocation());
2211
2212     return New->setInvalidDecl();
2213   }
2214
2215   // If the old declaration is invalid, just give up here.
2216   if (Old->isInvalidDecl())
2217     return New->setInvalidDecl();
2218
2219   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2220     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2221     auto *NewTag = New->getAnonDeclWithTypedefName();
2222     NamedDecl *Hidden = nullptr;
2223     if (OldTag && NewTag &&
2224         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2225         !hasVisibleDefinition(OldTag, &Hidden)) {
2226       // There is a definition of this tag, but it is not visible. Use it
2227       // instead of our tag.
2228       New->setTypeForDecl(OldTD->getTypeForDecl());
2229       if (OldTD->isModed())
2230         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2231                                     OldTD->getUnderlyingType());
2232       else
2233         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2234
2235       // Make the old tag definition visible.
2236       makeMergedDefinitionVisible(Hidden);
2237
2238       // If this was an unscoped enumeration, yank all of its enumerators
2239       // out of the scope.
2240       if (isa<EnumDecl>(NewTag)) {
2241         Scope *EnumScope = getNonFieldDeclScope(S);
2242         for (auto *D : NewTag->decls()) {
2243           auto *ED = cast<EnumConstantDecl>(D);
2244           assert(EnumScope->isDeclScope(ED));
2245           EnumScope->RemoveDecl(ED);
2246           IdResolver.RemoveDecl(ED);
2247           ED->getLexicalDeclContext()->removeDecl(ED);
2248         }
2249       }
2250     }
2251   }
2252
2253   // If the typedef types are not identical, reject them in all languages and
2254   // with any extensions enabled.
2255   if (isIncompatibleTypedef(Old, New))
2256     return;
2257
2258   // The types match.  Link up the redeclaration chain and merge attributes if
2259   // the old declaration was a typedef.
2260   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2261     New->setPreviousDecl(Typedef);
2262     mergeDeclAttributes(New, Old);
2263   }
2264
2265   if (getLangOpts().MicrosoftExt)
2266     return;
2267
2268   if (getLangOpts().CPlusPlus) {
2269     // C++ [dcl.typedef]p2:
2270     //   In a given non-class scope, a typedef specifier can be used to
2271     //   redefine the name of any type declared in that scope to refer
2272     //   to the type to which it already refers.
2273     if (!isa<CXXRecordDecl>(CurContext))
2274       return;
2275
2276     // C++0x [dcl.typedef]p4:
2277     //   In a given class scope, a typedef specifier can be used to redefine
2278     //   any class-name declared in that scope that is not also a typedef-name
2279     //   to refer to the type to which it already refers.
2280     //
2281     // This wording came in via DR424, which was a correction to the
2282     // wording in DR56, which accidentally banned code like:
2283     //
2284     //   struct S {
2285     //     typedef struct A { } A;
2286     //   };
2287     //
2288     // in the C++03 standard. We implement the C++0x semantics, which
2289     // allow the above but disallow
2290     //
2291     //   struct S {
2292     //     typedef int I;
2293     //     typedef int I;
2294     //   };
2295     //
2296     // since that was the intent of DR56.
2297     if (!isa<TypedefNameDecl>(Old))
2298       return;
2299
2300     Diag(New->getLocation(), diag::err_redefinition)
2301       << New->getDeclName();
2302     notePreviousDefinition(Old, New->getLocation());
2303     return New->setInvalidDecl();
2304   }
2305
2306   // Modules always permit redefinition of typedefs, as does C11.
2307   if (getLangOpts().Modules || getLangOpts().C11)
2308     return;
2309
2310   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2311   // is normally mapped to an error, but can be controlled with
2312   // -Wtypedef-redefinition.  If either the original or the redefinition is
2313   // in a system header, don't emit this for compatibility with GCC.
2314   if (getDiagnostics().getSuppressSystemWarnings() &&
2315       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2316       (Old->isImplicit() ||
2317        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2318        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2319     return;
2320
2321   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2322     << New->getDeclName();
2323   notePreviousDefinition(Old, New->getLocation());
2324 }
2325
2326 /// DeclhasAttr - returns true if decl Declaration already has the target
2327 /// attribute.
2328 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2329   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2330   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2331   for (const auto *i : D->attrs())
2332     if (i->getKind() == A->getKind()) {
2333       if (Ann) {
2334         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2335           return true;
2336         continue;
2337       }
2338       // FIXME: Don't hardcode this check
2339       if (OA && isa<OwnershipAttr>(i))
2340         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2341       return true;
2342     }
2343
2344   return false;
2345 }
2346
2347 static bool isAttributeTargetADefinition(Decl *D) {
2348   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2349     return VD->isThisDeclarationADefinition();
2350   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2351     return TD->isCompleteDefinition() || TD->isBeingDefined();
2352   return true;
2353 }
2354
2355 /// Merge alignment attributes from \p Old to \p New, taking into account the
2356 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2357 ///
2358 /// \return \c true if any attributes were added to \p New.
2359 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2360   // Look for alignas attributes on Old, and pick out whichever attribute
2361   // specifies the strictest alignment requirement.
2362   AlignedAttr *OldAlignasAttr = nullptr;
2363   AlignedAttr *OldStrictestAlignAttr = nullptr;
2364   unsigned OldAlign = 0;
2365   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2366     // FIXME: We have no way of representing inherited dependent alignments
2367     // in a case like:
2368     //   template<int A, int B> struct alignas(A) X;
2369     //   template<int A, int B> struct alignas(B) X {};
2370     // For now, we just ignore any alignas attributes which are not on the
2371     // definition in such a case.
2372     if (I->isAlignmentDependent())
2373       return false;
2374
2375     if (I->isAlignas())
2376       OldAlignasAttr = I;
2377
2378     unsigned Align = I->getAlignment(S.Context);
2379     if (Align > OldAlign) {
2380       OldAlign = Align;
2381       OldStrictestAlignAttr = I;
2382     }
2383   }
2384
2385   // Look for alignas attributes on New.
2386   AlignedAttr *NewAlignasAttr = nullptr;
2387   unsigned NewAlign = 0;
2388   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2389     if (I->isAlignmentDependent())
2390       return false;
2391
2392     if (I->isAlignas())
2393       NewAlignasAttr = I;
2394
2395     unsigned Align = I->getAlignment(S.Context);
2396     if (Align > NewAlign)
2397       NewAlign = Align;
2398   }
2399
2400   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2401     // Both declarations have 'alignas' attributes. We require them to match.
2402     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2403     // fall short. (If two declarations both have alignas, they must both match
2404     // every definition, and so must match each other if there is a definition.)
2405
2406     // If either declaration only contains 'alignas(0)' specifiers, then it
2407     // specifies the natural alignment for the type.
2408     if (OldAlign == 0 || NewAlign == 0) {
2409       QualType Ty;
2410       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2411         Ty = VD->getType();
2412       else
2413         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2414
2415       if (OldAlign == 0)
2416         OldAlign = S.Context.getTypeAlign(Ty);
2417       if (NewAlign == 0)
2418         NewAlign = S.Context.getTypeAlign(Ty);
2419     }
2420
2421     if (OldAlign != NewAlign) {
2422       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2423         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2424         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2425       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2426     }
2427   }
2428
2429   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2430     // C++11 [dcl.align]p6:
2431     //   if any declaration of an entity has an alignment-specifier,
2432     //   every defining declaration of that entity shall specify an
2433     //   equivalent alignment.
2434     // C11 6.7.5/7:
2435     //   If the definition of an object does not have an alignment
2436     //   specifier, any other declaration of that object shall also
2437     //   have no alignment specifier.
2438     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2439       << OldAlignasAttr;
2440     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2441       << OldAlignasAttr;
2442   }
2443
2444   bool AnyAdded = false;
2445
2446   // Ensure we have an attribute representing the strictest alignment.
2447   if (OldAlign > NewAlign) {
2448     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2449     Clone->setInherited(true);
2450     New->addAttr(Clone);
2451     AnyAdded = true;
2452   }
2453
2454   // Ensure we have an alignas attribute if the old declaration had one.
2455   if (OldAlignasAttr && !NewAlignasAttr &&
2456       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2457     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2458     Clone->setInherited(true);
2459     New->addAttr(Clone);
2460     AnyAdded = true;
2461   }
2462
2463   return AnyAdded;
2464 }
2465
2466 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2467                                const InheritableAttr *Attr,
2468                                Sema::AvailabilityMergeKind AMK) {
2469   // This function copies an attribute Attr from a previous declaration to the
2470   // new declaration D if the new declaration doesn't itself have that attribute
2471   // yet or if that attribute allows duplicates.
2472   // If you're adding a new attribute that requires logic different from
2473   // "use explicit attribute on decl if present, else use attribute from
2474   // previous decl", for example if the attribute needs to be consistent
2475   // between redeclarations, you need to call a custom merge function here.
2476   InheritableAttr *NewAttr = nullptr;
2477   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2478   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2479     NewAttr = S.mergeAvailabilityAttr(
2480         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2481         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2482         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2483         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2484   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2485     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2486                                     AttrSpellingListIndex);
2487   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2488     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2489                                         AttrSpellingListIndex);
2490   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2491     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2492                                    AttrSpellingListIndex);
2493   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2494     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2495                                    AttrSpellingListIndex);
2496   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2497     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2498                                 FA->getFormatIdx(), FA->getFirstArg(),
2499                                 AttrSpellingListIndex);
2500   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2501     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2502                                  AttrSpellingListIndex);
2503   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2504     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2505                                  AttrSpellingListIndex);
2506   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2507     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2508                                        AttrSpellingListIndex,
2509                                        IA->getSemanticSpelling());
2510   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2511     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2512                                       &S.Context.Idents.get(AA->getSpelling()),
2513                                       AttrSpellingListIndex);
2514   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2515            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2516             isa<CUDAGlobalAttr>(Attr))) {
2517     // CUDA target attributes are part of function signature for
2518     // overloading purposes and must not be merged.
2519     return false;
2520   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2521     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2522   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2523     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2524   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2525     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2526   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2527     NewAttr = S.mergeCommonAttr(D, *CommonA);
2528   else if (isa<AlignedAttr>(Attr))
2529     // AlignedAttrs are handled separately, because we need to handle all
2530     // such attributes on a declaration at the same time.
2531     NewAttr = nullptr;
2532   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2533            (AMK == Sema::AMK_Override ||
2534             AMK == Sema::AMK_ProtocolImplementation))
2535     NewAttr = nullptr;
2536   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2537     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2538                               UA->getGuid());
2539   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2540     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2541   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2542     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2543   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2544     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2545
2546   if (NewAttr) {
2547     NewAttr->setInherited(true);
2548     D->addAttr(NewAttr);
2549     if (isa<MSInheritanceAttr>(NewAttr))
2550       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2551     return true;
2552   }
2553
2554   return false;
2555 }
2556
2557 static const NamedDecl *getDefinition(const Decl *D) {
2558   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2559     return TD->getDefinition();
2560   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2561     const VarDecl *Def = VD->getDefinition();
2562     if (Def)
2563       return Def;
2564     return VD->getActingDefinition();
2565   }
2566   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2567     return FD->getDefinition();
2568   return nullptr;
2569 }
2570
2571 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2572   for (const auto *Attribute : D->attrs())
2573     if (Attribute->getKind() == Kind)
2574       return true;
2575   return false;
2576 }
2577
2578 /// checkNewAttributesAfterDef - If we already have a definition, check that
2579 /// there are no new attributes in this declaration.
2580 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2581   if (!New->hasAttrs())
2582     return;
2583
2584   const NamedDecl *Def = getDefinition(Old);
2585   if (!Def || Def == New)
2586     return;
2587
2588   AttrVec &NewAttributes = New->getAttrs();
2589   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2590     const Attr *NewAttribute = NewAttributes[I];
2591
2592     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2593       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2594         Sema::SkipBodyInfo SkipBody;
2595         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2596
2597         // If we're skipping this definition, drop the "alias" attribute.
2598         if (SkipBody.ShouldSkip) {
2599           NewAttributes.erase(NewAttributes.begin() + I);
2600           --E;
2601           continue;
2602         }
2603       } else {
2604         VarDecl *VD = cast<VarDecl>(New);
2605         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2606                                 VarDecl::TentativeDefinition
2607                             ? diag::err_alias_after_tentative
2608                             : diag::err_redefinition;
2609         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2610         if (Diag == diag::err_redefinition)
2611           S.notePreviousDefinition(Def, VD->getLocation());
2612         else
2613           S.Diag(Def->getLocation(), diag::note_previous_definition);
2614         VD->setInvalidDecl();
2615       }
2616       ++I;
2617       continue;
2618     }
2619
2620     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2621       // Tentative definitions are only interesting for the alias check above.
2622       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2623         ++I;
2624         continue;
2625       }
2626     }
2627
2628     if (hasAttribute(Def, NewAttribute->getKind())) {
2629       ++I;
2630       continue; // regular attr merging will take care of validating this.
2631     }
2632
2633     if (isa<C11NoReturnAttr>(NewAttribute)) {
2634       // C's _Noreturn is allowed to be added to a function after it is defined.
2635       ++I;
2636       continue;
2637     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2638       if (AA->isAlignas()) {
2639         // C++11 [dcl.align]p6:
2640         //   if any declaration of an entity has an alignment-specifier,
2641         //   every defining declaration of that entity shall specify an
2642         //   equivalent alignment.
2643         // C11 6.7.5/7:
2644         //   If the definition of an object does not have an alignment
2645         //   specifier, any other declaration of that object shall also
2646         //   have no alignment specifier.
2647         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2648           << AA;
2649         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2650           << AA;
2651         NewAttributes.erase(NewAttributes.begin() + I);
2652         --E;
2653         continue;
2654       }
2655     }
2656
2657     S.Diag(NewAttribute->getLocation(),
2658            diag::warn_attribute_precede_definition);
2659     S.Diag(Def->getLocation(), diag::note_previous_definition);
2660     NewAttributes.erase(NewAttributes.begin() + I);
2661     --E;
2662   }
2663 }
2664
2665 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2666 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2667                                AvailabilityMergeKind AMK) {
2668   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2669     UsedAttr *NewAttr = OldAttr->clone(Context);
2670     NewAttr->setInherited(true);
2671     New->addAttr(NewAttr);
2672   }
2673
2674   if (!Old->hasAttrs() && !New->hasAttrs())
2675     return;
2676
2677   // Attributes declared post-definition are currently ignored.
2678   checkNewAttributesAfterDef(*this, New, Old);
2679
2680   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2681     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2682       if (OldA->getLabel() != NewA->getLabel()) {
2683         // This redeclaration changes __asm__ label.
2684         Diag(New->getLocation(), diag::err_different_asm_label);
2685         Diag(OldA->getLocation(), diag::note_previous_declaration);
2686       }
2687     } else if (Old->isUsed()) {
2688       // This redeclaration adds an __asm__ label to a declaration that has
2689       // already been ODR-used.
2690       Diag(New->getLocation(), diag::err_late_asm_label_name)
2691         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2692     }
2693   }
2694
2695   // Re-declaration cannot add abi_tag's.
2696   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2697     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2698       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2699         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2700                       NewTag) == OldAbiTagAttr->tags_end()) {
2701           Diag(NewAbiTagAttr->getLocation(),
2702                diag::err_new_abi_tag_on_redeclaration)
2703               << NewTag;
2704           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2705         }
2706       }
2707     } else {
2708       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2709       Diag(Old->getLocation(), diag::note_previous_declaration);
2710     }
2711   }
2712
2713   // This redeclaration adds a section attribute.
2714   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2715     if (auto *VD = dyn_cast<VarDecl>(New)) {
2716       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2717         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2718         Diag(Old->getLocation(), diag::note_previous_declaration);
2719       }
2720     }
2721   }
2722
2723   // Redeclaration adds code-seg attribute.
2724   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2725   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2726       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2727     Diag(New->getLocation(), diag::warn_mismatched_section)
2728          << 0 /*codeseg*/;
2729     Diag(Old->getLocation(), diag::note_previous_declaration);
2730   }
2731
2732   if (!Old->hasAttrs())
2733     return;
2734
2735   bool foundAny = New->hasAttrs();
2736
2737   // Ensure that any moving of objects within the allocated map is done before
2738   // we process them.
2739   if (!foundAny) New->setAttrs(AttrVec());
2740
2741   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2742     // Ignore deprecated/unavailable/availability attributes if requested.
2743     AvailabilityMergeKind LocalAMK = AMK_None;
2744     if (isa<DeprecatedAttr>(I) ||
2745         isa<UnavailableAttr>(I) ||
2746         isa<AvailabilityAttr>(I)) {
2747       switch (AMK) {
2748       case AMK_None:
2749         continue;
2750
2751       case AMK_Redeclaration:
2752       case AMK_Override:
2753       case AMK_ProtocolImplementation:
2754         LocalAMK = AMK;
2755         break;
2756       }
2757     }
2758
2759     // Already handled.
2760     if (isa<UsedAttr>(I))
2761       continue;
2762
2763     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2764       foundAny = true;
2765   }
2766
2767   if (mergeAlignedAttrs(*this, New, Old))
2768     foundAny = true;
2769
2770   if (!foundAny) New->dropAttrs();
2771 }
2772
2773 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2774 /// to the new one.
2775 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2776                                      const ParmVarDecl *oldDecl,
2777                                      Sema &S) {
2778   // C++11 [dcl.attr.depend]p2:
2779   //   The first declaration of a function shall specify the
2780   //   carries_dependency attribute for its declarator-id if any declaration
2781   //   of the function specifies the carries_dependency attribute.
2782   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2783   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2784     S.Diag(CDA->getLocation(),
2785            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2786     // Find the first declaration of the parameter.
2787     // FIXME: Should we build redeclaration chains for function parameters?
2788     const FunctionDecl *FirstFD =
2789       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2790     const ParmVarDecl *FirstVD =
2791       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2792     S.Diag(FirstVD->getLocation(),
2793            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2794   }
2795
2796   if (!oldDecl->hasAttrs())
2797     return;
2798
2799   bool foundAny = newDecl->hasAttrs();
2800
2801   // Ensure that any moving of objects within the allocated map is
2802   // done before we process them.
2803   if (!foundAny) newDecl->setAttrs(AttrVec());
2804
2805   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2806     if (!DeclHasAttr(newDecl, I)) {
2807       InheritableAttr *newAttr =
2808         cast<InheritableParamAttr>(I->clone(S.Context));
2809       newAttr->setInherited(true);
2810       newDecl->addAttr(newAttr);
2811       foundAny = true;
2812     }
2813   }
2814
2815   if (!foundAny) newDecl->dropAttrs();
2816 }
2817
2818 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2819                                 const ParmVarDecl *OldParam,
2820                                 Sema &S) {
2821   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2822     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2823       if (*Oldnullability != *Newnullability) {
2824         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2825           << DiagNullabilityKind(
2826                *Newnullability,
2827                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2828                 != 0))
2829           << DiagNullabilityKind(
2830                *Oldnullability,
2831                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2832                 != 0));
2833         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2834       }
2835     } else {
2836       QualType NewT = NewParam->getType();
2837       NewT = S.Context.getAttributedType(
2838                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2839                          NewT, NewT);
2840       NewParam->setType(NewT);
2841     }
2842   }
2843 }
2844
2845 namespace {
2846
2847 /// Used in MergeFunctionDecl to keep track of function parameters in
2848 /// C.
2849 struct GNUCompatibleParamWarning {
2850   ParmVarDecl *OldParm;
2851   ParmVarDecl *NewParm;
2852   QualType PromotedType;
2853 };
2854
2855 } // end anonymous namespace
2856
2857 /// getSpecialMember - get the special member enum for a method.
2858 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2859   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2860     if (Ctor->isDefaultConstructor())
2861       return Sema::CXXDefaultConstructor;
2862
2863     if (Ctor->isCopyConstructor())
2864       return Sema::CXXCopyConstructor;
2865
2866     if (Ctor->isMoveConstructor())
2867       return Sema::CXXMoveConstructor;
2868   } else if (isa<CXXDestructorDecl>(MD)) {
2869     return Sema::CXXDestructor;
2870   } else if (MD->isCopyAssignmentOperator()) {
2871     return Sema::CXXCopyAssignment;
2872   } else if (MD->isMoveAssignmentOperator()) {
2873     return Sema::CXXMoveAssignment;
2874   }
2875
2876   return Sema::CXXInvalid;
2877 }
2878
2879 // Determine whether the previous declaration was a definition, implicit
2880 // declaration, or a declaration.
2881 template <typename T>
2882 static std::pair<diag::kind, SourceLocation>
2883 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2884   diag::kind PrevDiag;
2885   SourceLocation OldLocation = Old->getLocation();
2886   if (Old->isThisDeclarationADefinition())
2887     PrevDiag = diag::note_previous_definition;
2888   else if (Old->isImplicit()) {
2889     PrevDiag = diag::note_previous_implicit_declaration;
2890     if (OldLocation.isInvalid())
2891       OldLocation = New->getLocation();
2892   } else
2893     PrevDiag = diag::note_previous_declaration;
2894   return std::make_pair(PrevDiag, OldLocation);
2895 }
2896
2897 /// canRedefineFunction - checks if a function can be redefined. Currently,
2898 /// only extern inline functions can be redefined, and even then only in
2899 /// GNU89 mode.
2900 static bool canRedefineFunction(const FunctionDecl *FD,
2901                                 const LangOptions& LangOpts) {
2902   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2903           !LangOpts.CPlusPlus &&
2904           FD->isInlineSpecified() &&
2905           FD->getStorageClass() == SC_Extern);
2906 }
2907
2908 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2909   const AttributedType *AT = T->getAs<AttributedType>();
2910   while (AT && !AT->isCallingConv())
2911     AT = AT->getModifiedType()->getAs<AttributedType>();
2912   return AT;
2913 }
2914
2915 template <typename T>
2916 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2917   const DeclContext *DC = Old->getDeclContext();
2918   if (DC->isRecord())
2919     return false;
2920
2921   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2922   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2923     return true;
2924   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2925     return true;
2926   return false;
2927 }
2928
2929 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2930 static bool isExternC(VarTemplateDecl *) { return false; }
2931
2932 /// Check whether a redeclaration of an entity introduced by a
2933 /// using-declaration is valid, given that we know it's not an overload
2934 /// (nor a hidden tag declaration).
2935 template<typename ExpectedDecl>
2936 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2937                                    ExpectedDecl *New) {
2938   // C++11 [basic.scope.declarative]p4:
2939   //   Given a set of declarations in a single declarative region, each of
2940   //   which specifies the same unqualified name,
2941   //   -- they shall all refer to the same entity, or all refer to functions
2942   //      and function templates; or
2943   //   -- exactly one declaration shall declare a class name or enumeration
2944   //      name that is not a typedef name and the other declarations shall all
2945   //      refer to the same variable or enumerator, or all refer to functions
2946   //      and function templates; in this case the class name or enumeration
2947   //      name is hidden (3.3.10).
2948
2949   // C++11 [namespace.udecl]p14:
2950   //   If a function declaration in namespace scope or block scope has the
2951   //   same name and the same parameter-type-list as a function introduced
2952   //   by a using-declaration, and the declarations do not declare the same
2953   //   function, the program is ill-formed.
2954
2955   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2956   if (Old &&
2957       !Old->getDeclContext()->getRedeclContext()->Equals(
2958           New->getDeclContext()->getRedeclContext()) &&
2959       !(isExternC(Old) && isExternC(New)))
2960     Old = nullptr;
2961
2962   if (!Old) {
2963     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2964     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2965     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2966     return true;
2967   }
2968   return false;
2969 }
2970
2971 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2972                                             const FunctionDecl *B) {
2973   assert(A->getNumParams() == B->getNumParams());
2974
2975   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2976     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2977     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2978     if (AttrA == AttrB)
2979       return true;
2980     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2981            AttrA->isDynamic() == AttrB->isDynamic();
2982   };
2983
2984   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2985 }
2986
2987 /// If necessary, adjust the semantic declaration context for a qualified
2988 /// declaration to name the correct inline namespace within the qualifier.
2989 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2990                                                DeclaratorDecl *OldD) {
2991   // The only case where we need to update the DeclContext is when
2992   // redeclaration lookup for a qualified name finds a declaration
2993   // in an inline namespace within the context named by the qualifier:
2994   //
2995   //   inline namespace N { int f(); }
2996   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2997   //
2998   // For unqualified declarations, the semantic context *can* change
2999   // along the redeclaration chain (for local extern declarations,
3000   // extern "C" declarations, and friend declarations in particular).
3001   if (!NewD->getQualifier())
3002     return;
3003
3004   // NewD is probably already in the right context.
3005   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3006   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3007   if (NamedDC->Equals(SemaDC))
3008     return;
3009
3010   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3011           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3012          "unexpected context for redeclaration");
3013
3014   auto *LexDC = NewD->getLexicalDeclContext();
3015   auto FixSemaDC = [=](NamedDecl *D) {
3016     if (!D)
3017       return;
3018     D->setDeclContext(SemaDC);
3019     D->setLexicalDeclContext(LexDC);
3020   };
3021
3022   FixSemaDC(NewD);
3023   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3024     FixSemaDC(FD->getDescribedFunctionTemplate());
3025   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3026     FixSemaDC(VD->getDescribedVarTemplate());
3027 }
3028
3029 /// MergeFunctionDecl - We just parsed a function 'New' from
3030 /// declarator D which has the same name and scope as a previous
3031 /// declaration 'Old'.  Figure out how to resolve this situation,
3032 /// merging decls or emitting diagnostics as appropriate.
3033 ///
3034 /// In C++, New and Old must be declarations that are not
3035 /// overloaded. Use IsOverload to determine whether New and Old are
3036 /// overloaded, and to select the Old declaration that New should be
3037 /// merged with.
3038 ///
3039 /// Returns true if there was an error, false otherwise.
3040 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3041                              Scope *S, bool MergeTypeWithOld) {
3042   // Verify the old decl was also a function.
3043   FunctionDecl *Old = OldD->getAsFunction();
3044   if (!Old) {
3045     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3046       if (New->getFriendObjectKind()) {
3047         Diag(New->getLocation(), diag::err_using_decl_friend);
3048         Diag(Shadow->getTargetDecl()->getLocation(),
3049              diag::note_using_decl_target);
3050         Diag(Shadow->getUsingDecl()->getLocation(),
3051              diag::note_using_decl) << 0;
3052         return true;
3053       }
3054
3055       // Check whether the two declarations might declare the same function.
3056       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3057         return true;
3058       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3059     } else {
3060       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3061         << New->getDeclName();
3062       notePreviousDefinition(OldD, New->getLocation());
3063       return true;
3064     }
3065   }
3066
3067   // If the old declaration is invalid, just give up here.
3068   if (Old->isInvalidDecl())
3069     return true;
3070
3071   // Disallow redeclaration of some builtins.
3072   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3073     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3074     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3075         << Old << Old->getType();
3076     return true;
3077   }
3078
3079   diag::kind PrevDiag;
3080   SourceLocation OldLocation;
3081   std::tie(PrevDiag, OldLocation) =
3082       getNoteDiagForInvalidRedeclaration(Old, New);
3083
3084   // Don't complain about this if we're in GNU89 mode and the old function
3085   // is an extern inline function.
3086   // Don't complain about specializations. They are not supposed to have
3087   // storage classes.
3088   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3089       New->getStorageClass() == SC_Static &&
3090       Old->hasExternalFormalLinkage() &&
3091       !New->getTemplateSpecializationInfo() &&
3092       !canRedefineFunction(Old, getLangOpts())) {
3093     if (getLangOpts().MicrosoftExt) {
3094       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3095       Diag(OldLocation, PrevDiag);
3096     } else {
3097       Diag(New->getLocation(), diag::err_static_non_static) << New;
3098       Diag(OldLocation, PrevDiag);
3099       return true;
3100     }
3101   }
3102
3103   if (New->hasAttr<InternalLinkageAttr>() &&
3104       !Old->hasAttr<InternalLinkageAttr>()) {
3105     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3106         << New->getDeclName();
3107     notePreviousDefinition(Old, New->getLocation());
3108     New->dropAttr<InternalLinkageAttr>();
3109   }
3110
3111   if (CheckRedeclarationModuleOwnership(New, Old))
3112     return true;
3113
3114   if (!getLangOpts().CPlusPlus) {
3115     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3116     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3117       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3118         << New << OldOvl;
3119
3120       // Try our best to find a decl that actually has the overloadable
3121       // attribute for the note. In most cases (e.g. programs with only one
3122       // broken declaration/definition), this won't matter.
3123       //
3124       // FIXME: We could do this if we juggled some extra state in
3125       // OverloadableAttr, rather than just removing it.
3126       const Decl *DiagOld = Old;
3127       if (OldOvl) {
3128         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3129           const auto *A = D->getAttr<OverloadableAttr>();
3130           return A && !A->isImplicit();
3131         });
3132         // If we've implicitly added *all* of the overloadable attrs to this
3133         // chain, emitting a "previous redecl" note is pointless.
3134         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3135       }
3136
3137       if (DiagOld)
3138         Diag(DiagOld->getLocation(),
3139              diag::note_attribute_overloadable_prev_overload)
3140           << OldOvl;
3141
3142       if (OldOvl)
3143         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3144       else
3145         New->dropAttr<OverloadableAttr>();
3146     }
3147   }
3148
3149   // If a function is first declared with a calling convention, but is later
3150   // declared or defined without one, all following decls assume the calling
3151   // convention of the first.
3152   //
3153   // It's OK if a function is first declared without a calling convention,
3154   // but is later declared or defined with the default calling convention.
3155   //
3156   // To test if either decl has an explicit calling convention, we look for
3157   // AttributedType sugar nodes on the type as written.  If they are missing or
3158   // were canonicalized away, we assume the calling convention was implicit.
3159   //
3160   // Note also that we DO NOT return at this point, because we still have
3161   // other tests to run.
3162   QualType OldQType = Context.getCanonicalType(Old->getType());
3163   QualType NewQType = Context.getCanonicalType(New->getType());
3164   const FunctionType *OldType = cast<FunctionType>(OldQType);
3165   const FunctionType *NewType = cast<FunctionType>(NewQType);
3166   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3167   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3168   bool RequiresAdjustment = false;
3169
3170   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3171     FunctionDecl *First = Old->getFirstDecl();
3172     const FunctionType *FT =
3173         First->getType().getCanonicalType()->castAs<FunctionType>();
3174     FunctionType::ExtInfo FI = FT->getExtInfo();
3175     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3176     if (!NewCCExplicit) {
3177       // Inherit the CC from the previous declaration if it was specified
3178       // there but not here.
3179       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3180       RequiresAdjustment = true;
3181     } else if (New->getBuiltinID()) {
3182       // Calling Conventions on a Builtin aren't really useful and setting a
3183       // default calling convention and cdecl'ing some builtin redeclarations is
3184       // common, so warn and ignore the calling convention on the redeclaration.
3185       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3186           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3187           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3188       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3189       RequiresAdjustment = true;
3190     } else {
3191       // Calling conventions aren't compatible, so complain.
3192       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3193       Diag(New->getLocation(), diag::err_cconv_change)
3194         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3195         << !FirstCCExplicit
3196         << (!FirstCCExplicit ? "" :
3197             FunctionType::getNameForCallConv(FI.getCC()));
3198
3199       // Put the note on the first decl, since it is the one that matters.
3200       Diag(First->getLocation(), diag::note_previous_declaration);
3201       return true;
3202     }
3203   }
3204
3205   // FIXME: diagnose the other way around?
3206   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3207     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3208     RequiresAdjustment = true;
3209   }
3210
3211   // Merge regparm attribute.
3212   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3213       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3214     if (NewTypeInfo.getHasRegParm()) {
3215       Diag(New->getLocation(), diag::err_regparm_mismatch)
3216         << NewType->getRegParmType()
3217         << OldType->getRegParmType();
3218       Diag(OldLocation, diag::note_previous_declaration);
3219       return true;
3220     }
3221
3222     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3223     RequiresAdjustment = true;
3224   }
3225
3226   // Merge ns_returns_retained attribute.
3227   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3228     if (NewTypeInfo.getProducesResult()) {
3229       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3230           << "'ns_returns_retained'";
3231       Diag(OldLocation, diag::note_previous_declaration);
3232       return true;
3233     }
3234
3235     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3236     RequiresAdjustment = true;
3237   }
3238
3239   if (OldTypeInfo.getNoCallerSavedRegs() !=
3240       NewTypeInfo.getNoCallerSavedRegs()) {
3241     if (NewTypeInfo.getNoCallerSavedRegs()) {
3242       AnyX86NoCallerSavedRegistersAttr *Attr =
3243         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3244       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3245       Diag(OldLocation, diag::note_previous_declaration);
3246       return true;
3247     }
3248
3249     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3250     RequiresAdjustment = true;
3251   }
3252
3253   if (RequiresAdjustment) {
3254     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3255     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3256     New->setType(QualType(AdjustedType, 0));
3257     NewQType = Context.getCanonicalType(New->getType());
3258   }
3259
3260   // If this redeclaration makes the function inline, we may need to add it to
3261   // UndefinedButUsed.
3262   if (!Old->isInlined() && New->isInlined() &&
3263       !New->hasAttr<GNUInlineAttr>() &&
3264       !getLangOpts().GNUInline &&
3265       Old->isUsed(false) &&
3266       !Old->isDefined() && !New->isThisDeclarationADefinition())
3267     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3268                                            SourceLocation()));
3269
3270   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3271   // about it.
3272   if (New->hasAttr<GNUInlineAttr>() &&
3273       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3274     UndefinedButUsed.erase(Old->getCanonicalDecl());
3275   }
3276
3277   // If pass_object_size params don't match up perfectly, this isn't a valid
3278   // redeclaration.
3279   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3280       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3281     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3282         << New->getDeclName();
3283     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3284     return true;
3285   }
3286
3287   if (getLangOpts().CPlusPlus) {
3288     // C++1z [over.load]p2
3289     //   Certain function declarations cannot be overloaded:
3290     //     -- Function declarations that differ only in the return type,
3291     //        the exception specification, or both cannot be overloaded.
3292
3293     // Check the exception specifications match. This may recompute the type of
3294     // both Old and New if it resolved exception specifications, so grab the
3295     // types again after this. Because this updates the type, we do this before
3296     // any of the other checks below, which may update the "de facto" NewQType
3297     // but do not necessarily update the type of New.
3298     if (CheckEquivalentExceptionSpec(Old, New))
3299       return true;
3300     OldQType = Context.getCanonicalType(Old->getType());
3301     NewQType = Context.getCanonicalType(New->getType());
3302
3303     // Go back to the type source info to compare the declared return types,
3304     // per C++1y [dcl.type.auto]p13:
3305     //   Redeclarations or specializations of a function or function template
3306     //   with a declared return type that uses a placeholder type shall also
3307     //   use that placeholder, not a deduced type.
3308     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3309     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3310     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3311         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3312                                        OldDeclaredReturnType)) {
3313       QualType ResQT;
3314       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3315           OldDeclaredReturnType->isObjCObjectPointerType())
3316         // FIXME: This does the wrong thing for a deduced return type.
3317         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3318       if (ResQT.isNull()) {
3319         if (New->isCXXClassMember() && New->isOutOfLine())
3320           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3321               << New << New->getReturnTypeSourceRange();
3322         else
3323           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3324               << New->getReturnTypeSourceRange();
3325         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3326                                     << Old->getReturnTypeSourceRange();
3327         return true;
3328       }
3329       else
3330         NewQType = ResQT;
3331     }
3332
3333     QualType OldReturnType = OldType->getReturnType();
3334     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3335     if (OldReturnType != NewReturnType) {
3336       // If this function has a deduced return type and has already been
3337       // defined, copy the deduced value from the old declaration.
3338       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3339       if (OldAT && OldAT->isDeduced()) {
3340         New->setType(
3341             SubstAutoType(New->getType(),
3342                           OldAT->isDependentType() ? Context.DependentTy
3343                                                    : OldAT->getDeducedType()));
3344         NewQType = Context.getCanonicalType(
3345             SubstAutoType(NewQType,
3346                           OldAT->isDependentType() ? Context.DependentTy
3347                                                    : OldAT->getDeducedType()));
3348       }
3349     }
3350
3351     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3352     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3353     if (OldMethod && NewMethod) {
3354       // Preserve triviality.
3355       NewMethod->setTrivial(OldMethod->isTrivial());
3356
3357       // MSVC allows explicit template specialization at class scope:
3358       // 2 CXXMethodDecls referring to the same function will be injected.
3359       // We don't want a redeclaration error.
3360       bool IsClassScopeExplicitSpecialization =
3361                               OldMethod->isFunctionTemplateSpecialization() &&
3362                               NewMethod->isFunctionTemplateSpecialization();
3363       bool isFriend = NewMethod->getFriendObjectKind();
3364
3365       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3366           !IsClassScopeExplicitSpecialization) {
3367         //    -- Member function declarations with the same name and the
3368         //       same parameter types cannot be overloaded if any of them
3369         //       is a static member function declaration.
3370         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3371           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3372           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3373           return true;
3374         }
3375
3376         // C++ [class.mem]p1:
3377         //   [...] A member shall not be declared twice in the
3378         //   member-specification, except that a nested class or member
3379         //   class template can be declared and then later defined.
3380         if (!inTemplateInstantiation()) {
3381           unsigned NewDiag;
3382           if (isa<CXXConstructorDecl>(OldMethod))
3383             NewDiag = diag::err_constructor_redeclared;
3384           else if (isa<CXXDestructorDecl>(NewMethod))
3385             NewDiag = diag::err_destructor_redeclared;
3386           else if (isa<CXXConversionDecl>(NewMethod))
3387             NewDiag = diag::err_conv_function_redeclared;
3388           else
3389             NewDiag = diag::err_member_redeclared;
3390
3391           Diag(New->getLocation(), NewDiag);
3392         } else {
3393           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3394             << New << New->getType();
3395         }
3396         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3397         return true;
3398
3399       // Complain if this is an explicit declaration of a special
3400       // member that was initially declared implicitly.
3401       //
3402       // As an exception, it's okay to befriend such methods in order
3403       // to permit the implicit constructor/destructor/operator calls.
3404       } else if (OldMethod->isImplicit()) {
3405         if (isFriend) {
3406           NewMethod->setImplicit();
3407         } else {
3408           Diag(NewMethod->getLocation(),
3409                diag::err_definition_of_implicitly_declared_member)
3410             << New << getSpecialMember(OldMethod);
3411           return true;
3412         }
3413       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3414         Diag(NewMethod->getLocation(),
3415              diag::err_definition_of_explicitly_defaulted_member)
3416           << getSpecialMember(OldMethod);
3417         return true;
3418       }
3419     }
3420
3421     // C++11 [dcl.attr.noreturn]p1:
3422     //   The first declaration of a function shall specify the noreturn
3423     //   attribute if any declaration of that function specifies the noreturn
3424     //   attribute.
3425     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3426     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3427       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3428       Diag(Old->getFirstDecl()->getLocation(),
3429            diag::note_noreturn_missing_first_decl);
3430     }
3431
3432     // C++11 [dcl.attr.depend]p2:
3433     //   The first declaration of a function shall specify the
3434     //   carries_dependency attribute for its declarator-id if any declaration
3435     //   of the function specifies the carries_dependency attribute.
3436     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3437     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3438       Diag(CDA->getLocation(),
3439            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3440       Diag(Old->getFirstDecl()->getLocation(),
3441            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3442     }
3443
3444     // (C++98 8.3.5p3):
3445     //   All declarations for a function shall agree exactly in both the
3446     //   return type and the parameter-type-list.
3447     // We also want to respect all the extended bits except noreturn.
3448
3449     // noreturn should now match unless the old type info didn't have it.
3450     QualType OldQTypeForComparison = OldQType;
3451     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3452       auto *OldType = OldQType->castAs<FunctionProtoType>();
3453       const FunctionType *OldTypeForComparison
3454         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3455       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3456       assert(OldQTypeForComparison.isCanonical());
3457     }
3458
3459     if (haveIncompatibleLanguageLinkages(Old, New)) {
3460       // As a special case, retain the language linkage from previous
3461       // declarations of a friend function as an extension.
3462       //
3463       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3464       // and is useful because there's otherwise no way to specify language
3465       // linkage within class scope.
3466       //
3467       // Check cautiously as the friend object kind isn't yet complete.
3468       if (New->getFriendObjectKind() != Decl::FOK_None) {
3469         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3470         Diag(OldLocation, PrevDiag);
3471       } else {
3472         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3473         Diag(OldLocation, PrevDiag);
3474         return true;
3475       }
3476     }
3477
3478     if (OldQTypeForComparison == NewQType)
3479       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3480
3481     // If the types are imprecise (due to dependent constructs in friends or
3482     // local extern declarations), it's OK if they differ. We'll check again
3483     // during instantiation.
3484     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3485       return false;
3486
3487     // Fall through for conflicting redeclarations and redefinitions.
3488   }
3489
3490   // C: Function types need to be compatible, not identical. This handles
3491   // duplicate function decls like "void f(int); void f(enum X);" properly.
3492   if (!getLangOpts().CPlusPlus &&
3493       Context.typesAreCompatible(OldQType, NewQType)) {
3494     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3495     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3496     const FunctionProtoType *OldProto = nullptr;
3497     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3498         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3499       // The old declaration provided a function prototype, but the
3500       // new declaration does not. Merge in the prototype.
3501       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3502       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3503       NewQType =
3504           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3505                                   OldProto->getExtProtoInfo());
3506       New->setType(NewQType);
3507       New->setHasInheritedPrototype();
3508
3509       // Synthesize parameters with the same types.
3510       SmallVector<ParmVarDecl*, 16> Params;
3511       for (const auto &ParamType : OldProto->param_types()) {
3512         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3513                                                  SourceLocation(), nullptr,
3514                                                  ParamType, /*TInfo=*/nullptr,
3515                                                  SC_None, nullptr);
3516         Param->setScopeInfo(0, Params.size());
3517         Param->setImplicit();
3518         Params.push_back(Param);
3519       }
3520
3521       New->setParams(Params);
3522     }
3523
3524     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3525   }
3526
3527   // GNU C permits a K&R definition to follow a prototype declaration
3528   // if the declared types of the parameters in the K&R definition
3529   // match the types in the prototype declaration, even when the
3530   // promoted types of the parameters from the K&R definition differ
3531   // from the types in the prototype. GCC then keeps the types from
3532   // the prototype.
3533   //
3534   // If a variadic prototype is followed by a non-variadic K&R definition,
3535   // the K&R definition becomes variadic.  This is sort of an edge case, but
3536   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3537   // C99 6.9.1p8.
3538   if (!getLangOpts().CPlusPlus &&
3539       Old->hasPrototype() && !New->hasPrototype() &&
3540       New->getType()->getAs<FunctionProtoType>() &&
3541       Old->getNumParams() == New->getNumParams()) {
3542     SmallVector<QualType, 16> ArgTypes;
3543     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3544     const FunctionProtoType *OldProto
3545       = Old->getType()->getAs<FunctionProtoType>();
3546     const FunctionProtoType *NewProto
3547       = New->getType()->getAs<FunctionProtoType>();
3548
3549     // Determine whether this is the GNU C extension.
3550     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3551                                                NewProto->getReturnType());
3552     bool LooseCompatible = !MergedReturn.isNull();
3553     for (unsigned Idx = 0, End = Old->getNumParams();
3554          LooseCompatible && Idx != End; ++Idx) {
3555       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3556       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3557       if (Context.typesAreCompatible(OldParm->getType(),
3558                                      NewProto->getParamType(Idx))) {
3559         ArgTypes.push_back(NewParm->getType());
3560       } else if (Context.typesAreCompatible(OldParm->getType(),
3561                                             NewParm->getType(),
3562                                             /*CompareUnqualified=*/true)) {
3563         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3564                                            NewProto->getParamType(Idx) };
3565         Warnings.push_back(Warn);
3566         ArgTypes.push_back(NewParm->getType());
3567       } else
3568         LooseCompatible = false;
3569     }
3570
3571     if (LooseCompatible) {
3572       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3573         Diag(Warnings[Warn].NewParm->getLocation(),
3574              diag::ext_param_promoted_not_compatible_with_prototype)
3575           << Warnings[Warn].PromotedType
3576           << Warnings[Warn].OldParm->getType();
3577         if (Warnings[Warn].OldParm->getLocation().isValid())
3578           Diag(Warnings[Warn].OldParm->getLocation(),
3579                diag::note_previous_declaration);
3580       }
3581
3582       if (MergeTypeWithOld)
3583         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3584                                              OldProto->getExtProtoInfo()));
3585       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3586     }
3587
3588     // Fall through to diagnose conflicting types.
3589   }
3590
3591   // A function that has already been declared has been redeclared or
3592   // defined with a different type; show an appropriate diagnostic.
3593
3594   // If the previous declaration was an implicitly-generated builtin
3595   // declaration, then at the very least we should use a specialized note.
3596   unsigned BuiltinID;
3597   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3598     // If it's actually a library-defined builtin function like 'malloc'
3599     // or 'printf', just warn about the incompatible redeclaration.
3600     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3601       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3602       Diag(OldLocation, diag::note_previous_builtin_declaration)
3603         << Old << Old->getType();
3604
3605       // If this is a global redeclaration, just forget hereafter
3606       // about the "builtin-ness" of the function.
3607       //
3608       // Doing this for local extern declarations is problematic.  If
3609       // the builtin declaration remains visible, a second invalid
3610       // local declaration will produce a hard error; if it doesn't
3611       // remain visible, a single bogus local redeclaration (which is
3612       // actually only a warning) could break all the downstream code.
3613       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3614         New->getIdentifier()->revertBuiltin();
3615
3616       return false;
3617     }
3618
3619     PrevDiag = diag::note_previous_builtin_declaration;
3620   }
3621
3622   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3623   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3624   return true;
3625 }
3626
3627 /// Completes the merge of two function declarations that are
3628 /// known to be compatible.
3629 ///
3630 /// This routine handles the merging of attributes and other
3631 /// properties of function declarations from the old declaration to
3632 /// the new declaration, once we know that New is in fact a
3633 /// redeclaration of Old.
3634 ///
3635 /// \returns false
3636 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3637                                         Scope *S, bool MergeTypeWithOld) {
3638   // Merge the attributes
3639   mergeDeclAttributes(New, Old);
3640
3641   // Merge "pure" flag.
3642   if (Old->isPure())
3643     New->setPure();
3644
3645   // Merge "used" flag.
3646   if (Old->getMostRecentDecl()->isUsed(false))
3647     New->setIsUsed();
3648
3649   // Merge attributes from the parameters.  These can mismatch with K&R
3650   // declarations.
3651   if (New->getNumParams() == Old->getNumParams())
3652       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3653         ParmVarDecl *NewParam = New->getParamDecl(i);
3654         ParmVarDecl *OldParam = Old->getParamDecl(i);
3655         mergeParamDeclAttributes(NewParam, OldParam, *this);
3656         mergeParamDeclTypes(NewParam, OldParam, *this);
3657       }
3658
3659   if (getLangOpts().CPlusPlus)
3660     return MergeCXXFunctionDecl(New, Old, S);
3661
3662   // Merge the function types so the we get the composite types for the return
3663   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3664   // was visible.
3665   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3666   if (!Merged.isNull() && MergeTypeWithOld)
3667     New->setType(Merged);
3668
3669   return false;
3670 }
3671
3672 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3673                                 ObjCMethodDecl *oldMethod) {
3674   // Merge the attributes, including deprecated/unavailable
3675   AvailabilityMergeKind MergeKind =
3676     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3677       ? AMK_ProtocolImplementation
3678       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3679                                                        : AMK_Override;
3680
3681   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3682
3683   // Merge attributes from the parameters.
3684   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3685                                        oe = oldMethod->param_end();
3686   for (ObjCMethodDecl::param_iterator
3687          ni = newMethod->param_begin(), ne = newMethod->param_end();
3688        ni != ne && oi != oe; ++ni, ++oi)
3689     mergeParamDeclAttributes(*ni, *oi, *this);
3690
3691   CheckObjCMethodOverride(newMethod, oldMethod);
3692 }
3693
3694 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3695   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3696
3697   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3698          ? diag::err_redefinition_different_type
3699          : diag::err_redeclaration_different_type)
3700     << New->getDeclName() << New->getType() << Old->getType();
3701
3702   diag::kind PrevDiag;
3703   SourceLocation OldLocation;
3704   std::tie(PrevDiag, OldLocation)
3705     = getNoteDiagForInvalidRedeclaration(Old, New);
3706   S.Diag(OldLocation, PrevDiag);
3707   New->setInvalidDecl();
3708 }
3709
3710 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3711 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3712 /// emitting diagnostics as appropriate.
3713 ///
3714 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3715 /// to here in AddInitializerToDecl. We can't check them before the initializer
3716 /// is attached.
3717 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3718                              bool MergeTypeWithOld) {
3719   if (New->isInvalidDecl() || Old->isInvalidDecl())
3720     return;
3721
3722   QualType MergedT;
3723   if (getLangOpts().CPlusPlus) {
3724     if (New->getType()->isUndeducedType()) {
3725       // We don't know what the new type is until the initializer is attached.
3726       return;
3727     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3728       // These could still be something that needs exception specs checked.
3729       return MergeVarDeclExceptionSpecs(New, Old);
3730     }
3731     // C++ [basic.link]p10:
3732     //   [...] the types specified by all declarations referring to a given
3733     //   object or function shall be identical, except that declarations for an
3734     //   array object can specify array types that differ by the presence or
3735     //   absence of a major array bound (8.3.4).
3736     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3737       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3738       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3739
3740       // We are merging a variable declaration New into Old. If it has an array
3741       // bound, and that bound differs from Old's bound, we should diagnose the
3742       // mismatch.
3743       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3744         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3745              PrevVD = PrevVD->getPreviousDecl()) {
3746           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3747           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3748             continue;
3749
3750           if (!Context.hasSameType(NewArray, PrevVDTy))
3751             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3752         }
3753       }
3754
3755       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3756         if (Context.hasSameType(OldArray->getElementType(),
3757                                 NewArray->getElementType()))
3758           MergedT = New->getType();
3759       }
3760       // FIXME: Check visibility. New is hidden but has a complete type. If New
3761       // has no array bound, it should not inherit one from Old, if Old is not
3762       // visible.
3763       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3764         if (Context.hasSameType(OldArray->getElementType(),
3765                                 NewArray->getElementType()))
3766           MergedT = Old->getType();
3767       }
3768     }
3769     else if (New->getType()->isObjCObjectPointerType() &&
3770                Old->getType()->isObjCObjectPointerType()) {
3771       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3772                                               Old->getType());
3773     }
3774   } else {
3775     // C 6.2.7p2:
3776     //   All declarations that refer to the same object or function shall have
3777     //   compatible type.
3778     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3779   }
3780   if (MergedT.isNull()) {
3781     // It's OK if we couldn't merge types if either type is dependent, for a
3782     // block-scope variable. In other cases (static data members of class
3783     // templates, variable templates, ...), we require the types to be
3784     // equivalent.
3785     // FIXME: The C++ standard doesn't say anything about this.
3786     if ((New->getType()->isDependentType() ||
3787          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3788       // If the old type was dependent, we can't merge with it, so the new type
3789       // becomes dependent for now. We'll reproduce the original type when we
3790       // instantiate the TypeSourceInfo for the variable.
3791       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3792         New->setType(Context.DependentTy);
3793       return;
3794     }
3795     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3796   }
3797
3798   // Don't actually update the type on the new declaration if the old
3799   // declaration was an extern declaration in a different scope.
3800   if (MergeTypeWithOld)
3801     New->setType(MergedT);
3802 }
3803
3804 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3805                                   LookupResult &Previous) {
3806   // C11 6.2.7p4:
3807   //   For an identifier with internal or external linkage declared
3808   //   in a scope in which a prior declaration of that identifier is
3809   //   visible, if the prior declaration specifies internal or
3810   //   external linkage, the type of the identifier at the later
3811   //   declaration becomes the composite type.
3812   //
3813   // If the variable isn't visible, we do not merge with its type.
3814   if (Previous.isShadowed())
3815     return false;
3816
3817   if (S.getLangOpts().CPlusPlus) {
3818     // C++11 [dcl.array]p3:
3819     //   If there is a preceding declaration of the entity in the same
3820     //   scope in which the bound was specified, an omitted array bound
3821     //   is taken to be the same as in that earlier declaration.
3822     return NewVD->isPreviousDeclInSameBlockScope() ||
3823            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3824             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3825   } else {
3826     // If the old declaration was function-local, don't merge with its
3827     // type unless we're in the same function.
3828     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3829            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3830   }
3831 }
3832
3833 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3834 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3835 /// situation, merging decls or emitting diagnostics as appropriate.
3836 ///
3837 /// Tentative definition rules (C99 6.9.2p2) are checked by
3838 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3839 /// definitions here, since the initializer hasn't been attached.
3840 ///
3841 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3842   // If the new decl is already invalid, don't do any other checking.
3843   if (New->isInvalidDecl())
3844     return;
3845
3846   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3847     return;
3848
3849   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3850
3851   // Verify the old decl was also a variable or variable template.
3852   VarDecl *Old = nullptr;
3853   VarTemplateDecl *OldTemplate = nullptr;
3854   if (Previous.isSingleResult()) {
3855     if (NewTemplate) {
3856       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3857       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3858
3859       if (auto *Shadow =
3860               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3861         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3862           return New->setInvalidDecl();
3863     } else {
3864       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3865
3866       if (auto *Shadow =
3867               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3868         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3869           return New->setInvalidDecl();
3870     }
3871   }
3872   if (!Old) {
3873     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3874         << New->getDeclName();
3875     notePreviousDefinition(Previous.getRepresentativeDecl(),
3876                            New->getLocation());
3877     return New->setInvalidDecl();
3878   }
3879
3880   // Ensure the template parameters are compatible.
3881   if (NewTemplate &&
3882       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3883                                       OldTemplate->getTemplateParameters(),
3884                                       /*Complain=*/true, TPL_TemplateMatch))
3885     return New->setInvalidDecl();
3886
3887   // C++ [class.mem]p1:
3888   //   A member shall not be declared twice in the member-specification [...]
3889   //
3890   // Here, we need only consider static data members.
3891   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3892     Diag(New->getLocation(), diag::err_duplicate_member)
3893       << New->getIdentifier();
3894     Diag(Old->getLocation(), diag::note_previous_declaration);
3895     New->setInvalidDecl();
3896   }
3897
3898   mergeDeclAttributes(New, Old);
3899   // Warn if an already-declared variable is made a weak_import in a subsequent
3900   // declaration
3901   if (New->hasAttr<WeakImportAttr>() &&
3902       Old->getStorageClass() == SC_None &&
3903       !Old->hasAttr<WeakImportAttr>()) {
3904     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3905     notePreviousDefinition(Old, New->getLocation());
3906     // Remove weak_import attribute on new declaration.
3907     New->dropAttr<WeakImportAttr>();
3908   }
3909
3910   if (New->hasAttr<InternalLinkageAttr>() &&
3911       !Old->hasAttr<InternalLinkageAttr>()) {
3912     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3913         << New->getDeclName();
3914     notePreviousDefinition(Old, New->getLocation());
3915     New->dropAttr<InternalLinkageAttr>();
3916   }
3917
3918   // Merge the types.
3919   VarDecl *MostRecent = Old->getMostRecentDecl();
3920   if (MostRecent != Old) {
3921     MergeVarDeclTypes(New, MostRecent,
3922                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3923     if (New->isInvalidDecl())
3924       return;
3925   }
3926
3927   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3928   if (New->isInvalidDecl())
3929     return;
3930
3931   diag::kind PrevDiag;
3932   SourceLocation OldLocation;
3933   std::tie(PrevDiag, OldLocation) =
3934       getNoteDiagForInvalidRedeclaration(Old, New);
3935
3936   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3937   if (New->getStorageClass() == SC_Static &&
3938       !New->isStaticDataMember() &&
3939       Old->hasExternalFormalLinkage()) {
3940     if (getLangOpts().MicrosoftExt) {
3941       Diag(New->getLocation(), diag::ext_static_non_static)
3942           << New->getDeclName();
3943       Diag(OldLocation, PrevDiag);
3944     } else {
3945       Diag(New->getLocation(), diag::err_static_non_static)
3946           << New->getDeclName();
3947       Diag(OldLocation, PrevDiag);
3948       return New->setInvalidDecl();
3949     }
3950   }
3951   // C99 6.2.2p4:
3952   //   For an identifier declared with the storage-class specifier
3953   //   extern in a scope in which a prior declaration of that
3954   //   identifier is visible,23) if the prior declaration specifies
3955   //   internal or external linkage, the linkage of the identifier at
3956   //   the later declaration is the same as the linkage specified at
3957   //   the prior declaration. If no prior declaration is visible, or
3958   //   if the prior declaration specifies no linkage, then the
3959   //   identifier has external linkage.
3960   if (New->hasExternalStorage() && Old->hasLinkage())
3961     /* Okay */;
3962   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3963            !New->isStaticDataMember() &&
3964            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3965     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3966     Diag(OldLocation, PrevDiag);
3967     return New->setInvalidDecl();
3968   }
3969
3970   // Check if extern is followed by non-extern and vice-versa.
3971   if (New->hasExternalStorage() &&
3972       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3973     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3974     Diag(OldLocation, PrevDiag);
3975     return New->setInvalidDecl();
3976   }
3977   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3978       !New->hasExternalStorage()) {
3979     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3980     Diag(OldLocation, PrevDiag);
3981     return New->setInvalidDecl();
3982   }
3983
3984   if (CheckRedeclarationModuleOwnership(New, Old))
3985     return;
3986
3987   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3988
3989   // FIXME: The test for external storage here seems wrong? We still
3990   // need to check for mismatches.
3991   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3992       // Don't complain about out-of-line definitions of static members.
3993       !(Old->getLexicalDeclContext()->isRecord() &&
3994         !New->getLexicalDeclContext()->isRecord())) {
3995     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3996     Diag(OldLocation, PrevDiag);
3997     return New->setInvalidDecl();
3998   }
3999
4000   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4001     if (VarDecl *Def = Old->getDefinition()) {
4002       // C++1z [dcl.fcn.spec]p4:
4003       //   If the definition of a variable appears in a translation unit before
4004       //   its first declaration as inline, the program is ill-formed.
4005       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4006       Diag(Def->getLocation(), diag::note_previous_definition);
4007     }
4008   }
4009
4010   // If this redeclaration makes the variable inline, we may need to add it to
4011   // UndefinedButUsed.
4012   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4013       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4014     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4015                                            SourceLocation()));
4016
4017   if (New->getTLSKind() != Old->getTLSKind()) {
4018     if (!Old->getTLSKind()) {
4019       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4020       Diag(OldLocation, PrevDiag);
4021     } else if (!New->getTLSKind()) {
4022       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4023       Diag(OldLocation, PrevDiag);
4024     } else {
4025       // Do not allow redeclaration to change the variable between requiring
4026       // static and dynamic initialization.
4027       // FIXME: GCC allows this, but uses the TLS keyword on the first
4028       // declaration to determine the kind. Do we need to be compatible here?
4029       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4030         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4031       Diag(OldLocation, PrevDiag);
4032     }
4033   }
4034
4035   // C++ doesn't have tentative definitions, so go right ahead and check here.
4036   if (getLangOpts().CPlusPlus &&
4037       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4038     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4039         Old->getCanonicalDecl()->isConstexpr()) {
4040       // This definition won't be a definition any more once it's been merged.
4041       Diag(New->getLocation(),
4042            diag::warn_deprecated_redundant_constexpr_static_def);
4043     } else if (VarDecl *Def = Old->getDefinition()) {
4044       if (checkVarDeclRedefinition(Def, New))
4045         return;
4046     }
4047   }
4048
4049   if (haveIncompatibleLanguageLinkages(Old, New)) {
4050     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4051     Diag(OldLocation, PrevDiag);
4052     New->setInvalidDecl();
4053     return;
4054   }
4055
4056   // Merge "used" flag.
4057   if (Old->getMostRecentDecl()->isUsed(false))
4058     New->setIsUsed();
4059
4060   // Keep a chain of previous declarations.
4061   New->setPreviousDecl(Old);
4062   if (NewTemplate)
4063     NewTemplate->setPreviousDecl(OldTemplate);
4064   adjustDeclContextForDeclaratorDecl(New, Old);
4065
4066   // Inherit access appropriately.
4067   New->setAccess(Old->getAccess());
4068   if (NewTemplate)
4069     NewTemplate->setAccess(New->getAccess());
4070
4071   if (Old->isInline())
4072     New->setImplicitlyInline();
4073 }
4074
4075 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4076   SourceManager &SrcMgr = getSourceManager();
4077   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4078   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4079   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4080   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4081   auto &HSI = PP.getHeaderSearchInfo();
4082   StringRef HdrFilename =
4083       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4084
4085   auto noteFromModuleOrInclude = [&](Module *Mod,
4086                                      SourceLocation IncLoc) -> bool {
4087     // Redefinition errors with modules are common with non modular mapped
4088     // headers, example: a non-modular header H in module A that also gets
4089     // included directly in a TU. Pointing twice to the same header/definition
4090     // is confusing, try to get better diagnostics when modules is on.
4091     if (IncLoc.isValid()) {
4092       if (Mod) {
4093         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4094             << HdrFilename.str() << Mod->getFullModuleName();
4095         if (!Mod->DefinitionLoc.isInvalid())
4096           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4097               << Mod->getFullModuleName();
4098       } else {
4099         Diag(IncLoc, diag::note_redefinition_include_same_file)
4100             << HdrFilename.str();
4101       }
4102       return true;
4103     }
4104
4105     return false;
4106   };
4107
4108   // Is it the same file and same offset? Provide more information on why
4109   // this leads to a redefinition error.
4110   bool EmittedDiag = false;
4111   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4112     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4113     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4114     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4115     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4116
4117     // If the header has no guards, emit a note suggesting one.
4118     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4119       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4120
4121     if (EmittedDiag)
4122       return;
4123   }
4124
4125   // Redefinition coming from different files or couldn't do better above.
4126   if (Old->getLocation().isValid())
4127     Diag(Old->getLocation(), diag::note_previous_definition);
4128 }
4129
4130 /// We've just determined that \p Old and \p New both appear to be definitions
4131 /// of the same variable. Either diagnose or fix the problem.
4132 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4133   if (!hasVisibleDefinition(Old) &&
4134       (New->getFormalLinkage() == InternalLinkage ||
4135        New->isInline() ||
4136        New->getDescribedVarTemplate() ||
4137        New->getNumTemplateParameterLists() ||
4138        New->getDeclContext()->isDependentContext())) {
4139     // The previous definition is hidden, and multiple definitions are
4140     // permitted (in separate TUs). Demote this to a declaration.
4141     New->demoteThisDefinitionToDeclaration();
4142
4143     // Make the canonical definition visible.
4144     if (auto *OldTD = Old->getDescribedVarTemplate())
4145       makeMergedDefinitionVisible(OldTD);
4146     makeMergedDefinitionVisible(Old);
4147     return false;
4148   } else {
4149     Diag(New->getLocation(), diag::err_redefinition) << New;
4150     notePreviousDefinition(Old, New->getLocation());
4151     New->setInvalidDecl();
4152     return true;
4153   }
4154 }
4155
4156 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4157 /// no declarator (e.g. "struct foo;") is parsed.
4158 Decl *
4159 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4160                                  RecordDecl *&AnonRecord) {
4161   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4162                                     AnonRecord);
4163 }
4164
4165 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4166 // disambiguate entities defined in different scopes.
4167 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4168 // compatibility.
4169 // We will pick our mangling number depending on which version of MSVC is being
4170 // targeted.
4171 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4172   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4173              ? S->getMSCurManglingNumber()
4174              : S->getMSLastManglingNumber();
4175 }
4176
4177 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4178   if (!Context.getLangOpts().CPlusPlus)
4179     return;
4180
4181   if (isa<CXXRecordDecl>(Tag->getParent())) {
4182     // If this tag is the direct child of a class, number it if
4183     // it is anonymous.
4184     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4185       return;
4186     MangleNumberingContext &MCtx =
4187         Context.getManglingNumberContext(Tag->getParent());
4188     Context.setManglingNumber(
4189         Tag, MCtx.getManglingNumber(
4190                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4191     return;
4192   }
4193
4194   // If this tag isn't a direct child of a class, number it if it is local.
4195   Decl *ManglingContextDecl;
4196   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4197           Tag->getDeclContext(), ManglingContextDecl)) {
4198     Context.setManglingNumber(
4199         Tag, MCtx->getManglingNumber(
4200                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4201   }
4202 }
4203
4204 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4205                                         TypedefNameDecl *NewTD) {
4206   if (TagFromDeclSpec->isInvalidDecl())
4207     return;
4208
4209   // Do nothing if the tag already has a name for linkage purposes.
4210   if (TagFromDeclSpec->hasNameForLinkage())
4211     return;
4212
4213   // A well-formed anonymous tag must always be a TUK_Definition.
4214   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4215
4216   // The type must match the tag exactly;  no qualifiers allowed.
4217   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4218                            Context.getTagDeclType(TagFromDeclSpec))) {
4219     if (getLangOpts().CPlusPlus)
4220       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4221     return;
4222   }
4223
4224   // If we've already computed linkage for the anonymous tag, then
4225   // adding a typedef name for the anonymous decl can change that
4226   // linkage, which might be a serious problem.  Diagnose this as
4227   // unsupported and ignore the typedef name.  TODO: we should
4228   // pursue this as a language defect and establish a formal rule
4229   // for how to handle it.
4230   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4231     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4232
4233     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4234     tagLoc = getLocForEndOfToken(tagLoc);
4235
4236     llvm::SmallString<40> textToInsert;
4237     textToInsert += ' ';
4238     textToInsert += NewTD->getIdentifier()->getName();
4239     Diag(tagLoc, diag::note_typedef_changes_linkage)
4240         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4241     return;
4242   }
4243
4244   // Otherwise, set this is the anon-decl typedef for the tag.
4245   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4246 }
4247
4248 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4249   switch (T) {
4250   case DeclSpec::TST_class:
4251     return 0;
4252   case DeclSpec::TST_struct:
4253     return 1;
4254   case DeclSpec::TST_interface:
4255     return 2;
4256   case DeclSpec::TST_union:
4257     return 3;
4258   case DeclSpec::TST_enum:
4259     return 4;
4260   default:
4261     llvm_unreachable("unexpected type specifier");
4262   }
4263 }
4264
4265 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4266 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4267 /// parameters to cope with template friend declarations.
4268 Decl *
4269 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4270                                  MultiTemplateParamsArg TemplateParams,
4271                                  bool IsExplicitInstantiation,
4272                                  RecordDecl *&AnonRecord) {
4273   Decl *TagD = nullptr;
4274   TagDecl *Tag = nullptr;
4275   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4276       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4277       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4278       DS.getTypeSpecType() == DeclSpec::TST_union ||
4279       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4280     TagD = DS.getRepAsDecl();
4281
4282     if (!TagD) // We probably had an error
4283       return nullptr;
4284
4285     // Note that the above type specs guarantee that the
4286     // type rep is a Decl, whereas in many of the others
4287     // it's a Type.
4288     if (isa<TagDecl>(TagD))
4289       Tag = cast<TagDecl>(TagD);
4290     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4291       Tag = CTD->getTemplatedDecl();
4292   }
4293
4294   if (Tag) {
4295     handleTagNumbering(Tag, S);
4296     Tag->setFreeStanding();
4297     if (Tag->isInvalidDecl())
4298       return Tag;
4299   }
4300
4301   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4302     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4303     // or incomplete types shall not be restrict-qualified."
4304     if (TypeQuals & DeclSpec::TQ_restrict)
4305       Diag(DS.getRestrictSpecLoc(),
4306            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4307            << DS.getSourceRange();
4308   }
4309
4310   if (DS.isInlineSpecified())
4311     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4312         << getLangOpts().CPlusPlus17;
4313
4314   if (DS.hasConstexprSpecifier()) {
4315     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4316     // and definitions of functions and variables.
4317     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4318     // the declaration of a function or function template
4319     bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
4320     if (Tag)
4321       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4322           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
4323     else
4324       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4325           << IsConsteval;
4326     // Don't emit warnings after this error.
4327     return TagD;
4328   }
4329
4330   DiagnoseFunctionSpecifiers(DS);
4331
4332   if (DS.isFriendSpecified()) {
4333     // If we're dealing with a decl but not a TagDecl, assume that
4334     // whatever routines created it handled the friendship aspect.
4335     if (TagD && !Tag)
4336       return nullptr;
4337     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4338   }
4339
4340   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4341   bool IsExplicitSpecialization =
4342     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4343   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4344       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4345       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4346     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4347     // nested-name-specifier unless it is an explicit instantiation
4348     // or an explicit specialization.
4349     //
4350     // FIXME: We allow class template partial specializations here too, per the
4351     // obvious intent of DR1819.
4352     //
4353     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4354     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4355         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4356     return nullptr;
4357   }
4358
4359   // Track whether this decl-specifier declares anything.
4360   bool DeclaresAnything = true;
4361
4362   // Handle anonymous struct definitions.
4363   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4364     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4365         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4366       if (getLangOpts().CPlusPlus ||
4367           Record->getDeclContext()->isRecord()) {
4368         // If CurContext is a DeclContext that can contain statements,
4369         // RecursiveASTVisitor won't visit the decls that
4370         // BuildAnonymousStructOrUnion() will put into CurContext.
4371         // Also store them here so that they can be part of the
4372         // DeclStmt that gets created in this case.
4373         // FIXME: Also return the IndirectFieldDecls created by
4374         // BuildAnonymousStructOr union, for the same reason?
4375         if (CurContext->isFunctionOrMethod())
4376           AnonRecord = Record;
4377         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4378                                            Context.getPrintingPolicy());
4379       }
4380
4381       DeclaresAnything = false;
4382     }
4383   }
4384
4385   // C11 6.7.2.1p2:
4386   //   A struct-declaration that does not declare an anonymous structure or
4387   //   anonymous union shall contain a struct-declarator-list.
4388   //
4389   // This rule also existed in C89 and C99; the grammar for struct-declaration
4390   // did not permit a struct-declaration without a struct-declarator-list.
4391   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4392       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4393     // Check for Microsoft C extension: anonymous struct/union member.
4394     // Handle 2 kinds of anonymous struct/union:
4395     //   struct STRUCT;
4396     //   union UNION;
4397     // and
4398     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4399     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4400     if ((Tag && Tag->getDeclName()) ||
4401         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4402       RecordDecl *Record = nullptr;
4403       if (Tag)
4404         Record = dyn_cast<RecordDecl>(Tag);
4405       else if (const RecordType *RT =
4406                    DS.getRepAsType().get()->getAsStructureType())
4407         Record = RT->getDecl();
4408       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4409         Record = UT->getDecl();
4410
4411       if (Record && getLangOpts().MicrosoftExt) {
4412         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4413             << Record->isUnion() << DS.getSourceRange();
4414         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4415       }
4416
4417       DeclaresAnything = false;
4418     }
4419   }
4420
4421   // Skip all the checks below if we have a type error.
4422   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4423       (TagD && TagD->isInvalidDecl()))
4424     return TagD;
4425
4426   if (getLangOpts().CPlusPlus &&
4427       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4428     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4429       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4430           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4431         DeclaresAnything = false;
4432
4433   if (!DS.isMissingDeclaratorOk()) {
4434     // Customize diagnostic for a typedef missing a name.
4435     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4436       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4437           << DS.getSourceRange();
4438     else
4439       DeclaresAnything = false;
4440   }
4441
4442   if (DS.isModulePrivateSpecified() &&
4443       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4444     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4445       << Tag->getTagKind()
4446       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4447
4448   ActOnDocumentableDecl(TagD);
4449
4450   // C 6.7/2:
4451   //   A declaration [...] shall declare at least a declarator [...], a tag,
4452   //   or the members of an enumeration.
4453   // C++ [dcl.dcl]p3:
4454   //   [If there are no declarators], and except for the declaration of an
4455   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4456   //   names into the program, or shall redeclare a name introduced by a
4457   //   previous declaration.
4458   if (!DeclaresAnything) {
4459     // In C, we allow this as a (popular) extension / bug. Don't bother
4460     // producing further diagnostics for redundant qualifiers after this.
4461     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4462     return TagD;
4463   }
4464
4465   // C++ [dcl.stc]p1:
4466   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4467   //   init-declarator-list of the declaration shall not be empty.
4468   // C++ [dcl.fct.spec]p1:
4469   //   If a cv-qualifier appears in a decl-specifier-seq, the
4470   //   init-declarator-list of the declaration shall not be empty.
4471   //
4472   // Spurious qualifiers here appear to be valid in C.
4473   unsigned DiagID = diag::warn_standalone_specifier;
4474   if (getLangOpts().CPlusPlus)
4475     DiagID = diag::ext_standalone_specifier;
4476
4477   // Note that a linkage-specification sets a storage class, but
4478   // 'extern "C" struct foo;' is actually valid and not theoretically
4479   // useless.
4480   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4481     if (SCS == DeclSpec::SCS_mutable)
4482       // Since mutable is not a viable storage class specifier in C, there is
4483       // no reason to treat it as an extension. Instead, diagnose as an error.
4484       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4485     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4486       Diag(DS.getStorageClassSpecLoc(), DiagID)
4487         << DeclSpec::getSpecifierName(SCS);
4488   }
4489
4490   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4491     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4492       << DeclSpec::getSpecifierName(TSCS);
4493   if (DS.getTypeQualifiers()) {
4494     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4495       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4496     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4497       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4498     // Restrict is covered above.
4499     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4500       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4501     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4502       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4503   }
4504
4505   // Warn about ignored type attributes, for example:
4506   // __attribute__((aligned)) struct A;
4507   // Attributes should be placed after tag to apply to type declaration.
4508   if (!DS.getAttributes().empty()) {
4509     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4510     if (TypeSpecType == DeclSpec::TST_class ||
4511         TypeSpecType == DeclSpec::TST_struct ||
4512         TypeSpecType == DeclSpec::TST_interface ||
4513         TypeSpecType == DeclSpec::TST_union ||
4514         TypeSpecType == DeclSpec::TST_enum) {
4515       for (const ParsedAttr &AL : DS.getAttributes())
4516         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4517             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4518     }
4519   }
4520
4521   return TagD;
4522 }
4523
4524 /// We are trying to inject an anonymous member into the given scope;
4525 /// check if there's an existing declaration that can't be overloaded.
4526 ///
4527 /// \return true if this is a forbidden redeclaration
4528 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4529                                          Scope *S,
4530                                          DeclContext *Owner,
4531                                          DeclarationName Name,
4532                                          SourceLocation NameLoc,
4533                                          bool IsUnion) {
4534   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4535                  Sema::ForVisibleRedeclaration);
4536   if (!SemaRef.LookupName(R, S)) return false;
4537
4538   // Pick a representative declaration.
4539   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4540   assert(PrevDecl && "Expected a non-null Decl");
4541
4542   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4543     return false;
4544
4545   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4546     << IsUnion << Name;
4547   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4548
4549   return true;
4550 }
4551
4552 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4553 /// anonymous struct or union AnonRecord into the owning context Owner
4554 /// and scope S. This routine will be invoked just after we realize
4555 /// that an unnamed union or struct is actually an anonymous union or
4556 /// struct, e.g.,
4557 ///
4558 /// @code
4559 /// union {
4560 ///   int i;
4561 ///   float f;
4562 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4563 ///    // f into the surrounding scope.x
4564 /// @endcode
4565 ///
4566 /// This routine is recursive, injecting the names of nested anonymous
4567 /// structs/unions into the owning context and scope as well.
4568 static bool
4569 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4570                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4571                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4572   bool Invalid = false;
4573
4574   // Look every FieldDecl and IndirectFieldDecl with a name.
4575   for (auto *D : AnonRecord->decls()) {
4576     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4577         cast<NamedDecl>(D)->getDeclName()) {
4578       ValueDecl *VD = cast<ValueDecl>(D);
4579       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4580                                        VD->getLocation(),
4581                                        AnonRecord->isUnion())) {
4582         // C++ [class.union]p2:
4583         //   The names of the members of an anonymous union shall be
4584         //   distinct from the names of any other entity in the
4585         //   scope in which the anonymous union is declared.
4586         Invalid = true;
4587       } else {
4588         // C++ [class.union]p2:
4589         //   For the purpose of name lookup, after the anonymous union
4590         //   definition, the members of the anonymous union are
4591         //   considered to have been defined in the scope in which the
4592         //   anonymous union is declared.
4593         unsigned OldChainingSize = Chaining.size();
4594         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4595           Chaining.append(IF->chain_begin(), IF->chain_end());
4596         else
4597           Chaining.push_back(VD);
4598
4599         assert(Chaining.size() >= 2);
4600         NamedDecl **NamedChain =
4601           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4602         for (unsigned i = 0; i < Chaining.size(); i++)
4603           NamedChain[i] = Chaining[i];
4604
4605         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4606             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4607             VD->getType(), {NamedChain, Chaining.size()});
4608
4609         for (const auto *Attr : VD->attrs())
4610           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4611
4612         IndirectField->setAccess(AS);
4613         IndirectField->setImplicit();
4614         SemaRef.PushOnScopeChains(IndirectField, S);
4615
4616         // That includes picking up the appropriate access specifier.
4617         if (AS != AS_none) IndirectField->setAccess(AS);
4618
4619         Chaining.resize(OldChainingSize);
4620       }
4621     }
4622   }
4623
4624   return Invalid;
4625 }
4626
4627 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4628 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4629 /// illegal input values are mapped to SC_None.
4630 static StorageClass
4631 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4632   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4633   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4634          "Parser allowed 'typedef' as storage class VarDecl.");
4635   switch (StorageClassSpec) {
4636   case DeclSpec::SCS_unspecified:    return SC_None;
4637   case DeclSpec::SCS_extern:
4638     if (DS.isExternInLinkageSpec())
4639       return SC_None;
4640     return SC_Extern;
4641   case DeclSpec::SCS_static:         return SC_Static;
4642   case DeclSpec::SCS_auto:           return SC_Auto;
4643   case DeclSpec::SCS_register:       return SC_Register;
4644   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4645     // Illegal SCSs map to None: error reporting is up to the caller.
4646   case DeclSpec::SCS_mutable:        // Fall through.
4647   case DeclSpec::SCS_typedef:        return SC_None;
4648   }
4649   llvm_unreachable("unknown storage class specifier");
4650 }
4651
4652 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4653   assert(Record->hasInClassInitializer());
4654
4655   for (const auto *I : Record->decls()) {
4656     const auto *FD = dyn_cast<FieldDecl>(I);
4657     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4658       FD = IFD->getAnonField();
4659     if (FD && FD->hasInClassInitializer())
4660       return FD->getLocation();
4661   }
4662
4663   llvm_unreachable("couldn't find in-class initializer");
4664 }
4665
4666 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4667                                       SourceLocation DefaultInitLoc) {
4668   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4669     return;
4670
4671   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4672   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4673 }
4674
4675 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4676                                       CXXRecordDecl *AnonUnion) {
4677   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4678     return;
4679
4680   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4681 }
4682
4683 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4684 /// anonymous structure or union. Anonymous unions are a C++ feature
4685 /// (C++ [class.union]) and a C11 feature; anonymous structures
4686 /// are a C11 feature and GNU C++ extension.
4687 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4688                                         AccessSpecifier AS,
4689                                         RecordDecl *Record,
4690                                         const PrintingPolicy &Policy) {
4691   DeclContext *Owner = Record->getDeclContext();
4692
4693   // Diagnose whether this anonymous struct/union is an extension.
4694   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4695     Diag(Record->getLocation(), diag::ext_anonymous_union);
4696   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4697     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4698   else if (!Record->isUnion() && !getLangOpts().C11)
4699     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4700
4701   // C and C++ require different kinds of checks for anonymous
4702   // structs/unions.
4703   bool Invalid = false;
4704   if (getLangOpts().CPlusPlus) {
4705     const char *PrevSpec = nullptr;
4706     unsigned DiagID;
4707     if (Record->isUnion()) {
4708       // C++ [class.union]p6:
4709       // C++17 [class.union.anon]p2:
4710       //   Anonymous unions declared in a named namespace or in the
4711       //   global namespace shall be declared static.
4712       DeclContext *OwnerScope = Owner->getRedeclContext();
4713       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4714           (OwnerScope->isTranslationUnit() ||
4715            (OwnerScope->isNamespace() &&
4716             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4717         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4718           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4719
4720         // Recover by adding 'static'.
4721         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4722                                PrevSpec, DiagID, Policy);
4723       }
4724       // C++ [class.union]p6:
4725       //   A storage class is not allowed in a declaration of an
4726       //   anonymous union in a class scope.
4727       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4728                isa<RecordDecl>(Owner)) {
4729         Diag(DS.getStorageClassSpecLoc(),
4730              diag::err_anonymous_union_with_storage_spec)
4731           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4732
4733         // Recover by removing the storage specifier.
4734         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4735                                SourceLocation(),
4736                                PrevSpec, DiagID, Context.getPrintingPolicy());
4737       }
4738     }
4739
4740     // Ignore const/volatile/restrict qualifiers.
4741     if (DS.getTypeQualifiers()) {
4742       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4743         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4744           << Record->isUnion() << "const"
4745           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4746       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4747         Diag(DS.getVolatileSpecLoc(),
4748              diag::ext_anonymous_struct_union_qualified)
4749           << Record->isUnion() << "volatile"
4750           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4751       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4752         Diag(DS.getRestrictSpecLoc(),
4753              diag::ext_anonymous_struct_union_qualified)
4754           << Record->isUnion() << "restrict"
4755           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4756       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4757         Diag(DS.getAtomicSpecLoc(),
4758              diag::ext_anonymous_struct_union_qualified)
4759           << Record->isUnion() << "_Atomic"
4760           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4761       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4762         Diag(DS.getUnalignedSpecLoc(),
4763              diag::ext_anonymous_struct_union_qualified)
4764           << Record->isUnion() << "__unaligned"
4765           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4766
4767       DS.ClearTypeQualifiers();
4768     }
4769
4770     // C++ [class.union]p2:
4771     //   The member-specification of an anonymous union shall only
4772     //   define non-static data members. [Note: nested types and
4773     //   functions cannot be declared within an anonymous union. ]
4774     for (auto *Mem : Record->decls()) {
4775       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4776         // C++ [class.union]p3:
4777         //   An anonymous union shall not have private or protected
4778         //   members (clause 11).
4779         assert(FD->getAccess() != AS_none);
4780         if (FD->getAccess() != AS_public) {
4781           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4782             << Record->isUnion() << (FD->getAccess() == AS_protected);
4783           Invalid = true;
4784         }
4785
4786         // C++ [class.union]p1
4787         //   An object of a class with a non-trivial constructor, a non-trivial
4788         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4789         //   assignment operator cannot be a member of a union, nor can an
4790         //   array of such objects.
4791         if (CheckNontrivialField(FD))
4792           Invalid = true;
4793       } else if (Mem->isImplicit()) {
4794         // Any implicit members are fine.
4795       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4796         // This is a type that showed up in an
4797         // elaborated-type-specifier inside the anonymous struct or
4798         // union, but which actually declares a type outside of the
4799         // anonymous struct or union. It's okay.
4800       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4801         if (!MemRecord->isAnonymousStructOrUnion() &&
4802             MemRecord->getDeclName()) {
4803           // Visual C++ allows type definition in anonymous struct or union.
4804           if (getLangOpts().MicrosoftExt)
4805             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4806               << Record->isUnion();
4807           else {
4808             // This is a nested type declaration.
4809             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4810               << Record->isUnion();
4811             Invalid = true;
4812           }
4813         } else {
4814           // This is an anonymous type definition within another anonymous type.
4815           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4816           // not part of standard C++.
4817           Diag(MemRecord->getLocation(),
4818                diag::ext_anonymous_record_with_anonymous_type)
4819             << Record->isUnion();
4820         }
4821       } else if (isa<AccessSpecDecl>(Mem)) {
4822         // Any access specifier is fine.
4823       } else if (isa<StaticAssertDecl>(Mem)) {
4824         // In C++1z, static_assert declarations are also fine.
4825       } else {
4826         // We have something that isn't a non-static data
4827         // member. Complain about it.
4828         unsigned DK = diag::err_anonymous_record_bad_member;
4829         if (isa<TypeDecl>(Mem))
4830           DK = diag::err_anonymous_record_with_type;
4831         else if (isa<FunctionDecl>(Mem))
4832           DK = diag::err_anonymous_record_with_function;
4833         else if (isa<VarDecl>(Mem))
4834           DK = diag::err_anonymous_record_with_static;
4835
4836         // Visual C++ allows type definition in anonymous struct or union.
4837         if (getLangOpts().MicrosoftExt &&
4838             DK == diag::err_anonymous_record_with_type)
4839           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4840             << Record->isUnion();
4841         else {
4842           Diag(Mem->getLocation(), DK) << Record->isUnion();
4843           Invalid = true;
4844         }
4845       }
4846     }
4847
4848     // C++11 [class.union]p8 (DR1460):
4849     //   At most one variant member of a union may have a
4850     //   brace-or-equal-initializer.
4851     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4852         Owner->isRecord())
4853       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4854                                 cast<CXXRecordDecl>(Record));
4855   }
4856
4857   if (!Record->isUnion() && !Owner->isRecord()) {
4858     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4859       << getLangOpts().CPlusPlus;
4860     Invalid = true;
4861   }
4862
4863   // C++ [dcl.dcl]p3:
4864   //   [If there are no declarators], and except for the declaration of an
4865   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4866   //   names into the program
4867   // C++ [class.mem]p2:
4868   //   each such member-declaration shall either declare at least one member
4869   //   name of the class or declare at least one unnamed bit-field
4870   //
4871   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4872   if (getLangOpts().CPlusPlus && Record->field_empty())
4873     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4874
4875   // Mock up a declarator.
4876   Declarator Dc(DS, DeclaratorContext::MemberContext);
4877   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4878   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4879
4880   // Create a declaration for this anonymous struct/union.
4881   NamedDecl *Anon = nullptr;
4882   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4883     Anon = FieldDecl::Create(
4884         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4885         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4886         /*BitWidth=*/nullptr, /*Mutable=*/false,
4887         /*InitStyle=*/ICIS_NoInit);
4888     Anon->setAccess(AS);
4889     if (getLangOpts().CPlusPlus)
4890       FieldCollector->Add(cast<FieldDecl>(Anon));
4891   } else {
4892     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4893     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4894     if (SCSpec == DeclSpec::SCS_mutable) {
4895       // mutable can only appear on non-static class members, so it's always
4896       // an error here
4897       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4898       Invalid = true;
4899       SC = SC_None;
4900     }
4901
4902     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4903                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4904                            Context.getTypeDeclType(Record), TInfo, SC);
4905
4906     // Default-initialize the implicit variable. This initialization will be
4907     // trivial in almost all cases, except if a union member has an in-class
4908     // initializer:
4909     //   union { int n = 0; };
4910     ActOnUninitializedDecl(Anon);
4911   }
4912   Anon->setImplicit();
4913
4914   // Mark this as an anonymous struct/union type.
4915   Record->setAnonymousStructOrUnion(true);
4916
4917   // Add the anonymous struct/union object to the current
4918   // context. We'll be referencing this object when we refer to one of
4919   // its members.
4920   Owner->addDecl(Anon);
4921
4922   // Inject the members of the anonymous struct/union into the owning
4923   // context and into the identifier resolver chain for name lookup
4924   // purposes.
4925   SmallVector<NamedDecl*, 2> Chain;
4926   Chain.push_back(Anon);
4927
4928   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4929     Invalid = true;
4930
4931   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4932     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4933       Decl *ManglingContextDecl;
4934       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4935               NewVD->getDeclContext(), ManglingContextDecl)) {
4936         Context.setManglingNumber(
4937             NewVD, MCtx->getManglingNumber(
4938                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4939         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4940       }
4941     }
4942   }
4943
4944   if (Invalid)
4945     Anon->setInvalidDecl();
4946
4947   return Anon;
4948 }
4949
4950 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4951 /// Microsoft C anonymous structure.
4952 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4953 /// Example:
4954 ///
4955 /// struct A { int a; };
4956 /// struct B { struct A; int b; };
4957 ///
4958 /// void foo() {
4959 ///   B var;
4960 ///   var.a = 3;
4961 /// }
4962 ///
4963 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4964                                            RecordDecl *Record) {
4965   assert(Record && "expected a record!");
4966
4967   // Mock up a declarator.
4968   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4969   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4970   assert(TInfo && "couldn't build declarator info for anonymous struct");
4971
4972   auto *ParentDecl = cast<RecordDecl>(CurContext);
4973   QualType RecTy = Context.getTypeDeclType(Record);
4974
4975   // Create a declaration for this anonymous struct.
4976   NamedDecl *Anon =
4977       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4978                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4979                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4980                         /*InitStyle=*/ICIS_NoInit);
4981   Anon->setImplicit();
4982
4983   // Add the anonymous struct object to the current context.
4984   CurContext->addDecl(Anon);
4985
4986   // Inject the members of the anonymous struct into the current
4987   // context and into the identifier resolver chain for name lookup
4988   // purposes.
4989   SmallVector<NamedDecl*, 2> Chain;
4990   Chain.push_back(Anon);
4991
4992   RecordDecl *RecordDef = Record->getDefinition();
4993   if (RequireCompleteType(Anon->getLocation(), RecTy,
4994                           diag::err_field_incomplete) ||
4995       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4996                                           AS_none, Chain)) {
4997     Anon->setInvalidDecl();
4998     ParentDecl->setInvalidDecl();
4999   }
5000
5001   return Anon;
5002 }
5003
5004 /// GetNameForDeclarator - Determine the full declaration name for the
5005 /// given Declarator.
5006 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5007   return GetNameFromUnqualifiedId(D.getName());
5008 }
5009
5010 /// Retrieves the declaration name from a parsed unqualified-id.
5011 DeclarationNameInfo
5012 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5013   DeclarationNameInfo NameInfo;
5014   NameInfo.setLoc(Name.StartLocation);
5015
5016   switch (Name.getKind()) {
5017
5018   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5019   case UnqualifiedIdKind::IK_Identifier:
5020     NameInfo.setName(Name.Identifier);
5021     return NameInfo;
5022
5023   case UnqualifiedIdKind::IK_DeductionGuideName: {
5024     // C++ [temp.deduct.guide]p3:
5025     //   The simple-template-id shall name a class template specialization.
5026     //   The template-name shall be the same identifier as the template-name
5027     //   of the simple-template-id.
5028     // These together intend to imply that the template-name shall name a
5029     // class template.
5030     // FIXME: template<typename T> struct X {};
5031     //        template<typename T> using Y = X<T>;
5032     //        Y(int) -> Y<int>;
5033     //   satisfies these rules but does not name a class template.
5034     TemplateName TN = Name.TemplateName.get().get();
5035     auto *Template = TN.getAsTemplateDecl();
5036     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5037       Diag(Name.StartLocation,
5038            diag::err_deduction_guide_name_not_class_template)
5039         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5040       if (Template)
5041         Diag(Template->getLocation(), diag::note_template_decl_here);
5042       return DeclarationNameInfo();
5043     }
5044
5045     NameInfo.setName(
5046         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5047     return NameInfo;
5048   }
5049
5050   case UnqualifiedIdKind::IK_OperatorFunctionId:
5051     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5052                                            Name.OperatorFunctionId.Operator));
5053     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5054       = Name.OperatorFunctionId.SymbolLocations[0];
5055     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5056       = Name.EndLocation.getRawEncoding();
5057     return NameInfo;
5058
5059   case UnqualifiedIdKind::IK_LiteralOperatorId:
5060     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5061                                                            Name.Identifier));
5062     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5063     return NameInfo;
5064
5065   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5066     TypeSourceInfo *TInfo;
5067     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5068     if (Ty.isNull())
5069       return DeclarationNameInfo();
5070     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5071                                                Context.getCanonicalType(Ty)));
5072     NameInfo.setNamedTypeInfo(TInfo);
5073     return NameInfo;
5074   }
5075
5076   case UnqualifiedIdKind::IK_ConstructorName: {
5077     TypeSourceInfo *TInfo;
5078     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5079     if (Ty.isNull())
5080       return DeclarationNameInfo();
5081     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5082                                               Context.getCanonicalType(Ty)));
5083     NameInfo.setNamedTypeInfo(TInfo);
5084     return NameInfo;
5085   }
5086
5087   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5088     // In well-formed code, we can only have a constructor
5089     // template-id that refers to the current context, so go there
5090     // to find the actual type being constructed.
5091     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5092     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5093       return DeclarationNameInfo();
5094
5095     // Determine the type of the class being constructed.
5096     QualType CurClassType = Context.getTypeDeclType(CurClass);
5097
5098     // FIXME: Check two things: that the template-id names the same type as
5099     // CurClassType, and that the template-id does not occur when the name
5100     // was qualified.
5101
5102     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5103                                     Context.getCanonicalType(CurClassType)));
5104     // FIXME: should we retrieve TypeSourceInfo?
5105     NameInfo.setNamedTypeInfo(nullptr);
5106     return NameInfo;
5107   }
5108
5109   case UnqualifiedIdKind::IK_DestructorName: {
5110     TypeSourceInfo *TInfo;
5111     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5112     if (Ty.isNull())
5113       return DeclarationNameInfo();
5114     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5115                                               Context.getCanonicalType(Ty)));
5116     NameInfo.setNamedTypeInfo(TInfo);
5117     return NameInfo;
5118   }
5119
5120   case UnqualifiedIdKind::IK_TemplateId: {
5121     TemplateName TName = Name.TemplateId->Template.get();
5122     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5123     return Context.getNameForTemplate(TName, TNameLoc);
5124   }
5125
5126   } // switch (Name.getKind())
5127
5128   llvm_unreachable("Unknown name kind");
5129 }
5130
5131 static QualType getCoreType(QualType Ty) {
5132   do {
5133     if (Ty->isPointerType() || Ty->isReferenceType())
5134       Ty = Ty->getPointeeType();
5135     else if (Ty->isArrayType())
5136       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5137     else
5138       return Ty.withoutLocalFastQualifiers();
5139   } while (true);
5140 }
5141
5142 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5143 /// and Definition have "nearly" matching parameters. This heuristic is
5144 /// used to improve diagnostics in the case where an out-of-line function
5145 /// definition doesn't match any declaration within the class or namespace.
5146 /// Also sets Params to the list of indices to the parameters that differ
5147 /// between the declaration and the definition. If hasSimilarParameters
5148 /// returns true and Params is empty, then all of the parameters match.
5149 static bool hasSimilarParameters(ASTContext &Context,
5150                                      FunctionDecl *Declaration,
5151                                      FunctionDecl *Definition,
5152                                      SmallVectorImpl<unsigned> &Params) {
5153   Params.clear();
5154   if (Declaration->param_size() != Definition->param_size())
5155     return false;
5156   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5157     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5158     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5159
5160     // The parameter types are identical
5161     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5162       continue;
5163
5164     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5165     QualType DefParamBaseTy = getCoreType(DefParamTy);
5166     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5167     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5168
5169     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5170         (DeclTyName && DeclTyName == DefTyName))
5171       Params.push_back(Idx);
5172     else  // The two parameters aren't even close
5173       return false;
5174   }
5175
5176   return true;
5177 }
5178
5179 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5180 /// declarator needs to be rebuilt in the current instantiation.
5181 /// Any bits of declarator which appear before the name are valid for
5182 /// consideration here.  That's specifically the type in the decl spec
5183 /// and the base type in any member-pointer chunks.
5184 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5185                                                     DeclarationName Name) {
5186   // The types we specifically need to rebuild are:
5187   //   - typenames, typeofs, and decltypes
5188   //   - types which will become injected class names
5189   // Of course, we also need to rebuild any type referencing such a
5190   // type.  It's safest to just say "dependent", but we call out a
5191   // few cases here.
5192
5193   DeclSpec &DS = D.getMutableDeclSpec();
5194   switch (DS.getTypeSpecType()) {
5195   case DeclSpec::TST_typename:
5196   case DeclSpec::TST_typeofType:
5197   case DeclSpec::TST_underlyingType:
5198   case DeclSpec::TST_atomic: {
5199     // Grab the type from the parser.
5200     TypeSourceInfo *TSI = nullptr;
5201     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5202     if (T.isNull() || !T->isDependentType()) break;
5203
5204     // Make sure there's a type source info.  This isn't really much
5205     // of a waste; most dependent types should have type source info
5206     // attached already.
5207     if (!TSI)
5208       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5209
5210     // Rebuild the type in the current instantiation.
5211     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5212     if (!TSI) return true;
5213
5214     // Store the new type back in the decl spec.
5215     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5216     DS.UpdateTypeRep(LocType);
5217     break;
5218   }
5219
5220   case DeclSpec::TST_decltype:
5221   case DeclSpec::TST_typeofExpr: {
5222     Expr *E = DS.getRepAsExpr();
5223     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5224     if (Result.isInvalid()) return true;
5225     DS.UpdateExprRep(Result.get());
5226     break;
5227   }
5228
5229   default:
5230     // Nothing to do for these decl specs.
5231     break;
5232   }
5233
5234   // It doesn't matter what order we do this in.
5235   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5236     DeclaratorChunk &Chunk = D.getTypeObject(I);
5237
5238     // The only type information in the declarator which can come
5239     // before the declaration name is the base type of a member
5240     // pointer.
5241     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5242       continue;
5243
5244     // Rebuild the scope specifier in-place.
5245     CXXScopeSpec &SS = Chunk.Mem.Scope();
5246     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5247       return true;
5248   }
5249
5250   return false;
5251 }
5252
5253 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5254   D.setFunctionDefinitionKind(FDK_Declaration);
5255   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5256
5257   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5258       Dcl && Dcl->getDeclContext()->isFileContext())
5259     Dcl->setTopLevelDeclInObjCContainer();
5260
5261   if (getLangOpts().OpenCL)
5262     setCurrentOpenCLExtensionForDecl(Dcl);
5263
5264   return Dcl;
5265 }
5266
5267 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5268 ///   If T is the name of a class, then each of the following shall have a
5269 ///   name different from T:
5270 ///     - every static data member of class T;
5271 ///     - every member function of class T
5272 ///     - every member of class T that is itself a type;
5273 /// \returns true if the declaration name violates these rules.
5274 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5275                                    DeclarationNameInfo NameInfo) {
5276   DeclarationName Name = NameInfo.getName();
5277
5278   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5279   while (Record && Record->isAnonymousStructOrUnion())
5280     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5281   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5282     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5283     return true;
5284   }
5285
5286   return false;
5287 }
5288
5289 /// Diagnose a declaration whose declarator-id has the given
5290 /// nested-name-specifier.
5291 ///
5292 /// \param SS The nested-name-specifier of the declarator-id.
5293 ///
5294 /// \param DC The declaration context to which the nested-name-specifier
5295 /// resolves.
5296 ///
5297 /// \param Name The name of the entity being declared.
5298 ///
5299 /// \param Loc The location of the name of the entity being declared.
5300 ///
5301 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5302 /// we're declaring an explicit / partial specialization / instantiation.
5303 ///
5304 /// \returns true if we cannot safely recover from this error, false otherwise.
5305 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5306                                         DeclarationName Name,
5307                                         SourceLocation Loc, bool IsTemplateId) {
5308   DeclContext *Cur = CurContext;
5309   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5310     Cur = Cur->getParent();
5311
5312   // If the user provided a superfluous scope specifier that refers back to the
5313   // class in which the entity is already declared, diagnose and ignore it.
5314   //
5315   // class X {
5316   //   void X::f();
5317   // };
5318   //
5319   // Note, it was once ill-formed to give redundant qualification in all
5320   // contexts, but that rule was removed by DR482.
5321   if (Cur->Equals(DC)) {
5322     if (Cur->isRecord()) {
5323       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5324                                       : diag::err_member_extra_qualification)
5325         << Name << FixItHint::CreateRemoval(SS.getRange());
5326       SS.clear();
5327     } else {
5328       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5329     }
5330     return false;
5331   }
5332
5333   // Check whether the qualifying scope encloses the scope of the original
5334   // declaration. For a template-id, we perform the checks in
5335   // CheckTemplateSpecializationScope.
5336   if (!Cur->Encloses(DC) && !IsTemplateId) {
5337     if (Cur->isRecord())
5338       Diag(Loc, diag::err_member_qualification)
5339         << Name << SS.getRange();
5340     else if (isa<TranslationUnitDecl>(DC))
5341       Diag(Loc, diag::err_invalid_declarator_global_scope)
5342         << Name << SS.getRange();
5343     else if (isa<FunctionDecl>(Cur))
5344       Diag(Loc, diag::err_invalid_declarator_in_function)
5345         << Name << SS.getRange();
5346     else if (isa<BlockDecl>(Cur))
5347       Diag(Loc, diag::err_invalid_declarator_in_block)
5348         << Name << SS.getRange();
5349     else
5350       Diag(Loc, diag::err_invalid_declarator_scope)
5351       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5352
5353     return true;
5354   }
5355
5356   if (Cur->isRecord()) {
5357     // Cannot qualify members within a class.
5358     Diag(Loc, diag::err_member_qualification)
5359       << Name << SS.getRange();
5360     SS.clear();
5361
5362     // C++ constructors and destructors with incorrect scopes can break
5363     // our AST invariants by having the wrong underlying types. If
5364     // that's the case, then drop this declaration entirely.
5365     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5366          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5367         !Context.hasSameType(Name.getCXXNameType(),
5368                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5369       return true;
5370
5371     return false;
5372   }
5373
5374   // C++11 [dcl.meaning]p1:
5375   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5376   //   not begin with a decltype-specifer"
5377   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5378   while (SpecLoc.getPrefix())
5379     SpecLoc = SpecLoc.getPrefix();
5380   if (dyn_cast_or_null<DecltypeType>(
5381         SpecLoc.getNestedNameSpecifier()->getAsType()))
5382     Diag(Loc, diag::err_decltype_in_declarator)
5383       << SpecLoc.getTypeLoc().getSourceRange();
5384
5385   return false;
5386 }
5387
5388 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5389                                   MultiTemplateParamsArg TemplateParamLists) {
5390   // TODO: consider using NameInfo for diagnostic.
5391   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5392   DeclarationName Name = NameInfo.getName();
5393
5394   // All of these full declarators require an identifier.  If it doesn't have
5395   // one, the ParsedFreeStandingDeclSpec action should be used.
5396   if (D.isDecompositionDeclarator()) {
5397     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5398   } else if (!Name) {
5399     if (!D.isInvalidType())  // Reject this if we think it is valid.
5400       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5401           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5402     return nullptr;
5403   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5404     return nullptr;
5405
5406   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5407   // we find one that is.
5408   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5409          (S->getFlags() & Scope::TemplateParamScope) != 0)
5410     S = S->getParent();
5411
5412   DeclContext *DC = CurContext;
5413   if (D.getCXXScopeSpec().isInvalid())
5414     D.setInvalidType();
5415   else if (D.getCXXScopeSpec().isSet()) {
5416     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5417                                         UPPC_DeclarationQualifier))
5418       return nullptr;
5419
5420     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5421     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5422     if (!DC || isa<EnumDecl>(DC)) {
5423       // If we could not compute the declaration context, it's because the
5424       // declaration context is dependent but does not refer to a class,
5425       // class template, or class template partial specialization. Complain
5426       // and return early, to avoid the coming semantic disaster.
5427       Diag(D.getIdentifierLoc(),
5428            diag::err_template_qualified_declarator_no_match)
5429         << D.getCXXScopeSpec().getScopeRep()
5430         << D.getCXXScopeSpec().getRange();
5431       return nullptr;
5432     }
5433     bool IsDependentContext = DC->isDependentContext();
5434
5435     if (!IsDependentContext &&
5436         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5437       return nullptr;
5438
5439     // If a class is incomplete, do not parse entities inside it.
5440     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5441       Diag(D.getIdentifierLoc(),
5442            diag::err_member_def_undefined_record)
5443         << Name << DC << D.getCXXScopeSpec().getRange();
5444       return nullptr;
5445     }
5446     if (!D.getDeclSpec().isFriendSpecified()) {
5447       if (diagnoseQualifiedDeclaration(
5448               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5449               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5450         if (DC->isRecord())
5451           return nullptr;
5452
5453         D.setInvalidType();
5454       }
5455     }
5456
5457     // Check whether we need to rebuild the type of the given
5458     // declaration in the current instantiation.
5459     if (EnteringContext && IsDependentContext &&
5460         TemplateParamLists.size() != 0) {
5461       ContextRAII SavedContext(*this, DC);
5462       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5463         D.setInvalidType();
5464     }
5465   }
5466
5467   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5468   QualType R = TInfo->getType();
5469
5470   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5471                                       UPPC_DeclarationType))
5472     D.setInvalidType();
5473
5474   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5475                         forRedeclarationInCurContext());
5476
5477   // See if this is a redefinition of a variable in the same scope.
5478   if (!D.getCXXScopeSpec().isSet()) {
5479     bool IsLinkageLookup = false;
5480     bool CreateBuiltins = false;
5481
5482     // If the declaration we're planning to build will be a function
5483     // or object with linkage, then look for another declaration with
5484     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5485     //
5486     // If the declaration we're planning to build will be declared with
5487     // external linkage in the translation unit, create any builtin with
5488     // the same name.
5489     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5490       /* Do nothing*/;
5491     else if (CurContext->isFunctionOrMethod() &&
5492              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5493               R->isFunctionType())) {
5494       IsLinkageLookup = true;
5495       CreateBuiltins =
5496           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5497     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5498                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5499       CreateBuiltins = true;
5500
5501     if (IsLinkageLookup) {
5502       Previous.clear(LookupRedeclarationWithLinkage);
5503       Previous.setRedeclarationKind(ForExternalRedeclaration);
5504     }
5505
5506     LookupName(Previous, S, CreateBuiltins);
5507   } else { // Something like "int foo::x;"
5508     LookupQualifiedName(Previous, DC);
5509
5510     // C++ [dcl.meaning]p1:
5511     //   When the declarator-id is qualified, the declaration shall refer to a
5512     //  previously declared member of the class or namespace to which the
5513     //  qualifier refers (or, in the case of a namespace, of an element of the
5514     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5515     //  thereof; [...]
5516     //
5517     // Note that we already checked the context above, and that we do not have
5518     // enough information to make sure that Previous contains the declaration
5519     // we want to match. For example, given:
5520     //
5521     //   class X {
5522     //     void f();
5523     //     void f(float);
5524     //   };
5525     //
5526     //   void X::f(int) { } // ill-formed
5527     //
5528     // In this case, Previous will point to the overload set
5529     // containing the two f's declared in X, but neither of them
5530     // matches.
5531
5532     // C++ [dcl.meaning]p1:
5533     //   [...] the member shall not merely have been introduced by a
5534     //   using-declaration in the scope of the class or namespace nominated by
5535     //   the nested-name-specifier of the declarator-id.
5536     RemoveUsingDecls(Previous);
5537   }
5538
5539   if (Previous.isSingleResult() &&
5540       Previous.getFoundDecl()->isTemplateParameter()) {
5541     // Maybe we will complain about the shadowed template parameter.
5542     if (!D.isInvalidType())
5543       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5544                                       Previous.getFoundDecl());
5545
5546     // Just pretend that we didn't see the previous declaration.
5547     Previous.clear();
5548   }
5549
5550   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5551     // Forget that the previous declaration is the injected-class-name.
5552     Previous.clear();
5553
5554   // In C++, the previous declaration we find might be a tag type
5555   // (class or enum). In this case, the new declaration will hide the
5556   // tag type. Note that this applies to functions, function templates, and
5557   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5558   if (Previous.isSingleTagDecl() &&
5559       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5560       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5561     Previous.clear();
5562
5563   // Check that there are no default arguments other than in the parameters
5564   // of a function declaration (C++ only).
5565   if (getLangOpts().CPlusPlus)
5566     CheckExtraCXXDefaultArguments(D);
5567
5568   NamedDecl *New;
5569
5570   bool AddToScope = true;
5571   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5572     if (TemplateParamLists.size()) {
5573       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5574       return nullptr;
5575     }
5576
5577     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5578   } else if (R->isFunctionType()) {
5579     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5580                                   TemplateParamLists,
5581                                   AddToScope);
5582   } else {
5583     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5584                                   AddToScope);
5585   }
5586
5587   if (!New)
5588     return nullptr;
5589
5590   // If this has an identifier and is not a function template specialization,
5591   // add it to the scope stack.
5592   if (New->getDeclName() && AddToScope)
5593     PushOnScopeChains(New, S);
5594
5595   if (isInOpenMPDeclareTargetContext())
5596     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5597
5598   return New;
5599 }
5600
5601 /// Helper method to turn variable array types into constant array
5602 /// types in certain situations which would otherwise be errors (for
5603 /// GCC compatibility).
5604 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5605                                                     ASTContext &Context,
5606                                                     bool &SizeIsNegative,
5607                                                     llvm::APSInt &Oversized) {
5608   // This method tries to turn a variable array into a constant
5609   // array even when the size isn't an ICE.  This is necessary
5610   // for compatibility with code that depends on gcc's buggy
5611   // constant expression folding, like struct {char x[(int)(char*)2];}
5612   SizeIsNegative = false;
5613   Oversized = 0;
5614
5615   if (T->isDependentType())
5616     return QualType();
5617
5618   QualifierCollector Qs;
5619   const Type *Ty = Qs.strip(T);
5620
5621   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5622     QualType Pointee = PTy->getPointeeType();
5623     QualType FixedType =
5624         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5625                                             Oversized);
5626     if (FixedType.isNull()) return FixedType;
5627     FixedType = Context.getPointerType(FixedType);
5628     return Qs.apply(Context, FixedType);
5629   }
5630   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5631     QualType Inner = PTy->getInnerType();
5632     QualType FixedType =
5633         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5634                                             Oversized);
5635     if (FixedType.isNull()) return FixedType;
5636     FixedType = Context.getParenType(FixedType);
5637     return Qs.apply(Context, FixedType);
5638   }
5639
5640   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5641   if (!VLATy)
5642     return QualType();
5643   // FIXME: We should probably handle this case
5644   if (VLATy->getElementType()->isVariablyModifiedType())
5645     return QualType();
5646
5647   Expr::EvalResult Result;
5648   if (!VLATy->getSizeExpr() ||
5649       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5650     return QualType();
5651
5652   llvm::APSInt Res = Result.Val.getInt();
5653
5654   // Check whether the array size is negative.
5655   if (Res.isSigned() && Res.isNegative()) {
5656     SizeIsNegative = true;
5657     return QualType();
5658   }
5659
5660   // Check whether the array is too large to be addressed.
5661   unsigned ActiveSizeBits
5662     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5663                                               Res);
5664   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5665     Oversized = Res;
5666     return QualType();
5667   }
5668
5669   return Context.getConstantArrayType(VLATy->getElementType(),
5670                                       Res, ArrayType::Normal, 0);
5671 }
5672
5673 static void
5674 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5675   SrcTL = SrcTL.getUnqualifiedLoc();
5676   DstTL = DstTL.getUnqualifiedLoc();
5677   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5678     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5679     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5680                                       DstPTL.getPointeeLoc());
5681     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5682     return;
5683   }
5684   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5685     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5686     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5687                                       DstPTL.getInnerLoc());
5688     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5689     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5690     return;
5691   }
5692   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5693   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5694   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5695   TypeLoc DstElemTL = DstATL.getElementLoc();
5696   DstElemTL.initializeFullCopy(SrcElemTL);
5697   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5698   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5699   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5700 }
5701
5702 /// Helper method to turn variable array types into constant array
5703 /// types in certain situations which would otherwise be errors (for
5704 /// GCC compatibility).
5705 static TypeSourceInfo*
5706 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5707                                               ASTContext &Context,
5708                                               bool &SizeIsNegative,
5709                                               llvm::APSInt &Oversized) {
5710   QualType FixedTy
5711     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5712                                           SizeIsNegative, Oversized);
5713   if (FixedTy.isNull())
5714     return nullptr;
5715   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5716   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5717                                     FixedTInfo->getTypeLoc());
5718   return FixedTInfo;
5719 }
5720
5721 /// Register the given locally-scoped extern "C" declaration so
5722 /// that it can be found later for redeclarations. We include any extern "C"
5723 /// declaration that is not visible in the translation unit here, not just
5724 /// function-scope declarations.
5725 void
5726 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5727   if (!getLangOpts().CPlusPlus &&
5728       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5729     // Don't need to track declarations in the TU in C.
5730     return;
5731
5732   // Note that we have a locally-scoped external with this name.
5733   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5734 }
5735
5736 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5737   // FIXME: We can have multiple results via __attribute__((overloadable)).
5738   auto Result = Context.getExternCContextDecl()->lookup(Name);
5739   return Result.empty() ? nullptr : *Result.begin();
5740 }
5741
5742 /// Diagnose function specifiers on a declaration of an identifier that
5743 /// does not identify a function.
5744 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5745   // FIXME: We should probably indicate the identifier in question to avoid
5746   // confusion for constructs like "virtual int a(), b;"
5747   if (DS.isVirtualSpecified())
5748     Diag(DS.getVirtualSpecLoc(),
5749          diag::err_virtual_non_function);
5750
5751   if (DS.hasExplicitSpecifier())
5752     Diag(DS.getExplicitSpecLoc(),
5753          diag::err_explicit_non_function);
5754
5755   if (DS.isNoreturnSpecified())
5756     Diag(DS.getNoreturnSpecLoc(),
5757          diag::err_noreturn_non_function);
5758 }
5759
5760 NamedDecl*
5761 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5762                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5763   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5764   if (D.getCXXScopeSpec().isSet()) {
5765     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5766       << D.getCXXScopeSpec().getRange();
5767     D.setInvalidType();
5768     // Pretend we didn't see the scope specifier.
5769     DC = CurContext;
5770     Previous.clear();
5771   }
5772
5773   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5774
5775   if (D.getDeclSpec().isInlineSpecified())
5776     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5777         << getLangOpts().CPlusPlus17;
5778   if (D.getDeclSpec().hasConstexprSpecifier())
5779     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5780         << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
5781
5782   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5783     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5784       Diag(D.getName().StartLocation,
5785            diag::err_deduction_guide_invalid_specifier)
5786           << "typedef";
5787     else
5788       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5789           << D.getName().getSourceRange();
5790     return nullptr;
5791   }
5792
5793   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5794   if (!NewTD) return nullptr;
5795
5796   // Handle attributes prior to checking for duplicates in MergeVarDecl
5797   ProcessDeclAttributes(S, NewTD, D);
5798
5799   CheckTypedefForVariablyModifiedType(S, NewTD);
5800
5801   bool Redeclaration = D.isRedeclaration();
5802   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5803   D.setRedeclaration(Redeclaration);
5804   return ND;
5805 }
5806
5807 void
5808 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5809   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5810   // then it shall have block scope.
5811   // Note that variably modified types must be fixed before merging the decl so
5812   // that redeclarations will match.
5813   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5814   QualType T = TInfo->getType();
5815   if (T->isVariablyModifiedType()) {
5816     setFunctionHasBranchProtectedScope();
5817
5818     if (S->getFnParent() == nullptr) {
5819       bool SizeIsNegative;
5820       llvm::APSInt Oversized;
5821       TypeSourceInfo *FixedTInfo =
5822         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5823                                                       SizeIsNegative,
5824                                                       Oversized);
5825       if (FixedTInfo) {
5826         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5827         NewTD->setTypeSourceInfo(FixedTInfo);
5828       } else {
5829         if (SizeIsNegative)
5830           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5831         else if (T->isVariableArrayType())
5832           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5833         else if (Oversized.getBoolValue())
5834           Diag(NewTD->getLocation(), diag::err_array_too_large)
5835             << Oversized.toString(10);
5836         else
5837           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5838         NewTD->setInvalidDecl();
5839       }
5840     }
5841   }
5842 }
5843
5844 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5845 /// declares a typedef-name, either using the 'typedef' type specifier or via
5846 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5847 NamedDecl*
5848 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5849                            LookupResult &Previous, bool &Redeclaration) {
5850
5851   // Find the shadowed declaration before filtering for scope.
5852   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5853
5854   // Merge the decl with the existing one if appropriate. If the decl is
5855   // in an outer scope, it isn't the same thing.
5856   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5857                        /*AllowInlineNamespace*/false);
5858   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5859   if (!Previous.empty()) {
5860     Redeclaration = true;
5861     MergeTypedefNameDecl(S, NewTD, Previous);
5862   }
5863
5864   if (ShadowedDecl && !Redeclaration)
5865     CheckShadow(NewTD, ShadowedDecl, Previous);
5866
5867   // If this is the C FILE type, notify the AST context.
5868   if (IdentifierInfo *II = NewTD->getIdentifier())
5869     if (!NewTD->isInvalidDecl() &&
5870         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5871       if (II->isStr("FILE"))
5872         Context.setFILEDecl(NewTD);
5873       else if (II->isStr("jmp_buf"))
5874         Context.setjmp_bufDecl(NewTD);
5875       else if (II->isStr("sigjmp_buf"))
5876         Context.setsigjmp_bufDecl(NewTD);
5877       else if (II->isStr("ucontext_t"))
5878         Context.setucontext_tDecl(NewTD);
5879     }
5880
5881   return NewTD;
5882 }
5883
5884 /// Determines whether the given declaration is an out-of-scope
5885 /// previous declaration.
5886 ///
5887 /// This routine should be invoked when name lookup has found a
5888 /// previous declaration (PrevDecl) that is not in the scope where a
5889 /// new declaration by the same name is being introduced. If the new
5890 /// declaration occurs in a local scope, previous declarations with
5891 /// linkage may still be considered previous declarations (C99
5892 /// 6.2.2p4-5, C++ [basic.link]p6).
5893 ///
5894 /// \param PrevDecl the previous declaration found by name
5895 /// lookup
5896 ///
5897 /// \param DC the context in which the new declaration is being
5898 /// declared.
5899 ///
5900 /// \returns true if PrevDecl is an out-of-scope previous declaration
5901 /// for a new delcaration with the same name.
5902 static bool
5903 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5904                                 ASTContext &Context) {
5905   if (!PrevDecl)
5906     return false;
5907
5908   if (!PrevDecl->hasLinkage())
5909     return false;
5910
5911   if (Context.getLangOpts().CPlusPlus) {
5912     // C++ [basic.link]p6:
5913     //   If there is a visible declaration of an entity with linkage
5914     //   having the same name and type, ignoring entities declared
5915     //   outside the innermost enclosing namespace scope, the block
5916     //   scope declaration declares that same entity and receives the
5917     //   linkage of the previous declaration.
5918     DeclContext *OuterContext = DC->getRedeclContext();
5919     if (!OuterContext->isFunctionOrMethod())
5920       // This rule only applies to block-scope declarations.
5921       return false;
5922
5923     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5924     if (PrevOuterContext->isRecord())
5925       // We found a member function: ignore it.
5926       return false;
5927
5928     // Find the innermost enclosing namespace for the new and
5929     // previous declarations.
5930     OuterContext = OuterContext->getEnclosingNamespaceContext();
5931     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5932
5933     // The previous declaration is in a different namespace, so it
5934     // isn't the same function.
5935     if (!OuterContext->Equals(PrevOuterContext))
5936       return false;
5937   }
5938
5939   return true;
5940 }
5941
5942 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5943   CXXScopeSpec &SS = D.getCXXScopeSpec();
5944   if (!SS.isSet()) return;
5945   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5946 }
5947
5948 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5949   QualType type = decl->getType();
5950   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5951   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5952     // Various kinds of declaration aren't allowed to be __autoreleasing.
5953     unsigned kind = -1U;
5954     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5955       if (var->hasAttr<BlocksAttr>())
5956         kind = 0; // __block
5957       else if (!var->hasLocalStorage())
5958         kind = 1; // global
5959     } else if (isa<ObjCIvarDecl>(decl)) {
5960       kind = 3; // ivar
5961     } else if (isa<FieldDecl>(decl)) {
5962       kind = 2; // field
5963     }
5964
5965     if (kind != -1U) {
5966       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5967         << kind;
5968     }
5969   } else if (lifetime == Qualifiers::OCL_None) {
5970     // Try to infer lifetime.
5971     if (!type->isObjCLifetimeType())
5972       return false;
5973
5974     lifetime = type->getObjCARCImplicitLifetime();
5975     type = Context.getLifetimeQualifiedType(type, lifetime);
5976     decl->setType(type);
5977   }
5978
5979   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5980     // Thread-local variables cannot have lifetime.
5981     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5982         var->getTLSKind()) {
5983       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5984         << var->getType();
5985       return true;
5986     }
5987   }
5988
5989   return false;
5990 }
5991
5992 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5993   // Ensure that an auto decl is deduced otherwise the checks below might cache
5994   // the wrong linkage.
5995   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5996
5997   // 'weak' only applies to declarations with external linkage.
5998   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5999     if (!ND.isExternallyVisible()) {
6000       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6001       ND.dropAttr<WeakAttr>();
6002     }
6003   }
6004   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6005     if (ND.isExternallyVisible()) {
6006       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6007       ND.dropAttr<WeakRefAttr>();
6008       ND.dropAttr<AliasAttr>();
6009     }
6010   }
6011
6012   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6013     if (VD->hasInit()) {
6014       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6015         assert(VD->isThisDeclarationADefinition() &&
6016                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6017         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6018         VD->dropAttr<AliasAttr>();
6019       }
6020     }
6021   }
6022
6023   // 'selectany' only applies to externally visible variable declarations.
6024   // It does not apply to functions.
6025   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6026     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6027       S.Diag(Attr->getLocation(),
6028              diag::err_attribute_selectany_non_extern_data);
6029       ND.dropAttr<SelectAnyAttr>();
6030     }
6031   }
6032
6033   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6034     auto *VD = dyn_cast<VarDecl>(&ND);
6035     bool IsAnonymousNS = false;
6036     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6037     if (VD) {
6038       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6039       while (NS && !IsAnonymousNS) {
6040         IsAnonymousNS = NS->isAnonymousNamespace();
6041         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6042       }
6043     }
6044     // dll attributes require external linkage. Static locals may have external
6045     // linkage but still cannot be explicitly imported or exported.
6046     // In Microsoft mode, a variable defined in anonymous namespace must have
6047     // external linkage in order to be exported.
6048     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6049     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6050         (!AnonNSInMicrosoftMode &&
6051          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6052       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6053         << &ND << Attr;
6054       ND.setInvalidDecl();
6055     }
6056   }
6057
6058   // Virtual functions cannot be marked as 'notail'.
6059   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6060     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6061       if (MD->isVirtual()) {
6062         S.Diag(ND.getLocation(),
6063                diag::err_invalid_attribute_on_virtual_function)
6064             << Attr;
6065         ND.dropAttr<NotTailCalledAttr>();
6066       }
6067
6068   // Check the attributes on the function type, if any.
6069   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6070     // Don't declare this variable in the second operand of the for-statement;
6071     // GCC miscompiles that by ending its lifetime before evaluating the
6072     // third operand. See gcc.gnu.org/PR86769.
6073     AttributedTypeLoc ATL;
6074     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6075          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6076          TL = ATL.getModifiedLoc()) {
6077       // The [[lifetimebound]] attribute can be applied to the implicit object
6078       // parameter of a non-static member function (other than a ctor or dtor)
6079       // by applying it to the function type.
6080       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6081         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6082         if (!MD || MD->isStatic()) {
6083           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6084               << !MD << A->getRange();
6085         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6086           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6087               << isa<CXXDestructorDecl>(MD) << A->getRange();
6088         }
6089       }
6090     }
6091   }
6092 }
6093
6094 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6095                                            NamedDecl *NewDecl,
6096                                            bool IsSpecialization,
6097                                            bool IsDefinition) {
6098   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6099     return;
6100
6101   bool IsTemplate = false;
6102   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6103     OldDecl = OldTD->getTemplatedDecl();
6104     IsTemplate = true;
6105     if (!IsSpecialization)
6106       IsDefinition = false;
6107   }
6108   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6109     NewDecl = NewTD->getTemplatedDecl();
6110     IsTemplate = true;
6111   }
6112
6113   if (!OldDecl || !NewDecl)
6114     return;
6115
6116   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6117   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6118   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6119   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6120
6121   // dllimport and dllexport are inheritable attributes so we have to exclude
6122   // inherited attribute instances.
6123   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6124                     (NewExportAttr && !NewExportAttr->isInherited());
6125
6126   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6127   // the only exception being explicit specializations.
6128   // Implicitly generated declarations are also excluded for now because there
6129   // is no other way to switch these to use dllimport or dllexport.
6130   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6131
6132   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6133     // Allow with a warning for free functions and global variables.
6134     bool JustWarn = false;
6135     if (!OldDecl->isCXXClassMember()) {
6136       auto *VD = dyn_cast<VarDecl>(OldDecl);
6137       if (VD && !VD->getDescribedVarTemplate())
6138         JustWarn = true;
6139       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6140       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6141         JustWarn = true;
6142     }
6143
6144     // We cannot change a declaration that's been used because IR has already
6145     // been emitted. Dllimported functions will still work though (modulo
6146     // address equality) as they can use the thunk.
6147     if (OldDecl->isUsed())
6148       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6149         JustWarn = false;
6150
6151     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6152                                : diag::err_attribute_dll_redeclaration;
6153     S.Diag(NewDecl->getLocation(), DiagID)
6154         << NewDecl
6155         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6156     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6157     if (!JustWarn) {
6158       NewDecl->setInvalidDecl();
6159       return;
6160     }
6161   }
6162
6163   // A redeclaration is not allowed to drop a dllimport attribute, the only
6164   // exceptions being inline function definitions (except for function
6165   // templates), local extern declarations, qualified friend declarations or
6166   // special MSVC extension: in the last case, the declaration is treated as if
6167   // it were marked dllexport.
6168   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6169   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6170   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6171     // Ignore static data because out-of-line definitions are diagnosed
6172     // separately.
6173     IsStaticDataMember = VD->isStaticDataMember();
6174     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6175                    VarDecl::DeclarationOnly;
6176   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6177     IsInline = FD->isInlined();
6178     IsQualifiedFriend = FD->getQualifier() &&
6179                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6180   }
6181
6182   if (OldImportAttr && !HasNewAttr &&
6183       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6184       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6185     if (IsMicrosoft && IsDefinition) {
6186       S.Diag(NewDecl->getLocation(),
6187              diag::warn_redeclaration_without_import_attribute)
6188           << NewDecl;
6189       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6190       NewDecl->dropAttr<DLLImportAttr>();
6191       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6192           NewImportAttr->getRange(), S.Context,
6193           NewImportAttr->getSpellingListIndex()));
6194     } else {
6195       S.Diag(NewDecl->getLocation(),
6196              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6197           << NewDecl << OldImportAttr;
6198       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6199       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6200       OldDecl->dropAttr<DLLImportAttr>();
6201       NewDecl->dropAttr<DLLImportAttr>();
6202     }
6203   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6204     // In MinGW, seeing a function declared inline drops the dllimport
6205     // attribute.
6206     OldDecl->dropAttr<DLLImportAttr>();
6207     NewDecl->dropAttr<DLLImportAttr>();
6208     S.Diag(NewDecl->getLocation(),
6209            diag::warn_dllimport_dropped_from_inline_function)
6210         << NewDecl << OldImportAttr;
6211   }
6212
6213   // A specialization of a class template member function is processed here
6214   // since it's a redeclaration. If the parent class is dllexport, the
6215   // specialization inherits that attribute. This doesn't happen automatically
6216   // since the parent class isn't instantiated until later.
6217   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6218     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6219         !NewImportAttr && !NewExportAttr) {
6220       if (const DLLExportAttr *ParentExportAttr =
6221               MD->getParent()->getAttr<DLLExportAttr>()) {
6222         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6223         NewAttr->setInherited(true);
6224         NewDecl->addAttr(NewAttr);
6225       }
6226     }
6227   }
6228 }
6229
6230 /// Given that we are within the definition of the given function,
6231 /// will that definition behave like C99's 'inline', where the
6232 /// definition is discarded except for optimization purposes?
6233 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6234   // Try to avoid calling GetGVALinkageForFunction.
6235
6236   // All cases of this require the 'inline' keyword.
6237   if (!FD->isInlined()) return false;
6238
6239   // This is only possible in C++ with the gnu_inline attribute.
6240   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6241     return false;
6242
6243   // Okay, go ahead and call the relatively-more-expensive function.
6244   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6245 }
6246
6247 /// Determine whether a variable is extern "C" prior to attaching
6248 /// an initializer. We can't just call isExternC() here, because that
6249 /// will also compute and cache whether the declaration is externally
6250 /// visible, which might change when we attach the initializer.
6251 ///
6252 /// This can only be used if the declaration is known to not be a
6253 /// redeclaration of an internal linkage declaration.
6254 ///
6255 /// For instance:
6256 ///
6257 ///   auto x = []{};
6258 ///
6259 /// Attaching the initializer here makes this declaration not externally
6260 /// visible, because its type has internal linkage.
6261 ///
6262 /// FIXME: This is a hack.
6263 template<typename T>
6264 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6265   if (S.getLangOpts().CPlusPlus) {
6266     // In C++, the overloadable attribute negates the effects of extern "C".
6267     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6268       return false;
6269
6270     // So do CUDA's host/device attributes.
6271     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6272                                  D->template hasAttr<CUDAHostAttr>()))
6273       return false;
6274   }
6275   return D->isExternC();
6276 }
6277
6278 static bool shouldConsiderLinkage(const VarDecl *VD) {
6279   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6280   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6281       isa<OMPDeclareMapperDecl>(DC))
6282     return VD->hasExternalStorage();
6283   if (DC->isFileContext())
6284     return true;
6285   if (DC->isRecord())
6286     return false;
6287   llvm_unreachable("Unexpected context");
6288 }
6289
6290 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6291   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6292   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6293       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6294     return true;
6295   if (DC->isRecord())
6296     return false;
6297   llvm_unreachable("Unexpected context");
6298 }
6299
6300 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6301                           ParsedAttr::Kind Kind) {
6302   // Check decl attributes on the DeclSpec.
6303   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6304     return true;
6305
6306   // Walk the declarator structure, checking decl attributes that were in a type
6307   // position to the decl itself.
6308   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6309     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6310       return true;
6311   }
6312
6313   // Finally, check attributes on the decl itself.
6314   return PD.getAttributes().hasAttribute(Kind);
6315 }
6316
6317 /// Adjust the \c DeclContext for a function or variable that might be a
6318 /// function-local external declaration.
6319 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6320   if (!DC->isFunctionOrMethod())
6321     return false;
6322
6323   // If this is a local extern function or variable declared within a function
6324   // template, don't add it into the enclosing namespace scope until it is
6325   // instantiated; it might have a dependent type right now.
6326   if (DC->isDependentContext())
6327     return true;
6328
6329   // C++11 [basic.link]p7:
6330   //   When a block scope declaration of an entity with linkage is not found to
6331   //   refer to some other declaration, then that entity is a member of the
6332   //   innermost enclosing namespace.
6333   //
6334   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6335   // semantically-enclosing namespace, not a lexically-enclosing one.
6336   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6337     DC = DC->getParent();
6338   return true;
6339 }
6340
6341 /// Returns true if given declaration has external C language linkage.
6342 static bool isDeclExternC(const Decl *D) {
6343   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6344     return FD->isExternC();
6345   if (const auto *VD = dyn_cast<VarDecl>(D))
6346     return VD->isExternC();
6347
6348   llvm_unreachable("Unknown type of decl!");
6349 }
6350
6351 NamedDecl *Sema::ActOnVariableDeclarator(
6352     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6353     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6354     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6355   QualType R = TInfo->getType();
6356   DeclarationName Name = GetNameForDeclarator(D).getName();
6357
6358   IdentifierInfo *II = Name.getAsIdentifierInfo();
6359
6360   if (D.isDecompositionDeclarator()) {
6361     // Take the name of the first declarator as our name for diagnostic
6362     // purposes.
6363     auto &Decomp = D.getDecompositionDeclarator();
6364     if (!Decomp.bindings().empty()) {
6365       II = Decomp.bindings()[0].Name;
6366       Name = II;
6367     }
6368   } else if (!II) {
6369     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6370     return nullptr;
6371   }
6372
6373   if (getLangOpts().OpenCL) {
6374     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6375     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6376     // argument.
6377     if (R->isImageType() || R->isPipeType()) {
6378       Diag(D.getIdentifierLoc(),
6379            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6380           << R;
6381       D.setInvalidType();
6382       return nullptr;
6383     }
6384
6385     // OpenCL v1.2 s6.9.r:
6386     // The event type cannot be used to declare a program scope variable.
6387     // OpenCL v2.0 s6.9.q:
6388     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6389     if (NULL == S->getParent()) {
6390       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6391         Diag(D.getIdentifierLoc(),
6392              diag::err_invalid_type_for_program_scope_var) << R;
6393         D.setInvalidType();
6394         return nullptr;
6395       }
6396     }
6397
6398     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6399     QualType NR = R;
6400     while (NR->isPointerType()) {
6401       if (NR->isFunctionPointerType()) {
6402         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6403         D.setInvalidType();
6404         break;
6405       }
6406       NR = NR->getPointeeType();
6407     }
6408
6409     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6410       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6411       // half array type (unless the cl_khr_fp16 extension is enabled).
6412       if (Context.getBaseElementType(R)->isHalfType()) {
6413         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6414         D.setInvalidType();
6415       }
6416     }
6417
6418     if (R->isSamplerT()) {
6419       // OpenCL v1.2 s6.9.b p4:
6420       // The sampler type cannot be used with the __local and __global address
6421       // space qualifiers.
6422       if (R.getAddressSpace() == LangAS::opencl_local ||
6423           R.getAddressSpace() == LangAS::opencl_global) {
6424         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6425       }
6426
6427       // OpenCL v1.2 s6.12.14.1:
6428       // A global sampler must be declared with either the constant address
6429       // space qualifier or with the const qualifier.
6430       if (DC->isTranslationUnit() &&
6431           !(R.getAddressSpace() == LangAS::opencl_constant ||
6432           R.isConstQualified())) {
6433         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6434         D.setInvalidType();
6435       }
6436     }
6437
6438     // OpenCL v1.2 s6.9.r:
6439     // The event type cannot be used with the __local, __constant and __global
6440     // address space qualifiers.
6441     if (R->isEventT()) {
6442       if (R.getAddressSpace() != LangAS::opencl_private) {
6443         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6444         D.setInvalidType();
6445       }
6446     }
6447
6448     // C++ for OpenCL does not allow the thread_local storage qualifier.
6449     // OpenCL C does not support thread_local either, and
6450     // also reject all other thread storage class specifiers.
6451     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6452     if (TSC != TSCS_unspecified) {
6453       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6454       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6455            diag::err_opencl_unknown_type_specifier)
6456           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6457           << DeclSpec::getSpecifierName(TSC) << 1;
6458       D.setInvalidType();
6459       return nullptr;
6460     }
6461   }
6462
6463   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6464   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6465
6466   // dllimport globals without explicit storage class are treated as extern. We
6467   // have to change the storage class this early to get the right DeclContext.
6468   if (SC == SC_None && !DC->isRecord() &&
6469       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6470       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6471     SC = SC_Extern;
6472
6473   DeclContext *OriginalDC = DC;
6474   bool IsLocalExternDecl = SC == SC_Extern &&
6475                            adjustContextForLocalExternDecl(DC);
6476
6477   if (SCSpec == DeclSpec::SCS_mutable) {
6478     // mutable can only appear on non-static class members, so it's always
6479     // an error here
6480     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6481     D.setInvalidType();
6482     SC = SC_None;
6483   }
6484
6485   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6486       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6487                               D.getDeclSpec().getStorageClassSpecLoc())) {
6488     // In C++11, the 'register' storage class specifier is deprecated.
6489     // Suppress the warning in system macros, it's used in macros in some
6490     // popular C system headers, such as in glibc's htonl() macro.
6491     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6492          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6493                                    : diag::warn_deprecated_register)
6494       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6495   }
6496
6497   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6498
6499   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6500     // C99 6.9p2: The storage-class specifiers auto and register shall not
6501     // appear in the declaration specifiers in an external declaration.
6502     // Global Register+Asm is a GNU extension we support.
6503     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6504       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6505       D.setInvalidType();
6506     }
6507   }
6508
6509   bool IsMemberSpecialization = false;
6510   bool IsVariableTemplateSpecialization = false;
6511   bool IsPartialSpecialization = false;
6512   bool IsVariableTemplate = false;
6513   VarDecl *NewVD = nullptr;
6514   VarTemplateDecl *NewTemplate = nullptr;
6515   TemplateParameterList *TemplateParams = nullptr;
6516   if (!getLangOpts().CPlusPlus) {
6517     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6518                             II, R, TInfo, SC);
6519
6520     if (R->getContainedDeducedType())
6521       ParsingInitForAutoVars.insert(NewVD);
6522
6523     if (D.isInvalidType())
6524       NewVD->setInvalidDecl();
6525
6526     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6527         NewVD->hasLocalStorage())
6528       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6529                             NTCUC_AutoVar, NTCUK_Destruct);
6530   } else {
6531     bool Invalid = false;
6532
6533     if (DC->isRecord() && !CurContext->isRecord()) {
6534       // This is an out-of-line definition of a static data member.
6535       switch (SC) {
6536       case SC_None:
6537         break;
6538       case SC_Static:
6539         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6540              diag::err_static_out_of_line)
6541           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6542         break;
6543       case SC_Auto:
6544       case SC_Register:
6545       case SC_Extern:
6546         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6547         // to names of variables declared in a block or to function parameters.
6548         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6549         // of class members
6550
6551         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6552              diag::err_storage_class_for_static_member)
6553           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6554         break;
6555       case SC_PrivateExtern:
6556         llvm_unreachable("C storage class in c++!");
6557       }
6558     }
6559
6560     if (SC == SC_Static && CurContext->isRecord()) {
6561       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6562         if (RD->isLocalClass())
6563           Diag(D.getIdentifierLoc(),
6564                diag::err_static_data_member_not_allowed_in_local_class)
6565             << Name << RD->getDeclName();
6566
6567         // C++98 [class.union]p1: If a union contains a static data member,
6568         // the program is ill-formed. C++11 drops this restriction.
6569         if (RD->isUnion())
6570           Diag(D.getIdentifierLoc(),
6571                getLangOpts().CPlusPlus11
6572                  ? diag::warn_cxx98_compat_static_data_member_in_union
6573                  : diag::ext_static_data_member_in_union) << Name;
6574         // We conservatively disallow static data members in anonymous structs.
6575         else if (!RD->getDeclName())
6576           Diag(D.getIdentifierLoc(),
6577                diag::err_static_data_member_not_allowed_in_anon_struct)
6578             << Name << RD->isUnion();
6579       }
6580     }
6581
6582     // Match up the template parameter lists with the scope specifier, then
6583     // determine whether we have a template or a template specialization.
6584     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6585         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6586         D.getCXXScopeSpec(),
6587         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6588             ? D.getName().TemplateId
6589             : nullptr,
6590         TemplateParamLists,
6591         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6592
6593     if (TemplateParams) {
6594       if (!TemplateParams->size() &&
6595           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6596         // There is an extraneous 'template<>' for this variable. Complain
6597         // about it, but allow the declaration of the variable.
6598         Diag(TemplateParams->getTemplateLoc(),
6599              diag::err_template_variable_noparams)
6600           << II
6601           << SourceRange(TemplateParams->getTemplateLoc(),
6602                          TemplateParams->getRAngleLoc());
6603         TemplateParams = nullptr;
6604       } else {
6605         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6606           // This is an explicit specialization or a partial specialization.
6607           // FIXME: Check that we can declare a specialization here.
6608           IsVariableTemplateSpecialization = true;
6609           IsPartialSpecialization = TemplateParams->size() > 0;
6610         } else { // if (TemplateParams->size() > 0)
6611           // This is a template declaration.
6612           IsVariableTemplate = true;
6613
6614           // Check that we can declare a template here.
6615           if (CheckTemplateDeclScope(S, TemplateParams))
6616             return nullptr;
6617
6618           // Only C++1y supports variable templates (N3651).
6619           Diag(D.getIdentifierLoc(),
6620                getLangOpts().CPlusPlus14
6621                    ? diag::warn_cxx11_compat_variable_template
6622                    : diag::ext_variable_template);
6623         }
6624       }
6625     } else {
6626       assert((Invalid ||
6627               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6628              "should have a 'template<>' for this decl");
6629     }
6630
6631     if (IsVariableTemplateSpecialization) {
6632       SourceLocation TemplateKWLoc =
6633           TemplateParamLists.size() > 0
6634               ? TemplateParamLists[0]->getTemplateLoc()
6635               : SourceLocation();
6636       DeclResult Res = ActOnVarTemplateSpecialization(
6637           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6638           IsPartialSpecialization);
6639       if (Res.isInvalid())
6640         return nullptr;
6641       NewVD = cast<VarDecl>(Res.get());
6642       AddToScope = false;
6643     } else if (D.isDecompositionDeclarator()) {
6644       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6645                                         D.getIdentifierLoc(), R, TInfo, SC,
6646                                         Bindings);
6647     } else
6648       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6649                               D.getIdentifierLoc(), II, R, TInfo, SC);
6650
6651     // If this is supposed to be a variable template, create it as such.
6652     if (IsVariableTemplate) {
6653       NewTemplate =
6654           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6655                                   TemplateParams, NewVD);
6656       NewVD->setDescribedVarTemplate(NewTemplate);
6657     }
6658
6659     // If this decl has an auto type in need of deduction, make a note of the
6660     // Decl so we can diagnose uses of it in its own initializer.
6661     if (R->getContainedDeducedType())
6662       ParsingInitForAutoVars.insert(NewVD);
6663
6664     if (D.isInvalidType() || Invalid) {
6665       NewVD->setInvalidDecl();
6666       if (NewTemplate)
6667         NewTemplate->setInvalidDecl();
6668     }
6669
6670     SetNestedNameSpecifier(*this, NewVD, D);
6671
6672     // If we have any template parameter lists that don't directly belong to
6673     // the variable (matching the scope specifier), store them.
6674     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6675     if (TemplateParamLists.size() > VDTemplateParamLists)
6676       NewVD->setTemplateParameterListsInfo(
6677           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6678
6679     if (D.getDeclSpec().hasConstexprSpecifier()) {
6680       NewVD->setConstexpr(true);
6681       // C++1z [dcl.spec.constexpr]p1:
6682       //   A static data member declared with the constexpr specifier is
6683       //   implicitly an inline variable.
6684       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6685         NewVD->setImplicitlyInline();
6686       if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
6687         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6688              diag::err_constexpr_wrong_decl_kind)
6689             << /*consteval*/ 1;
6690     }
6691   }
6692
6693   if (D.getDeclSpec().isInlineSpecified()) {
6694     if (!getLangOpts().CPlusPlus) {
6695       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6696           << 0;
6697     } else if (CurContext->isFunctionOrMethod()) {
6698       // 'inline' is not allowed on block scope variable declaration.
6699       Diag(D.getDeclSpec().getInlineSpecLoc(),
6700            diag::err_inline_declaration_block_scope) << Name
6701         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6702     } else {
6703       Diag(D.getDeclSpec().getInlineSpecLoc(),
6704            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6705                                      : diag::ext_inline_variable);
6706       NewVD->setInlineSpecified();
6707     }
6708   }
6709
6710   // Set the lexical context. If the declarator has a C++ scope specifier, the
6711   // lexical context will be different from the semantic context.
6712   NewVD->setLexicalDeclContext(CurContext);
6713   if (NewTemplate)
6714     NewTemplate->setLexicalDeclContext(CurContext);
6715
6716   if (IsLocalExternDecl) {
6717     if (D.isDecompositionDeclarator())
6718       for (auto *B : Bindings)
6719         B->setLocalExternDecl();
6720     else
6721       NewVD->setLocalExternDecl();
6722   }
6723
6724   bool EmitTLSUnsupportedError = false;
6725   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6726     // C++11 [dcl.stc]p4:
6727     //   When thread_local is applied to a variable of block scope the
6728     //   storage-class-specifier static is implied if it does not appear
6729     //   explicitly.
6730     // Core issue: 'static' is not implied if the variable is declared
6731     //   'extern'.
6732     if (NewVD->hasLocalStorage() &&
6733         (SCSpec != DeclSpec::SCS_unspecified ||
6734          TSCS != DeclSpec::TSCS_thread_local ||
6735          !DC->isFunctionOrMethod()))
6736       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6737            diag::err_thread_non_global)
6738         << DeclSpec::getSpecifierName(TSCS);
6739     else if (!Context.getTargetInfo().isTLSSupported()) {
6740       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6741         // Postpone error emission until we've collected attributes required to
6742         // figure out whether it's a host or device variable and whether the
6743         // error should be ignored.
6744         EmitTLSUnsupportedError = true;
6745         // We still need to mark the variable as TLS so it shows up in AST with
6746         // proper storage class for other tools to use even if we're not going
6747         // to emit any code for it.
6748         NewVD->setTSCSpec(TSCS);
6749       } else
6750         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6751              diag::err_thread_unsupported);
6752     } else
6753       NewVD->setTSCSpec(TSCS);
6754   }
6755
6756   // C99 6.7.4p3
6757   //   An inline definition of a function with external linkage shall
6758   //   not contain a definition of a modifiable object with static or
6759   //   thread storage duration...
6760   // We only apply this when the function is required to be defined
6761   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6762   // that a local variable with thread storage duration still has to
6763   // be marked 'static'.  Also note that it's possible to get these
6764   // semantics in C++ using __attribute__((gnu_inline)).
6765   if (SC == SC_Static && S->getFnParent() != nullptr &&
6766       !NewVD->getType().isConstQualified()) {
6767     FunctionDecl *CurFD = getCurFunctionDecl();
6768     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6769       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6770            diag::warn_static_local_in_extern_inline);
6771       MaybeSuggestAddingStaticToDecl(CurFD);
6772     }
6773   }
6774
6775   if (D.getDeclSpec().isModulePrivateSpecified()) {
6776     if (IsVariableTemplateSpecialization)
6777       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6778           << (IsPartialSpecialization ? 1 : 0)
6779           << FixItHint::CreateRemoval(
6780                  D.getDeclSpec().getModulePrivateSpecLoc());
6781     else if (IsMemberSpecialization)
6782       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6783         << 2
6784         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6785     else if (NewVD->hasLocalStorage())
6786       Diag(NewVD->getLocation(), diag::err_module_private_local)
6787         << 0 << NewVD->getDeclName()
6788         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6789         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6790     else {
6791       NewVD->setModulePrivate();
6792       if (NewTemplate)
6793         NewTemplate->setModulePrivate();
6794       for (auto *B : Bindings)
6795         B->setModulePrivate();
6796     }
6797   }
6798
6799   // Handle attributes prior to checking for duplicates in MergeVarDecl
6800   ProcessDeclAttributes(S, NewVD, D);
6801
6802   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6803     if (EmitTLSUnsupportedError &&
6804         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6805          (getLangOpts().OpenMPIsDevice &&
6806           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6807       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6808            diag::err_thread_unsupported);
6809     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6810     // storage [duration]."
6811     if (SC == SC_None && S->getFnParent() != nullptr &&
6812         (NewVD->hasAttr<CUDASharedAttr>() ||
6813          NewVD->hasAttr<CUDAConstantAttr>())) {
6814       NewVD->setStorageClass(SC_Static);
6815     }
6816   }
6817
6818   // Ensure that dllimport globals without explicit storage class are treated as
6819   // extern. The storage class is set above using parsed attributes. Now we can
6820   // check the VarDecl itself.
6821   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6822          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6823          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6824
6825   // In auto-retain/release, infer strong retension for variables of
6826   // retainable type.
6827   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6828     NewVD->setInvalidDecl();
6829
6830   // Handle GNU asm-label extension (encoded as an attribute).
6831   if (Expr *E = (Expr*)D.getAsmLabel()) {
6832     // The parser guarantees this is a string.
6833     StringLiteral *SE = cast<StringLiteral>(E);
6834     StringRef Label = SE->getString();
6835     if (S->getFnParent() != nullptr) {
6836       switch (SC) {
6837       case SC_None:
6838       case SC_Auto:
6839         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6840         break;
6841       case SC_Register:
6842         // Local Named register
6843         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6844             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6845           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6846         break;
6847       case SC_Static:
6848       case SC_Extern:
6849       case SC_PrivateExtern:
6850         break;
6851       }
6852     } else if (SC == SC_Register) {
6853       // Global Named register
6854       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6855         const auto &TI = Context.getTargetInfo();
6856         bool HasSizeMismatch;
6857
6858         if (!TI.isValidGCCRegisterName(Label))
6859           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6860         else if (!TI.validateGlobalRegisterVariable(Label,
6861                                                     Context.getTypeSize(R),
6862                                                     HasSizeMismatch))
6863           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6864         else if (HasSizeMismatch)
6865           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6866       }
6867
6868       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6869         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6870         NewVD->setInvalidDecl(true);
6871       }
6872     }
6873
6874     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6875                                                 Context, Label, 0));
6876   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6877     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6878       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6879     if (I != ExtnameUndeclaredIdentifiers.end()) {
6880       if (isDeclExternC(NewVD)) {
6881         NewVD->addAttr(I->second);
6882         ExtnameUndeclaredIdentifiers.erase(I);
6883       } else
6884         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6885             << /*Variable*/1 << NewVD;
6886     }
6887   }
6888
6889   // Find the shadowed declaration before filtering for scope.
6890   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6891                                 ? getShadowedDeclaration(NewVD, Previous)
6892                                 : nullptr;
6893
6894   // Don't consider existing declarations that are in a different
6895   // scope and are out-of-semantic-context declarations (if the new
6896   // declaration has linkage).
6897   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6898                        D.getCXXScopeSpec().isNotEmpty() ||
6899                        IsMemberSpecialization ||
6900                        IsVariableTemplateSpecialization);
6901
6902   // Check whether the previous declaration is in the same block scope. This
6903   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6904   if (getLangOpts().CPlusPlus &&
6905       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6906     NewVD->setPreviousDeclInSameBlockScope(
6907         Previous.isSingleResult() && !Previous.isShadowed() &&
6908         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6909
6910   if (!getLangOpts().CPlusPlus) {
6911     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6912   } else {
6913     // If this is an explicit specialization of a static data member, check it.
6914     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6915         CheckMemberSpecialization(NewVD, Previous))
6916       NewVD->setInvalidDecl();
6917
6918     // Merge the decl with the existing one if appropriate.
6919     if (!Previous.empty()) {
6920       if (Previous.isSingleResult() &&
6921           isa<FieldDecl>(Previous.getFoundDecl()) &&
6922           D.getCXXScopeSpec().isSet()) {
6923         // The user tried to define a non-static data member
6924         // out-of-line (C++ [dcl.meaning]p1).
6925         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6926           << D.getCXXScopeSpec().getRange();
6927         Previous.clear();
6928         NewVD->setInvalidDecl();
6929       }
6930     } else if (D.getCXXScopeSpec().isSet()) {
6931       // No previous declaration in the qualifying scope.
6932       Diag(D.getIdentifierLoc(), diag::err_no_member)
6933         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6934         << D.getCXXScopeSpec().getRange();
6935       NewVD->setInvalidDecl();
6936     }
6937
6938     if (!IsVariableTemplateSpecialization)
6939       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6940
6941     if (NewTemplate) {
6942       VarTemplateDecl *PrevVarTemplate =
6943           NewVD->getPreviousDecl()
6944               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6945               : nullptr;
6946
6947       // Check the template parameter list of this declaration, possibly
6948       // merging in the template parameter list from the previous variable
6949       // template declaration.
6950       if (CheckTemplateParameterList(
6951               TemplateParams,
6952               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6953                               : nullptr,
6954               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6955                DC->isDependentContext())
6956                   ? TPC_ClassTemplateMember
6957                   : TPC_VarTemplate))
6958         NewVD->setInvalidDecl();
6959
6960       // If we are providing an explicit specialization of a static variable
6961       // template, make a note of that.
6962       if (PrevVarTemplate &&
6963           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6964         PrevVarTemplate->setMemberSpecialization();
6965     }
6966   }
6967
6968   // Diagnose shadowed variables iff this isn't a redeclaration.
6969   if (ShadowedDecl && !D.isRedeclaration())
6970     CheckShadow(NewVD, ShadowedDecl, Previous);
6971
6972   ProcessPragmaWeak(S, NewVD);
6973
6974   // If this is the first declaration of an extern C variable, update
6975   // the map of such variables.
6976   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6977       isIncompleteDeclExternC(*this, NewVD))
6978     RegisterLocallyScopedExternCDecl(NewVD, S);
6979
6980   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6981     Decl *ManglingContextDecl;
6982     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6983             NewVD->getDeclContext(), ManglingContextDecl)) {
6984       Context.setManglingNumber(
6985           NewVD, MCtx->getManglingNumber(
6986                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6987       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6988     }
6989   }
6990
6991   // Special handling of variable named 'main'.
6992   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6993       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6994       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6995
6996     // C++ [basic.start.main]p3
6997     // A program that declares a variable main at global scope is ill-formed.
6998     if (getLangOpts().CPlusPlus)
6999       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7000
7001     // In C, and external-linkage variable named main results in undefined
7002     // behavior.
7003     else if (NewVD->hasExternalFormalLinkage())
7004       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7005   }
7006
7007   if (D.isRedeclaration() && !Previous.empty()) {
7008     NamedDecl *Prev = Previous.getRepresentativeDecl();
7009     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7010                                    D.isFunctionDefinition());
7011   }
7012
7013   if (NewTemplate) {
7014     if (NewVD->isInvalidDecl())
7015       NewTemplate->setInvalidDecl();
7016     ActOnDocumentableDecl(NewTemplate);
7017     return NewTemplate;
7018   }
7019
7020   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7021     CompleteMemberSpecialization(NewVD, Previous);
7022
7023   return NewVD;
7024 }
7025
7026 /// Enum describing the %select options in diag::warn_decl_shadow.
7027 enum ShadowedDeclKind {
7028   SDK_Local,
7029   SDK_Global,
7030   SDK_StaticMember,
7031   SDK_Field,
7032   SDK_Typedef,
7033   SDK_Using
7034 };
7035
7036 /// Determine what kind of declaration we're shadowing.
7037 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7038                                                 const DeclContext *OldDC) {
7039   if (isa<TypeAliasDecl>(ShadowedDecl))
7040     return SDK_Using;
7041   else if (isa<TypedefDecl>(ShadowedDecl))
7042     return SDK_Typedef;
7043   else if (isa<RecordDecl>(OldDC))
7044     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7045
7046   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7047 }
7048
7049 /// Return the location of the capture if the given lambda captures the given
7050 /// variable \p VD, or an invalid source location otherwise.
7051 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7052                                          const VarDecl *VD) {
7053   for (const Capture &Capture : LSI->Captures) {
7054     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7055       return Capture.getLocation();
7056   }
7057   return SourceLocation();
7058 }
7059
7060 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7061                                      const LookupResult &R) {
7062   // Only diagnose if we're shadowing an unambiguous field or variable.
7063   if (R.getResultKind() != LookupResult::Found)
7064     return false;
7065
7066   // Return false if warning is ignored.
7067   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7068 }
7069
7070 /// Return the declaration shadowed by the given variable \p D, or null
7071 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7072 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7073                                         const LookupResult &R) {
7074   if (!shouldWarnIfShadowedDecl(Diags, R))
7075     return nullptr;
7076
7077   // Don't diagnose declarations at file scope.
7078   if (D->hasGlobalStorage())
7079     return nullptr;
7080
7081   NamedDecl *ShadowedDecl = R.getFoundDecl();
7082   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7083              ? ShadowedDecl
7084              : nullptr;
7085 }
7086
7087 /// Return the declaration shadowed by the given typedef \p D, or null
7088 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7089 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7090                                         const LookupResult &R) {
7091   // Don't warn if typedef declaration is part of a class
7092   if (D->getDeclContext()->isRecord())
7093     return nullptr;
7094
7095   if (!shouldWarnIfShadowedDecl(Diags, R))
7096     return nullptr;
7097
7098   NamedDecl *ShadowedDecl = R.getFoundDecl();
7099   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7100 }
7101
7102 /// Diagnose variable or built-in function shadowing.  Implements
7103 /// -Wshadow.
7104 ///
7105 /// This method is called whenever a VarDecl is added to a "useful"
7106 /// scope.
7107 ///
7108 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7109 /// \param R the lookup of the name
7110 ///
7111 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7112                        const LookupResult &R) {
7113   DeclContext *NewDC = D->getDeclContext();
7114
7115   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7116     // Fields are not shadowed by variables in C++ static methods.
7117     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7118       if (MD->isStatic())
7119         return;
7120
7121     // Fields shadowed by constructor parameters are a special case. Usually
7122     // the constructor initializes the field with the parameter.
7123     if (isa<CXXConstructorDecl>(NewDC))
7124       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7125         // Remember that this was shadowed so we can either warn about its
7126         // modification or its existence depending on warning settings.
7127         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7128         return;
7129       }
7130   }
7131
7132   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7133     if (shadowedVar->isExternC()) {
7134       // For shadowing external vars, make sure that we point to the global
7135       // declaration, not a locally scoped extern declaration.
7136       for (auto I : shadowedVar->redecls())
7137         if (I->isFileVarDecl()) {
7138           ShadowedDecl = I;
7139           break;
7140         }
7141     }
7142
7143   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7144
7145   unsigned WarningDiag = diag::warn_decl_shadow;
7146   SourceLocation CaptureLoc;
7147   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7148       isa<CXXMethodDecl>(NewDC)) {
7149     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7150       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7151         if (RD->getLambdaCaptureDefault() == LCD_None) {
7152           // Try to avoid warnings for lambdas with an explicit capture list.
7153           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7154           // Warn only when the lambda captures the shadowed decl explicitly.
7155           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7156           if (CaptureLoc.isInvalid())
7157             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7158         } else {
7159           // Remember that this was shadowed so we can avoid the warning if the
7160           // shadowed decl isn't captured and the warning settings allow it.
7161           cast<LambdaScopeInfo>(getCurFunction())
7162               ->ShadowingDecls.push_back(
7163                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7164           return;
7165         }
7166       }
7167
7168       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7169         // A variable can't shadow a local variable in an enclosing scope, if
7170         // they are separated by a non-capturing declaration context.
7171         for (DeclContext *ParentDC = NewDC;
7172              ParentDC && !ParentDC->Equals(OldDC);
7173              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7174           // Only block literals, captured statements, and lambda expressions
7175           // can capture; other scopes don't.
7176           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7177               !isLambdaCallOperator(ParentDC)) {
7178             return;
7179           }
7180         }
7181       }
7182     }
7183   }
7184
7185   // Only warn about certain kinds of shadowing for class members.
7186   if (NewDC && NewDC->isRecord()) {
7187     // In particular, don't warn about shadowing non-class members.
7188     if (!OldDC->isRecord())
7189       return;
7190
7191     // TODO: should we warn about static data members shadowing
7192     // static data members from base classes?
7193
7194     // TODO: don't diagnose for inaccessible shadowed members.
7195     // This is hard to do perfectly because we might friend the
7196     // shadowing context, but that's just a false negative.
7197   }
7198
7199
7200   DeclarationName Name = R.getLookupName();
7201
7202   // Emit warning and note.
7203   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7204     return;
7205   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7206   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7207   if (!CaptureLoc.isInvalid())
7208     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7209         << Name << /*explicitly*/ 1;
7210   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7211 }
7212
7213 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7214 /// when these variables are captured by the lambda.
7215 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7216   for (const auto &Shadow : LSI->ShadowingDecls) {
7217     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7218     // Try to avoid the warning when the shadowed decl isn't captured.
7219     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7220     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7221     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7222                                        ? diag::warn_decl_shadow_uncaptured_local
7223                                        : diag::warn_decl_shadow)
7224         << Shadow.VD->getDeclName()
7225         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7226     if (!CaptureLoc.isInvalid())
7227       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7228           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7229     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7230   }
7231 }
7232
7233 /// Check -Wshadow without the advantage of a previous lookup.
7234 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7235   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7236     return;
7237
7238   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7239                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7240   LookupName(R, S);
7241   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7242     CheckShadow(D, ShadowedDecl, R);
7243 }
7244
7245 /// Check if 'E', which is an expression that is about to be modified, refers
7246 /// to a constructor parameter that shadows a field.
7247 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7248   // Quickly ignore expressions that can't be shadowing ctor parameters.
7249   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7250     return;
7251   E = E->IgnoreParenImpCasts();
7252   auto *DRE = dyn_cast<DeclRefExpr>(E);
7253   if (!DRE)
7254     return;
7255   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7256   auto I = ShadowingDecls.find(D);
7257   if (I == ShadowingDecls.end())
7258     return;
7259   const NamedDecl *ShadowedDecl = I->second;
7260   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7261   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7262   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7263   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7264
7265   // Avoid issuing multiple warnings about the same decl.
7266   ShadowingDecls.erase(I);
7267 }
7268
7269 /// Check for conflict between this global or extern "C" declaration and
7270 /// previous global or extern "C" declarations. This is only used in C++.
7271 template<typename T>
7272 static bool checkGlobalOrExternCConflict(
7273     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7274   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7275   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7276
7277   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7278     // The common case: this global doesn't conflict with any extern "C"
7279     // declaration.
7280     return false;
7281   }
7282
7283   if (Prev) {
7284     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7285       // Both the old and new declarations have C language linkage. This is a
7286       // redeclaration.
7287       Previous.clear();
7288       Previous.addDecl(Prev);
7289       return true;
7290     }
7291
7292     // This is a global, non-extern "C" declaration, and there is a previous
7293     // non-global extern "C" declaration. Diagnose if this is a variable
7294     // declaration.
7295     if (!isa<VarDecl>(ND))
7296       return false;
7297   } else {
7298     // The declaration is extern "C". Check for any declaration in the
7299     // translation unit which might conflict.
7300     if (IsGlobal) {
7301       // We have already performed the lookup into the translation unit.
7302       IsGlobal = false;
7303       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7304            I != E; ++I) {
7305         if (isa<VarDecl>(*I)) {
7306           Prev = *I;
7307           break;
7308         }
7309       }
7310     } else {
7311       DeclContext::lookup_result R =
7312           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7313       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7314            I != E; ++I) {
7315         if (isa<VarDecl>(*I)) {
7316           Prev = *I;
7317           break;
7318         }
7319         // FIXME: If we have any other entity with this name in global scope,
7320         // the declaration is ill-formed, but that is a defect: it breaks the
7321         // 'stat' hack, for instance. Only variables can have mangled name
7322         // clashes with extern "C" declarations, so only they deserve a
7323         // diagnostic.
7324       }
7325     }
7326
7327     if (!Prev)
7328       return false;
7329   }
7330
7331   // Use the first declaration's location to ensure we point at something which
7332   // is lexically inside an extern "C" linkage-spec.
7333   assert(Prev && "should have found a previous declaration to diagnose");
7334   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7335     Prev = FD->getFirstDecl();
7336   else
7337     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7338
7339   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7340     << IsGlobal << ND;
7341   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7342     << IsGlobal;
7343   return false;
7344 }
7345
7346 /// Apply special rules for handling extern "C" declarations. Returns \c true
7347 /// if we have found that this is a redeclaration of some prior entity.
7348 ///
7349 /// Per C++ [dcl.link]p6:
7350 ///   Two declarations [for a function or variable] with C language linkage
7351 ///   with the same name that appear in different scopes refer to the same
7352 ///   [entity]. An entity with C language linkage shall not be declared with
7353 ///   the same name as an entity in global scope.
7354 template<typename T>
7355 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7356                                                   LookupResult &Previous) {
7357   if (!S.getLangOpts().CPlusPlus) {
7358     // In C, when declaring a global variable, look for a corresponding 'extern'
7359     // variable declared in function scope. We don't need this in C++, because
7360     // we find local extern decls in the surrounding file-scope DeclContext.
7361     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7362       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7363         Previous.clear();
7364         Previous.addDecl(Prev);
7365         return true;
7366       }
7367     }
7368     return false;
7369   }
7370
7371   // A declaration in the translation unit can conflict with an extern "C"
7372   // declaration.
7373   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7374     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7375
7376   // An extern "C" declaration can conflict with a declaration in the
7377   // translation unit or can be a redeclaration of an extern "C" declaration
7378   // in another scope.
7379   if (isIncompleteDeclExternC(S,ND))
7380     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7381
7382   // Neither global nor extern "C": nothing to do.
7383   return false;
7384 }
7385
7386 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7387   // If the decl is already known invalid, don't check it.
7388   if (NewVD->isInvalidDecl())
7389     return;
7390
7391   QualType T = NewVD->getType();
7392
7393   // Defer checking an 'auto' type until its initializer is attached.
7394   if (T->isUndeducedType())
7395     return;
7396
7397   if (NewVD->hasAttrs())
7398     CheckAlignasUnderalignment(NewVD);
7399
7400   if (T->isObjCObjectType()) {
7401     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7402       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7403     T = Context.getObjCObjectPointerType(T);
7404     NewVD->setType(T);
7405   }
7406
7407   // Emit an error if an address space was applied to decl with local storage.
7408   // This includes arrays of objects with address space qualifiers, but not
7409   // automatic variables that point to other address spaces.
7410   // ISO/IEC TR 18037 S5.1.2
7411   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7412       T.getAddressSpace() != LangAS::Default) {
7413     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7414     NewVD->setInvalidDecl();
7415     return;
7416   }
7417
7418   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7419   // scope.
7420   if (getLangOpts().OpenCLVersion == 120 &&
7421       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7422       NewVD->isStaticLocal()) {
7423     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7424     NewVD->setInvalidDecl();
7425     return;
7426   }
7427
7428   if (getLangOpts().OpenCL) {
7429     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7430     if (NewVD->hasAttr<BlocksAttr>()) {
7431       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7432       return;
7433     }
7434
7435     if (T->isBlockPointerType()) {
7436       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7437       // can't use 'extern' storage class.
7438       if (!T.isConstQualified()) {
7439         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7440             << 0 /*const*/;
7441         NewVD->setInvalidDecl();
7442         return;
7443       }
7444       if (NewVD->hasExternalStorage()) {
7445         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7446         NewVD->setInvalidDecl();
7447         return;
7448       }
7449     }
7450     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7451     // __constant address space.
7452     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7453     // variables inside a function can also be declared in the global
7454     // address space.
7455     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7456     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7457     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7458         NewVD->hasExternalStorage()) {
7459       if (!T->isSamplerT() &&
7460           !(T.getAddressSpace() == LangAS::opencl_constant ||
7461             (T.getAddressSpace() == LangAS::opencl_global &&
7462              (getLangOpts().OpenCLVersion == 200 ||
7463               getLangOpts().OpenCLCPlusPlus)))) {
7464         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7465         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7466           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7467               << Scope << "global or constant";
7468         else
7469           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7470               << Scope << "constant";
7471         NewVD->setInvalidDecl();
7472         return;
7473       }
7474     } else {
7475       if (T.getAddressSpace() == LangAS::opencl_global) {
7476         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7477             << 1 /*is any function*/ << "global";
7478         NewVD->setInvalidDecl();
7479         return;
7480       }
7481       if (T.getAddressSpace() == LangAS::opencl_constant ||
7482           T.getAddressSpace() == LangAS::opencl_local) {
7483         FunctionDecl *FD = getCurFunctionDecl();
7484         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7485         // in functions.
7486         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7487           if (T.getAddressSpace() == LangAS::opencl_constant)
7488             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7489                 << 0 /*non-kernel only*/ << "constant";
7490           else
7491             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7492                 << 0 /*non-kernel only*/ << "local";
7493           NewVD->setInvalidDecl();
7494           return;
7495         }
7496         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7497         // in the outermost scope of a kernel function.
7498         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7499           if (!getCurScope()->isFunctionScope()) {
7500             if (T.getAddressSpace() == LangAS::opencl_constant)
7501               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7502                   << "constant";
7503             else
7504               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7505                   << "local";
7506             NewVD->setInvalidDecl();
7507             return;
7508           }
7509         }
7510       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7511                  // If we are parsing a template we didn't deduce an addr
7512                  // space yet.
7513                  T.getAddressSpace() != LangAS::Default) {
7514         // Do not allow other address spaces on automatic variable.
7515         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7516         NewVD->setInvalidDecl();
7517         return;
7518       }
7519     }
7520   }
7521
7522   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7523       && !NewVD->hasAttr<BlocksAttr>()) {
7524     if (getLangOpts().getGC() != LangOptions::NonGC)
7525       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7526     else {
7527       assert(!getLangOpts().ObjCAutoRefCount);
7528       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7529     }
7530   }
7531
7532   bool isVM = T->isVariablyModifiedType();
7533   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7534       NewVD->hasAttr<BlocksAttr>())
7535     setFunctionHasBranchProtectedScope();
7536
7537   if ((isVM && NewVD->hasLinkage()) ||
7538       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7539     bool SizeIsNegative;
7540     llvm::APSInt Oversized;
7541     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7542         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7543     QualType FixedT;
7544     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7545       FixedT = FixedTInfo->getType();
7546     else if (FixedTInfo) {
7547       // Type and type-as-written are canonically different. We need to fix up
7548       // both types separately.
7549       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7550                                                    Oversized);
7551     }
7552     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7553       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7554       // FIXME: This won't give the correct result for
7555       // int a[10][n];
7556       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7557
7558       if (NewVD->isFileVarDecl())
7559         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7560         << SizeRange;
7561       else if (NewVD->isStaticLocal())
7562         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7563         << SizeRange;
7564       else
7565         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7566         << SizeRange;
7567       NewVD->setInvalidDecl();
7568       return;
7569     }
7570
7571     if (!FixedTInfo) {
7572       if (NewVD->isFileVarDecl())
7573         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7574       else
7575         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7576       NewVD->setInvalidDecl();
7577       return;
7578     }
7579
7580     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7581     NewVD->setType(FixedT);
7582     NewVD->setTypeSourceInfo(FixedTInfo);
7583   }
7584
7585   if (T->isVoidType()) {
7586     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7587     //                    of objects and functions.
7588     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7589       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7590         << T;
7591       NewVD->setInvalidDecl();
7592       return;
7593     }
7594   }
7595
7596   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7597     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7598     NewVD->setInvalidDecl();
7599     return;
7600   }
7601
7602   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7603     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7604     NewVD->setInvalidDecl();
7605     return;
7606   }
7607
7608   if (NewVD->isConstexpr() && !T->isDependentType() &&
7609       RequireLiteralType(NewVD->getLocation(), T,
7610                          diag::err_constexpr_var_non_literal)) {
7611     NewVD->setInvalidDecl();
7612     return;
7613   }
7614 }
7615
7616 /// Perform semantic checking on a newly-created variable
7617 /// declaration.
7618 ///
7619 /// This routine performs all of the type-checking required for a
7620 /// variable declaration once it has been built. It is used both to
7621 /// check variables after they have been parsed and their declarators
7622 /// have been translated into a declaration, and to check variables
7623 /// that have been instantiated from a template.
7624 ///
7625 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7626 ///
7627 /// Returns true if the variable declaration is a redeclaration.
7628 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7629   CheckVariableDeclarationType(NewVD);
7630
7631   // If the decl is already known invalid, don't check it.
7632   if (NewVD->isInvalidDecl())
7633     return false;
7634
7635   // If we did not find anything by this name, look for a non-visible
7636   // extern "C" declaration with the same name.
7637   if (Previous.empty() &&
7638       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7639     Previous.setShadowed();
7640
7641   if (!Previous.empty()) {
7642     MergeVarDecl(NewVD, Previous);
7643     return true;
7644   }
7645   return false;
7646 }
7647
7648 namespace {
7649 struct FindOverriddenMethod {
7650   Sema *S;
7651   CXXMethodDecl *Method;
7652
7653   /// Member lookup function that determines whether a given C++
7654   /// method overrides a method in a base class, to be used with
7655   /// CXXRecordDecl::lookupInBases().
7656   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7657     RecordDecl *BaseRecord =
7658         Specifier->getType()->getAs<RecordType>()->getDecl();
7659
7660     DeclarationName Name = Method->getDeclName();
7661
7662     // FIXME: Do we care about other names here too?
7663     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7664       // We really want to find the base class destructor here.
7665       QualType T = S->Context.getTypeDeclType(BaseRecord);
7666       CanQualType CT = S->Context.getCanonicalType(T);
7667
7668       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7669     }
7670
7671     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7672          Path.Decls = Path.Decls.slice(1)) {
7673       NamedDecl *D = Path.Decls.front();
7674       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7675         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7676           return true;
7677       }
7678     }
7679
7680     return false;
7681   }
7682 };
7683
7684 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7685 } // end anonymous namespace
7686
7687 /// Report an error regarding overriding, along with any relevant
7688 /// overridden methods.
7689 ///
7690 /// \param DiagID the primary error to report.
7691 /// \param MD the overriding method.
7692 /// \param OEK which overrides to include as notes.
7693 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7694                             OverrideErrorKind OEK = OEK_All) {
7695   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7696   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7697     // This check (& the OEK parameter) could be replaced by a predicate, but
7698     // without lambdas that would be overkill. This is still nicer than writing
7699     // out the diag loop 3 times.
7700     if ((OEK == OEK_All) ||
7701         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7702         (OEK == OEK_Deleted && O->isDeleted()))
7703       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7704   }
7705 }
7706
7707 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7708 /// and if so, check that it's a valid override and remember it.
7709 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7710   // Look for methods in base classes that this method might override.
7711   CXXBasePaths Paths;
7712   FindOverriddenMethod FOM;
7713   FOM.Method = MD;
7714   FOM.S = this;
7715   bool hasDeletedOverridenMethods = false;
7716   bool hasNonDeletedOverridenMethods = false;
7717   bool AddedAny = false;
7718   if (DC->lookupInBases(FOM, Paths)) {
7719     for (auto *I : Paths.found_decls()) {
7720       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7721         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7722         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7723             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7724             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7725             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7726           hasDeletedOverridenMethods |= OldMD->isDeleted();
7727           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7728           AddedAny = true;
7729         }
7730       }
7731     }
7732   }
7733
7734   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7735     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7736   }
7737   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7738     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7739   }
7740
7741   return AddedAny;
7742 }
7743
7744 namespace {
7745   // Struct for holding all of the extra arguments needed by
7746   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7747   struct ActOnFDArgs {
7748     Scope *S;
7749     Declarator &D;
7750     MultiTemplateParamsArg TemplateParamLists;
7751     bool AddToScope;
7752   };
7753 } // end anonymous namespace
7754
7755 namespace {
7756
7757 // Callback to only accept typo corrections that have a non-zero edit distance.
7758 // Also only accept corrections that have the same parent decl.
7759 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7760  public:
7761   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7762                             CXXRecordDecl *Parent)
7763       : Context(Context), OriginalFD(TypoFD),
7764         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7765
7766   bool ValidateCandidate(const TypoCorrection &candidate) override {
7767     if (candidate.getEditDistance() == 0)
7768       return false;
7769
7770     SmallVector<unsigned, 1> MismatchedParams;
7771     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7772                                           CDeclEnd = candidate.end();
7773          CDecl != CDeclEnd; ++CDecl) {
7774       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7775
7776       if (FD && !FD->hasBody() &&
7777           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7778         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7779           CXXRecordDecl *Parent = MD->getParent();
7780           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7781             return true;
7782         } else if (!ExpectedParent) {
7783           return true;
7784         }
7785       }
7786     }
7787
7788     return false;
7789   }
7790
7791   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7792     return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7793   }
7794
7795  private:
7796   ASTContext &Context;
7797   FunctionDecl *OriginalFD;
7798   CXXRecordDecl *ExpectedParent;
7799 };
7800
7801 } // end anonymous namespace
7802
7803 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7804   TypoCorrectedFunctionDefinitions.insert(F);
7805 }
7806
7807 /// Generate diagnostics for an invalid function redeclaration.
7808 ///
7809 /// This routine handles generating the diagnostic messages for an invalid
7810 /// function redeclaration, including finding possible similar declarations
7811 /// or performing typo correction if there are no previous declarations with
7812 /// the same name.
7813 ///
7814 /// Returns a NamedDecl iff typo correction was performed and substituting in
7815 /// the new declaration name does not cause new errors.
7816 static NamedDecl *DiagnoseInvalidRedeclaration(
7817     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7818     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7819   DeclarationName Name = NewFD->getDeclName();
7820   DeclContext *NewDC = NewFD->getDeclContext();
7821   SmallVector<unsigned, 1> MismatchedParams;
7822   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7823   TypoCorrection Correction;
7824   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7825   unsigned DiagMsg =
7826     IsLocalFriend ? diag::err_no_matching_local_friend :
7827     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7828     diag::err_member_decl_does_not_match;
7829   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7830                     IsLocalFriend ? Sema::LookupLocalFriendName
7831                                   : Sema::LookupOrdinaryName,
7832                     Sema::ForVisibleRedeclaration);
7833
7834   NewFD->setInvalidDecl();
7835   if (IsLocalFriend)
7836     SemaRef.LookupName(Prev, S);
7837   else
7838     SemaRef.LookupQualifiedName(Prev, NewDC);
7839   assert(!Prev.isAmbiguous() &&
7840          "Cannot have an ambiguity in previous-declaration lookup");
7841   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7842   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7843                                 MD ? MD->getParent() : nullptr);
7844   if (!Prev.empty()) {
7845     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7846          Func != FuncEnd; ++Func) {
7847       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7848       if (FD &&
7849           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7850         // Add 1 to the index so that 0 can mean the mismatch didn't
7851         // involve a parameter
7852         unsigned ParamNum =
7853             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7854         NearMatches.push_back(std::make_pair(FD, ParamNum));
7855       }
7856     }
7857   // If the qualified name lookup yielded nothing, try typo correction
7858   } else if ((Correction = SemaRef.CorrectTypo(
7859                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7860                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7861                   IsLocalFriend ? nullptr : NewDC))) {
7862     // Set up everything for the call to ActOnFunctionDeclarator
7863     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7864                               ExtraArgs.D.getIdentifierLoc());
7865     Previous.clear();
7866     Previous.setLookupName(Correction.getCorrection());
7867     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7868                                     CDeclEnd = Correction.end();
7869          CDecl != CDeclEnd; ++CDecl) {
7870       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7871       if (FD && !FD->hasBody() &&
7872           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7873         Previous.addDecl(FD);
7874       }
7875     }
7876     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7877
7878     NamedDecl *Result;
7879     // Retry building the function declaration with the new previous
7880     // declarations, and with errors suppressed.
7881     {
7882       // Trap errors.
7883       Sema::SFINAETrap Trap(SemaRef);
7884
7885       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7886       // pieces need to verify the typo-corrected C++ declaration and hopefully
7887       // eliminate the need for the parameter pack ExtraArgs.
7888       Result = SemaRef.ActOnFunctionDeclarator(
7889           ExtraArgs.S, ExtraArgs.D,
7890           Correction.getCorrectionDecl()->getDeclContext(),
7891           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7892           ExtraArgs.AddToScope);
7893
7894       if (Trap.hasErrorOccurred())
7895         Result = nullptr;
7896     }
7897
7898     if (Result) {
7899       // Determine which correction we picked.
7900       Decl *Canonical = Result->getCanonicalDecl();
7901       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7902            I != E; ++I)
7903         if ((*I)->getCanonicalDecl() == Canonical)
7904           Correction.setCorrectionDecl(*I);
7905
7906       // Let Sema know about the correction.
7907       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7908       SemaRef.diagnoseTypo(
7909           Correction,
7910           SemaRef.PDiag(IsLocalFriend
7911                           ? diag::err_no_matching_local_friend_suggest
7912                           : diag::err_member_decl_does_not_match_suggest)
7913             << Name << NewDC << IsDefinition);
7914       return Result;
7915     }
7916
7917     // Pretend the typo correction never occurred
7918     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7919                               ExtraArgs.D.getIdentifierLoc());
7920     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7921     Previous.clear();
7922     Previous.setLookupName(Name);
7923   }
7924
7925   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7926       << Name << NewDC << IsDefinition << NewFD->getLocation();
7927
7928   bool NewFDisConst = false;
7929   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7930     NewFDisConst = NewMD->isConst();
7931
7932   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7933        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7934        NearMatch != NearMatchEnd; ++NearMatch) {
7935     FunctionDecl *FD = NearMatch->first;
7936     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7937     bool FDisConst = MD && MD->isConst();
7938     bool IsMember = MD || !IsLocalFriend;
7939
7940     // FIXME: These notes are poorly worded for the local friend case.
7941     if (unsigned Idx = NearMatch->second) {
7942       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7943       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7944       if (Loc.isInvalid()) Loc = FD->getLocation();
7945       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7946                                  : diag::note_local_decl_close_param_match)
7947         << Idx << FDParam->getType()
7948         << NewFD->getParamDecl(Idx - 1)->getType();
7949     } else if (FDisConst != NewFDisConst) {
7950       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7951           << NewFDisConst << FD->getSourceRange().getEnd();
7952     } else
7953       SemaRef.Diag(FD->getLocation(),
7954                    IsMember ? diag::note_member_def_close_match
7955                             : diag::note_local_decl_close_match);
7956   }
7957   return nullptr;
7958 }
7959
7960 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7961   switch (D.getDeclSpec().getStorageClassSpec()) {
7962   default: llvm_unreachable("Unknown storage class!");
7963   case DeclSpec::SCS_auto:
7964   case DeclSpec::SCS_register:
7965   case DeclSpec::SCS_mutable:
7966     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7967                  diag::err_typecheck_sclass_func);
7968     D.getMutableDeclSpec().ClearStorageClassSpecs();
7969     D.setInvalidType();
7970     break;
7971   case DeclSpec::SCS_unspecified: break;
7972   case DeclSpec::SCS_extern:
7973     if (D.getDeclSpec().isExternInLinkageSpec())
7974       return SC_None;
7975     return SC_Extern;
7976   case DeclSpec::SCS_static: {
7977     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7978       // C99 6.7.1p5:
7979       //   The declaration of an identifier for a function that has
7980       //   block scope shall have no explicit storage-class specifier
7981       //   other than extern
7982       // See also (C++ [dcl.stc]p4).
7983       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7984                    diag::err_static_block_func);
7985       break;
7986     } else
7987       return SC_Static;
7988   }
7989   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7990   }
7991
7992   // No explicit storage class has already been returned
7993   return SC_None;
7994 }
7995
7996 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7997                                            DeclContext *DC, QualType &R,
7998                                            TypeSourceInfo *TInfo,
7999                                            StorageClass SC,
8000                                            bool &IsVirtualOkay) {
8001   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8002   DeclarationName Name = NameInfo.getName();
8003
8004   FunctionDecl *NewFD = nullptr;
8005   bool isInline = D.getDeclSpec().isInlineSpecified();
8006
8007   if (!SemaRef.getLangOpts().CPlusPlus) {
8008     // Determine whether the function was written with a
8009     // prototype. This true when:
8010     //   - there is a prototype in the declarator, or
8011     //   - the type R of the function is some kind of typedef or other non-
8012     //     attributed reference to a type name (which eventually refers to a
8013     //     function type).
8014     bool HasPrototype =
8015       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8016       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8017
8018     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8019                                  R, TInfo, SC, isInline, HasPrototype,
8020                                  CSK_unspecified);
8021     if (D.isInvalidType())
8022       NewFD->setInvalidDecl();
8023
8024     return NewFD;
8025   }
8026
8027   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8028   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8029   // Check that the return type is not an abstract class type.
8030   // For record types, this is done by the AbstractClassUsageDiagnoser once
8031   // the class has been completely parsed.
8032   if (!DC->isRecord() &&
8033       SemaRef.RequireNonAbstractType(
8034           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8035           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8036     D.setInvalidType();
8037
8038   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8039     // This is a C++ constructor declaration.
8040     assert(DC->isRecord() &&
8041            "Constructors can only be declared in a member context");
8042
8043     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8044     return CXXConstructorDecl::Create(
8045         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8046         TInfo, ExplicitSpecifier, isInline,
8047         /*isImplicitlyDeclared=*/false, ConstexprKind);
8048
8049   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8050     // This is a C++ destructor declaration.
8051     if (DC->isRecord()) {
8052       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8053       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8054       CXXDestructorDecl *NewDD =
8055           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8056                                     NameInfo, R, TInfo, isInline,
8057                                     /*isImplicitlyDeclared=*/false);
8058
8059       // If the destructor needs an implicit exception specification, set it
8060       // now. FIXME: It'd be nice to be able to create the right type to start
8061       // with, but the type needs to reference the destructor declaration.
8062       if (SemaRef.getLangOpts().CPlusPlus11)
8063         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8064
8065       IsVirtualOkay = true;
8066       return NewDD;
8067
8068     } else {
8069       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8070       D.setInvalidType();
8071
8072       // Create a FunctionDecl to satisfy the function definition parsing
8073       // code path.
8074       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8075                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8076                                   isInline,
8077                                   /*hasPrototype=*/true, ConstexprKind);
8078     }
8079
8080   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8081     if (!DC->isRecord()) {
8082       SemaRef.Diag(D.getIdentifierLoc(),
8083            diag::err_conv_function_not_member);
8084       return nullptr;
8085     }
8086
8087     SemaRef.CheckConversionDeclarator(D, R, SC);
8088     IsVirtualOkay = true;
8089     return CXXConversionDecl::Create(
8090         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8091         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8092
8093   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8094     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8095
8096     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8097                                          ExplicitSpecifier, NameInfo, R, TInfo,
8098                                          D.getEndLoc());
8099   } else if (DC->isRecord()) {
8100     // If the name of the function is the same as the name of the record,
8101     // then this must be an invalid constructor that has a return type.
8102     // (The parser checks for a return type and makes the declarator a
8103     // constructor if it has no return type).
8104     if (Name.getAsIdentifierInfo() &&
8105         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8106       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8107         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8108         << SourceRange(D.getIdentifierLoc());
8109       return nullptr;
8110     }
8111
8112     // This is a C++ method declaration.
8113     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8114         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8115         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8116     IsVirtualOkay = !Ret->isStatic();
8117     return Ret;
8118   } else {
8119     bool isFriend =
8120         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8121     if (!isFriend && SemaRef.CurContext->isRecord())
8122       return nullptr;
8123
8124     // Determine whether the function was written with a
8125     // prototype. This true when:
8126     //   - we're in C++ (where every function has a prototype),
8127     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8128                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8129                                 ConstexprKind);
8130   }
8131 }
8132
8133 enum OpenCLParamType {
8134   ValidKernelParam,
8135   PtrPtrKernelParam,
8136   PtrKernelParam,
8137   InvalidAddrSpacePtrKernelParam,
8138   InvalidKernelParam,
8139   RecordKernelParam
8140 };
8141
8142 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8143   // Size dependent types are just typedefs to normal integer types
8144   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8145   // integers other than by their names.
8146   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8147
8148   // Remove typedefs one by one until we reach a typedef
8149   // for a size dependent type.
8150   QualType DesugaredTy = Ty;
8151   do {
8152     ArrayRef<StringRef> Names(SizeTypeNames);
8153     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8154     if (Names.end() != Match)
8155       return true;
8156
8157     Ty = DesugaredTy;
8158     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8159   } while (DesugaredTy != Ty);
8160
8161   return false;
8162 }
8163
8164 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8165   if (PT->isPointerType()) {
8166     QualType PointeeType = PT->getPointeeType();
8167     if (PointeeType->isPointerType())
8168       return PtrPtrKernelParam;
8169     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8170         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8171         PointeeType.getAddressSpace() == LangAS::Default)
8172       return InvalidAddrSpacePtrKernelParam;
8173     return PtrKernelParam;
8174   }
8175
8176   // OpenCL v1.2 s6.9.k:
8177   // Arguments to kernel functions in a program cannot be declared with the
8178   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8179   // uintptr_t or a struct and/or union that contain fields declared to be one
8180   // of these built-in scalar types.
8181   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8182     return InvalidKernelParam;
8183
8184   if (PT->isImageType())
8185     return PtrKernelParam;
8186
8187   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8188     return InvalidKernelParam;
8189
8190   // OpenCL extension spec v1.2 s9.5:
8191   // This extension adds support for half scalar and vector types as built-in
8192   // types that can be used for arithmetic operations, conversions etc.
8193   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8194     return InvalidKernelParam;
8195
8196   if (PT->isRecordType())
8197     return RecordKernelParam;
8198
8199   // Look into an array argument to check if it has a forbidden type.
8200   if (PT->isArrayType()) {
8201     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8202     // Call ourself to check an underlying type of an array. Since the
8203     // getPointeeOrArrayElementType returns an innermost type which is not an
8204     // array, this recursive call only happens once.
8205     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8206   }
8207
8208   return ValidKernelParam;
8209 }
8210
8211 static void checkIsValidOpenCLKernelParameter(
8212   Sema &S,
8213   Declarator &D,
8214   ParmVarDecl *Param,
8215   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8216   QualType PT = Param->getType();
8217
8218   // Cache the valid types we encounter to avoid rechecking structs that are
8219   // used again
8220   if (ValidTypes.count(PT.getTypePtr()))
8221     return;
8222
8223   switch (getOpenCLKernelParameterType(S, PT)) {
8224   case PtrPtrKernelParam:
8225     // OpenCL v1.2 s6.9.a:
8226     // A kernel function argument cannot be declared as a
8227     // pointer to a pointer type.
8228     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8229     D.setInvalidType();
8230     return;
8231
8232   case InvalidAddrSpacePtrKernelParam:
8233     // OpenCL v1.0 s6.5:
8234     // __kernel function arguments declared to be a pointer of a type can point
8235     // to one of the following address spaces only : __global, __local or
8236     // __constant.
8237     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8238     D.setInvalidType();
8239     return;
8240
8241     // OpenCL v1.2 s6.9.k:
8242     // Arguments to kernel functions in a program cannot be declared with the
8243     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8244     // uintptr_t or a struct and/or union that contain fields declared to be
8245     // one of these built-in scalar types.
8246
8247   case InvalidKernelParam:
8248     // OpenCL v1.2 s6.8 n:
8249     // A kernel function argument cannot be declared
8250     // of event_t type.
8251     // Do not diagnose half type since it is diagnosed as invalid argument
8252     // type for any function elsewhere.
8253     if (!PT->isHalfType()) {
8254       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8255
8256       // Explain what typedefs are involved.
8257       const TypedefType *Typedef = nullptr;
8258       while ((Typedef = PT->getAs<TypedefType>())) {
8259         SourceLocation Loc = Typedef->getDecl()->getLocation();
8260         // SourceLocation may be invalid for a built-in type.
8261         if (Loc.isValid())
8262           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8263         PT = Typedef->desugar();
8264       }
8265     }
8266
8267     D.setInvalidType();
8268     return;
8269
8270   case PtrKernelParam:
8271   case ValidKernelParam:
8272     ValidTypes.insert(PT.getTypePtr());
8273     return;
8274
8275   case RecordKernelParam:
8276     break;
8277   }
8278
8279   // Track nested structs we will inspect
8280   SmallVector<const Decl *, 4> VisitStack;
8281
8282   // Track where we are in the nested structs. Items will migrate from
8283   // VisitStack to HistoryStack as we do the DFS for bad field.
8284   SmallVector<const FieldDecl *, 4> HistoryStack;
8285   HistoryStack.push_back(nullptr);
8286
8287   // At this point we already handled everything except of a RecordType or
8288   // an ArrayType of a RecordType.
8289   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8290   const RecordType *RecTy =
8291       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8292   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8293
8294   VisitStack.push_back(RecTy->getDecl());
8295   assert(VisitStack.back() && "First decl null?");
8296
8297   do {
8298     const Decl *Next = VisitStack.pop_back_val();
8299     if (!Next) {
8300       assert(!HistoryStack.empty());
8301       // Found a marker, we have gone up a level
8302       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8303         ValidTypes.insert(Hist->getType().getTypePtr());
8304
8305       continue;
8306     }
8307
8308     // Adds everything except the original parameter declaration (which is not a
8309     // field itself) to the history stack.
8310     const RecordDecl *RD;
8311     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8312       HistoryStack.push_back(Field);
8313
8314       QualType FieldTy = Field->getType();
8315       // Other field types (known to be valid or invalid) are handled while we
8316       // walk around RecordDecl::fields().
8317       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8318              "Unexpected type.");
8319       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8320
8321       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8322     } else {
8323       RD = cast<RecordDecl>(Next);
8324     }
8325
8326     // Add a null marker so we know when we've gone back up a level
8327     VisitStack.push_back(nullptr);
8328
8329     for (const auto *FD : RD->fields()) {
8330       QualType QT = FD->getType();
8331
8332       if (ValidTypes.count(QT.getTypePtr()))
8333         continue;
8334
8335       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8336       if (ParamType == ValidKernelParam)
8337         continue;
8338
8339       if (ParamType == RecordKernelParam) {
8340         VisitStack.push_back(FD);
8341         continue;
8342       }
8343
8344       // OpenCL v1.2 s6.9.p:
8345       // Arguments to kernel functions that are declared to be a struct or union
8346       // do not allow OpenCL objects to be passed as elements of the struct or
8347       // union.
8348       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8349           ParamType == InvalidAddrSpacePtrKernelParam) {
8350         S.Diag(Param->getLocation(),
8351                diag::err_record_with_pointers_kernel_param)
8352           << PT->isUnionType()
8353           << PT;
8354       } else {
8355         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8356       }
8357
8358       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8359           << OrigRecDecl->getDeclName();
8360
8361       // We have an error, now let's go back up through history and show where
8362       // the offending field came from
8363       for (ArrayRef<const FieldDecl *>::const_iterator
8364                I = HistoryStack.begin() + 1,
8365                E = HistoryStack.end();
8366            I != E; ++I) {
8367         const FieldDecl *OuterField = *I;
8368         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8369           << OuterField->getType();
8370       }
8371
8372       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8373         << QT->isPointerType()
8374         << QT;
8375       D.setInvalidType();
8376       return;
8377     }
8378   } while (!VisitStack.empty());
8379 }
8380
8381 /// Find the DeclContext in which a tag is implicitly declared if we see an
8382 /// elaborated type specifier in the specified context, and lookup finds
8383 /// nothing.
8384 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8385   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8386     DC = DC->getParent();
8387   return DC;
8388 }
8389
8390 /// Find the Scope in which a tag is implicitly declared if we see an
8391 /// elaborated type specifier in the specified context, and lookup finds
8392 /// nothing.
8393 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8394   while (S->isClassScope() ||
8395          (LangOpts.CPlusPlus &&
8396           S->isFunctionPrototypeScope()) ||
8397          ((S->getFlags() & Scope::DeclScope) == 0) ||
8398          (S->getEntity() && S->getEntity()->isTransparentContext()))
8399     S = S->getParent();
8400   return S;
8401 }
8402
8403 NamedDecl*
8404 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8405                               TypeSourceInfo *TInfo, LookupResult &Previous,
8406                               MultiTemplateParamsArg TemplateParamLists,
8407                               bool &AddToScope) {
8408   QualType R = TInfo->getType();
8409
8410   assert(R->isFunctionType());
8411
8412   // TODO: consider using NameInfo for diagnostic.
8413   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8414   DeclarationName Name = NameInfo.getName();
8415   StorageClass SC = getFunctionStorageClass(*this, D);
8416
8417   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8418     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8419          diag::err_invalid_thread)
8420       << DeclSpec::getSpecifierName(TSCS);
8421
8422   if (D.isFirstDeclarationOfMember())
8423     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8424                            D.getIdentifierLoc());
8425
8426   bool isFriend = false;
8427   FunctionTemplateDecl *FunctionTemplate = nullptr;
8428   bool isMemberSpecialization = false;
8429   bool isFunctionTemplateSpecialization = false;
8430
8431   bool isDependentClassScopeExplicitSpecialization = false;
8432   bool HasExplicitTemplateArgs = false;
8433   TemplateArgumentListInfo TemplateArgs;
8434
8435   bool isVirtualOkay = false;
8436
8437   DeclContext *OriginalDC = DC;
8438   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8439
8440   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8441                                               isVirtualOkay);
8442   if (!NewFD) return nullptr;
8443
8444   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8445     NewFD->setTopLevelDeclInObjCContainer();
8446
8447   // Set the lexical context. If this is a function-scope declaration, or has a
8448   // C++ scope specifier, or is the object of a friend declaration, the lexical
8449   // context will be different from the semantic context.
8450   NewFD->setLexicalDeclContext(CurContext);
8451
8452   if (IsLocalExternDecl)
8453     NewFD->setLocalExternDecl();
8454
8455   if (getLangOpts().CPlusPlus) {
8456     bool isInline = D.getDeclSpec().isInlineSpecified();
8457     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8458     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8459     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8460     isFriend = D.getDeclSpec().isFriendSpecified();
8461     if (isFriend && !isInline && D.isFunctionDefinition()) {
8462       // C++ [class.friend]p5
8463       //   A function can be defined in a friend declaration of a
8464       //   class . . . . Such a function is implicitly inline.
8465       NewFD->setImplicitlyInline();
8466     }
8467
8468     // If this is a method defined in an __interface, and is not a constructor
8469     // or an overloaded operator, then set the pure flag (isVirtual will already
8470     // return true).
8471     if (const CXXRecordDecl *Parent =
8472           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8473       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8474         NewFD->setPure(true);
8475
8476       // C++ [class.union]p2
8477       //   A union can have member functions, but not virtual functions.
8478       if (isVirtual && Parent->isUnion())
8479         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8480     }
8481
8482     SetNestedNameSpecifier(*this, NewFD, D);
8483     isMemberSpecialization = false;
8484     isFunctionTemplateSpecialization = false;
8485     if (D.isInvalidType())
8486       NewFD->setInvalidDecl();
8487
8488     // Match up the template parameter lists with the scope specifier, then
8489     // determine whether we have a template or a template specialization.
8490     bool Invalid = false;
8491     if (TemplateParameterList *TemplateParams =
8492             MatchTemplateParametersToScopeSpecifier(
8493                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8494                 D.getCXXScopeSpec(),
8495                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8496                     ? D.getName().TemplateId
8497                     : nullptr,
8498                 TemplateParamLists, isFriend, isMemberSpecialization,
8499                 Invalid)) {
8500       if (TemplateParams->size() > 0) {
8501         // This is a function template
8502
8503         // Check that we can declare a template here.
8504         if (CheckTemplateDeclScope(S, TemplateParams))
8505           NewFD->setInvalidDecl();
8506
8507         // A destructor cannot be a template.
8508         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8509           Diag(NewFD->getLocation(), diag::err_destructor_template);
8510           NewFD->setInvalidDecl();
8511         }
8512
8513         // If we're adding a template to a dependent context, we may need to
8514         // rebuilding some of the types used within the template parameter list,
8515         // now that we know what the current instantiation is.
8516         if (DC->isDependentContext()) {
8517           ContextRAII SavedContext(*this, DC);
8518           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8519             Invalid = true;
8520         }
8521
8522         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8523                                                         NewFD->getLocation(),
8524                                                         Name, TemplateParams,
8525                                                         NewFD);
8526         FunctionTemplate->setLexicalDeclContext(CurContext);
8527         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8528
8529         // For source fidelity, store the other template param lists.
8530         if (TemplateParamLists.size() > 1) {
8531           NewFD->setTemplateParameterListsInfo(Context,
8532                                                TemplateParamLists.drop_back(1));
8533         }
8534       } else {
8535         // This is a function template specialization.
8536         isFunctionTemplateSpecialization = true;
8537         // For source fidelity, store all the template param lists.
8538         if (TemplateParamLists.size() > 0)
8539           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8540
8541         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8542         if (isFriend) {
8543           // We want to remove the "template<>", found here.
8544           SourceRange RemoveRange = TemplateParams->getSourceRange();
8545
8546           // If we remove the template<> and the name is not a
8547           // template-id, we're actually silently creating a problem:
8548           // the friend declaration will refer to an untemplated decl,
8549           // and clearly the user wants a template specialization.  So
8550           // we need to insert '<>' after the name.
8551           SourceLocation InsertLoc;
8552           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8553             InsertLoc = D.getName().getSourceRange().getEnd();
8554             InsertLoc = getLocForEndOfToken(InsertLoc);
8555           }
8556
8557           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8558             << Name << RemoveRange
8559             << FixItHint::CreateRemoval(RemoveRange)
8560             << FixItHint::CreateInsertion(InsertLoc, "<>");
8561         }
8562       }
8563     } else {
8564       // All template param lists were matched against the scope specifier:
8565       // this is NOT (an explicit specialization of) a template.
8566       if (TemplateParamLists.size() > 0)
8567         // For source fidelity, store all the template param lists.
8568         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8569     }
8570
8571     if (Invalid) {
8572       NewFD->setInvalidDecl();
8573       if (FunctionTemplate)
8574         FunctionTemplate->setInvalidDecl();
8575     }
8576
8577     // C++ [dcl.fct.spec]p5:
8578     //   The virtual specifier shall only be used in declarations of
8579     //   nonstatic class member functions that appear within a
8580     //   member-specification of a class declaration; see 10.3.
8581     //
8582     if (isVirtual && !NewFD->isInvalidDecl()) {
8583       if (!isVirtualOkay) {
8584         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8585              diag::err_virtual_non_function);
8586       } else if (!CurContext->isRecord()) {
8587         // 'virtual' was specified outside of the class.
8588         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8589              diag::err_virtual_out_of_class)
8590           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8591       } else if (NewFD->getDescribedFunctionTemplate()) {
8592         // C++ [temp.mem]p3:
8593         //  A member function template shall not be virtual.
8594         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8595              diag::err_virtual_member_function_template)
8596           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8597       } else {
8598         // Okay: Add virtual to the method.
8599         NewFD->setVirtualAsWritten(true);
8600       }
8601
8602       if (getLangOpts().CPlusPlus14 &&
8603           NewFD->getReturnType()->isUndeducedType())
8604         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8605     }
8606
8607     if (getLangOpts().CPlusPlus14 &&
8608         (NewFD->isDependentContext() ||
8609          (isFriend && CurContext->isDependentContext())) &&
8610         NewFD->getReturnType()->isUndeducedType()) {
8611       // If the function template is referenced directly (for instance, as a
8612       // member of the current instantiation), pretend it has a dependent type.
8613       // This is not really justified by the standard, but is the only sane
8614       // thing to do.
8615       // FIXME: For a friend function, we have not marked the function as being
8616       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8617       const FunctionProtoType *FPT =
8618           NewFD->getType()->castAs<FunctionProtoType>();
8619       QualType Result =
8620           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8621       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8622                                              FPT->getExtProtoInfo()));
8623     }
8624
8625     // C++ [dcl.fct.spec]p3:
8626     //  The inline specifier shall not appear on a block scope function
8627     //  declaration.
8628     if (isInline && !NewFD->isInvalidDecl()) {
8629       if (CurContext->isFunctionOrMethod()) {
8630         // 'inline' is not allowed on block scope function declaration.
8631         Diag(D.getDeclSpec().getInlineSpecLoc(),
8632              diag::err_inline_declaration_block_scope) << Name
8633           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8634       }
8635     }
8636
8637     // C++ [dcl.fct.spec]p6:
8638     //  The explicit specifier shall be used only in the declaration of a
8639     //  constructor or conversion function within its class definition;
8640     //  see 12.3.1 and 12.3.2.
8641     if (hasExplicit && !NewFD->isInvalidDecl() &&
8642         !isa<CXXDeductionGuideDecl>(NewFD)) {
8643       if (!CurContext->isRecord()) {
8644         // 'explicit' was specified outside of the class.
8645         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8646              diag::err_explicit_out_of_class)
8647             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8648       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8649                  !isa<CXXConversionDecl>(NewFD)) {
8650         // 'explicit' was specified on a function that wasn't a constructor
8651         // or conversion function.
8652         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8653              diag::err_explicit_non_ctor_or_conv_function)
8654             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8655       }
8656     }
8657
8658     if (ConstexprKind != CSK_unspecified) {
8659       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8660       // are implicitly inline.
8661       NewFD->setImplicitlyInline();
8662
8663       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8664       // be either constructors or to return a literal type. Therefore,
8665       // destructors cannot be declared constexpr.
8666       if (isa<CXXDestructorDecl>(NewFD))
8667         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8668             << (ConstexprKind == CSK_consteval);
8669     }
8670
8671     // If __module_private__ was specified, mark the function accordingly.
8672     if (D.getDeclSpec().isModulePrivateSpecified()) {
8673       if (isFunctionTemplateSpecialization) {
8674         SourceLocation ModulePrivateLoc
8675           = D.getDeclSpec().getModulePrivateSpecLoc();
8676         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8677           << 0
8678           << FixItHint::CreateRemoval(ModulePrivateLoc);
8679       } else {
8680         NewFD->setModulePrivate();
8681         if (FunctionTemplate)
8682           FunctionTemplate->setModulePrivate();
8683       }
8684     }
8685
8686     if (isFriend) {
8687       if (FunctionTemplate) {
8688         FunctionTemplate->setObjectOfFriendDecl();
8689         FunctionTemplate->setAccess(AS_public);
8690       }
8691       NewFD->setObjectOfFriendDecl();
8692       NewFD->setAccess(AS_public);
8693     }
8694
8695     // If a function is defined as defaulted or deleted, mark it as such now.
8696     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8697     // definition kind to FDK_Definition.
8698     switch (D.getFunctionDefinitionKind()) {
8699       case FDK_Declaration:
8700       case FDK_Definition:
8701         break;
8702
8703       case FDK_Defaulted:
8704         NewFD->setDefaulted();
8705         break;
8706
8707       case FDK_Deleted:
8708         NewFD->setDeletedAsWritten();
8709         break;
8710     }
8711
8712     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8713         D.isFunctionDefinition()) {
8714       // C++ [class.mfct]p2:
8715       //   A member function may be defined (8.4) in its class definition, in
8716       //   which case it is an inline member function (7.1.2)
8717       NewFD->setImplicitlyInline();
8718     }
8719
8720     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8721         !CurContext->isRecord()) {
8722       // C++ [class.static]p1:
8723       //   A data or function member of a class may be declared static
8724       //   in a class definition, in which case it is a static member of
8725       //   the class.
8726
8727       // Complain about the 'static' specifier if it's on an out-of-line
8728       // member function definition.
8729
8730       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8731       // member function template declaration and class member template
8732       // declaration (MSVC versions before 2015), warn about this.
8733       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8734            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8735              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8736            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8737            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8738         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8739     }
8740
8741     // C++11 [except.spec]p15:
8742     //   A deallocation function with no exception-specification is treated
8743     //   as if it were specified with noexcept(true).
8744     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8745     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8746          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8747         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8748       NewFD->setType(Context.getFunctionType(
8749           FPT->getReturnType(), FPT->getParamTypes(),
8750           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8751   }
8752
8753   // Filter out previous declarations that don't match the scope.
8754   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8755                        D.getCXXScopeSpec().isNotEmpty() ||
8756                        isMemberSpecialization ||
8757                        isFunctionTemplateSpecialization);
8758
8759   // Handle GNU asm-label extension (encoded as an attribute).
8760   if (Expr *E = (Expr*) D.getAsmLabel()) {
8761     // The parser guarantees this is a string.
8762     StringLiteral *SE = cast<StringLiteral>(E);
8763     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8764                                                 SE->getString(), 0));
8765   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8766     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8767       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8768     if (I != ExtnameUndeclaredIdentifiers.end()) {
8769       if (isDeclExternC(NewFD)) {
8770         NewFD->addAttr(I->second);
8771         ExtnameUndeclaredIdentifiers.erase(I);
8772       } else
8773         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8774             << /*Variable*/0 << NewFD;
8775     }
8776   }
8777
8778   // Copy the parameter declarations from the declarator D to the function
8779   // declaration NewFD, if they are available.  First scavenge them into Params.
8780   SmallVector<ParmVarDecl*, 16> Params;
8781   unsigned FTIIdx;
8782   if (D.isFunctionDeclarator(FTIIdx)) {
8783     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8784
8785     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8786     // function that takes no arguments, not a function that takes a
8787     // single void argument.
8788     // We let through "const void" here because Sema::GetTypeForDeclarator
8789     // already checks for that case.
8790     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8791       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8792         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8793         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8794         Param->setDeclContext(NewFD);
8795         Params.push_back(Param);
8796
8797         if (Param->isInvalidDecl())
8798           NewFD->setInvalidDecl();
8799       }
8800     }
8801
8802     if (!getLangOpts().CPlusPlus) {
8803       // In C, find all the tag declarations from the prototype and move them
8804       // into the function DeclContext. Remove them from the surrounding tag
8805       // injection context of the function, which is typically but not always
8806       // the TU.
8807       DeclContext *PrototypeTagContext =
8808           getTagInjectionContext(NewFD->getLexicalDeclContext());
8809       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8810         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8811
8812         // We don't want to reparent enumerators. Look at their parent enum
8813         // instead.
8814         if (!TD) {
8815           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8816             TD = cast<EnumDecl>(ECD->getDeclContext());
8817         }
8818         if (!TD)
8819           continue;
8820         DeclContext *TagDC = TD->getLexicalDeclContext();
8821         if (!TagDC->containsDecl(TD))
8822           continue;
8823         TagDC->removeDecl(TD);
8824         TD->setDeclContext(NewFD);
8825         NewFD->addDecl(TD);
8826
8827         // Preserve the lexical DeclContext if it is not the surrounding tag
8828         // injection context of the FD. In this example, the semantic context of
8829         // E will be f and the lexical context will be S, while both the
8830         // semantic and lexical contexts of S will be f:
8831         //   void f(struct S { enum E { a } f; } s);
8832         if (TagDC != PrototypeTagContext)
8833           TD->setLexicalDeclContext(TagDC);
8834       }
8835     }
8836   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8837     // When we're declaring a function with a typedef, typeof, etc as in the
8838     // following example, we'll need to synthesize (unnamed)
8839     // parameters for use in the declaration.
8840     //
8841     // @code
8842     // typedef void fn(int);
8843     // fn f;
8844     // @endcode
8845
8846     // Synthesize a parameter for each argument type.
8847     for (const auto &AI : FT->param_types()) {
8848       ParmVarDecl *Param =
8849           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8850       Param->setScopeInfo(0, Params.size());
8851       Params.push_back(Param);
8852     }
8853   } else {
8854     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8855            "Should not need args for typedef of non-prototype fn");
8856   }
8857
8858   // Finally, we know we have the right number of parameters, install them.
8859   NewFD->setParams(Params);
8860
8861   if (D.getDeclSpec().isNoreturnSpecified())
8862     NewFD->addAttr(
8863         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8864                                        Context, 0));
8865
8866   // Functions returning a variably modified type violate C99 6.7.5.2p2
8867   // because all functions have linkage.
8868   if (!NewFD->isInvalidDecl() &&
8869       NewFD->getReturnType()->isVariablyModifiedType()) {
8870     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8871     NewFD->setInvalidDecl();
8872   }
8873
8874   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8875   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8876       !NewFD->hasAttr<SectionAttr>()) {
8877     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8878                                                  PragmaClangTextSection.SectionName,
8879                                                  PragmaClangTextSection.PragmaLocation));
8880   }
8881
8882   // Apply an implicit SectionAttr if #pragma code_seg is active.
8883   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8884       !NewFD->hasAttr<SectionAttr>()) {
8885     NewFD->addAttr(
8886         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8887                                     CodeSegStack.CurrentValue->getString(),
8888                                     CodeSegStack.CurrentPragmaLocation));
8889     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8890                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8891                          ASTContext::PSF_Read,
8892                      NewFD))
8893       NewFD->dropAttr<SectionAttr>();
8894   }
8895
8896   // Apply an implicit CodeSegAttr from class declspec or
8897   // apply an implicit SectionAttr from #pragma code_seg if active.
8898   if (!NewFD->hasAttr<CodeSegAttr>()) {
8899     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8900                                                                  D.isFunctionDefinition())) {
8901       NewFD->addAttr(SAttr);
8902     }
8903   }
8904
8905   // Handle attributes.
8906   ProcessDeclAttributes(S, NewFD, D);
8907
8908   if (getLangOpts().OpenCL) {
8909     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8910     // type declaration will generate a compilation error.
8911     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8912     if (AddressSpace != LangAS::Default) {
8913       Diag(NewFD->getLocation(),
8914            diag::err_opencl_return_value_with_address_space);
8915       NewFD->setInvalidDecl();
8916     }
8917   }
8918
8919   if (!getLangOpts().CPlusPlus) {
8920     // Perform semantic checking on the function declaration.
8921     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8922       CheckMain(NewFD, D.getDeclSpec());
8923
8924     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8925       CheckMSVCRTEntryPoint(NewFD);
8926
8927     if (!NewFD->isInvalidDecl())
8928       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8929                                                   isMemberSpecialization));
8930     else if (!Previous.empty())
8931       // Recover gracefully from an invalid redeclaration.
8932       D.setRedeclaration(true);
8933     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8934             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8935            "previous declaration set still overloaded");
8936
8937     // Diagnose no-prototype function declarations with calling conventions that
8938     // don't support variadic calls. Only do this in C and do it after merging
8939     // possibly prototyped redeclarations.
8940     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8941     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8942       CallingConv CC = FT->getExtInfo().getCC();
8943       if (!supportsVariadicCall(CC)) {
8944         // Windows system headers sometimes accidentally use stdcall without
8945         // (void) parameters, so we relax this to a warning.
8946         int DiagID =
8947             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8948         Diag(NewFD->getLocation(), DiagID)
8949             << FunctionType::getNameForCallConv(CC);
8950       }
8951     }
8952
8953    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
8954        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
8955      checkNonTrivialCUnion(NewFD->getReturnType(),
8956                            NewFD->getReturnTypeSourceRange().getBegin(),
8957                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
8958   } else {
8959     // C++11 [replacement.functions]p3:
8960     //  The program's definitions shall not be specified as inline.
8961     //
8962     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8963     //
8964     // Suppress the diagnostic if the function is __attribute__((used)), since
8965     // that forces an external definition to be emitted.
8966     if (D.getDeclSpec().isInlineSpecified() &&
8967         NewFD->isReplaceableGlobalAllocationFunction() &&
8968         !NewFD->hasAttr<UsedAttr>())
8969       Diag(D.getDeclSpec().getInlineSpecLoc(),
8970            diag::ext_operator_new_delete_declared_inline)
8971         << NewFD->getDeclName();
8972
8973     // If the declarator is a template-id, translate the parser's template
8974     // argument list into our AST format.
8975     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8976       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8977       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8978       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8979       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8980                                          TemplateId->NumArgs);
8981       translateTemplateArguments(TemplateArgsPtr,
8982                                  TemplateArgs);
8983
8984       HasExplicitTemplateArgs = true;
8985
8986       if (NewFD->isInvalidDecl()) {
8987         HasExplicitTemplateArgs = false;
8988       } else if (FunctionTemplate) {
8989         // Function template with explicit template arguments.
8990         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8991           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8992
8993         HasExplicitTemplateArgs = false;
8994       } else {
8995         assert((isFunctionTemplateSpecialization ||
8996                 D.getDeclSpec().isFriendSpecified()) &&
8997                "should have a 'template<>' for this decl");
8998         // "friend void foo<>(int);" is an implicit specialization decl.
8999         isFunctionTemplateSpecialization = true;
9000       }
9001     } else if (isFriend && isFunctionTemplateSpecialization) {
9002       // This combination is only possible in a recovery case;  the user
9003       // wrote something like:
9004       //   template <> friend void foo(int);
9005       // which we're recovering from as if the user had written:
9006       //   friend void foo<>(int);
9007       // Go ahead and fake up a template id.
9008       HasExplicitTemplateArgs = true;
9009       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9010       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9011     }
9012
9013     // We do not add HD attributes to specializations here because
9014     // they may have different constexpr-ness compared to their
9015     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9016     // may end up with different effective targets. Instead, a
9017     // specialization inherits its target attributes from its template
9018     // in the CheckFunctionTemplateSpecialization() call below.
9019     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
9020       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9021
9022     // If it's a friend (and only if it's a friend), it's possible
9023     // that either the specialized function type or the specialized
9024     // template is dependent, and therefore matching will fail.  In
9025     // this case, don't check the specialization yet.
9026     bool InstantiationDependent = false;
9027     if (isFunctionTemplateSpecialization && isFriend &&
9028         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9029          TemplateSpecializationType::anyDependentTemplateArguments(
9030             TemplateArgs,
9031             InstantiationDependent))) {
9032       assert(HasExplicitTemplateArgs &&
9033              "friend function specialization without template args");
9034       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9035                                                        Previous))
9036         NewFD->setInvalidDecl();
9037     } else if (isFunctionTemplateSpecialization) {
9038       if (CurContext->isDependentContext() && CurContext->isRecord()
9039           && !isFriend) {
9040         isDependentClassScopeExplicitSpecialization = true;
9041       } else if (!NewFD->isInvalidDecl() &&
9042                  CheckFunctionTemplateSpecialization(
9043                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9044                      Previous))
9045         NewFD->setInvalidDecl();
9046
9047       // C++ [dcl.stc]p1:
9048       //   A storage-class-specifier shall not be specified in an explicit
9049       //   specialization (14.7.3)
9050       FunctionTemplateSpecializationInfo *Info =
9051           NewFD->getTemplateSpecializationInfo();
9052       if (Info && SC != SC_None) {
9053         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9054           Diag(NewFD->getLocation(),
9055                diag::err_explicit_specialization_inconsistent_storage_class)
9056             << SC
9057             << FixItHint::CreateRemoval(
9058                                       D.getDeclSpec().getStorageClassSpecLoc());
9059
9060         else
9061           Diag(NewFD->getLocation(),
9062                diag::ext_explicit_specialization_storage_class)
9063             << FixItHint::CreateRemoval(
9064                                       D.getDeclSpec().getStorageClassSpecLoc());
9065       }
9066     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9067       if (CheckMemberSpecialization(NewFD, Previous))
9068           NewFD->setInvalidDecl();
9069     }
9070
9071     // Perform semantic checking on the function declaration.
9072     if (!isDependentClassScopeExplicitSpecialization) {
9073       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9074         CheckMain(NewFD, D.getDeclSpec());
9075
9076       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9077         CheckMSVCRTEntryPoint(NewFD);
9078
9079       if (!NewFD->isInvalidDecl())
9080         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9081                                                     isMemberSpecialization));
9082       else if (!Previous.empty())
9083         // Recover gracefully from an invalid redeclaration.
9084         D.setRedeclaration(true);
9085     }
9086
9087     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9088             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9089            "previous declaration set still overloaded");
9090
9091     NamedDecl *PrincipalDecl = (FunctionTemplate
9092                                 ? cast<NamedDecl>(FunctionTemplate)
9093                                 : NewFD);
9094
9095     if (isFriend && NewFD->getPreviousDecl()) {
9096       AccessSpecifier Access = AS_public;
9097       if (!NewFD->isInvalidDecl())
9098         Access = NewFD->getPreviousDecl()->getAccess();
9099
9100       NewFD->setAccess(Access);
9101       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9102     }
9103
9104     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9105         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9106       PrincipalDecl->setNonMemberOperator();
9107
9108     // If we have a function template, check the template parameter
9109     // list. This will check and merge default template arguments.
9110     if (FunctionTemplate) {
9111       FunctionTemplateDecl *PrevTemplate =
9112                                      FunctionTemplate->getPreviousDecl();
9113       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9114                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9115                                     : nullptr,
9116                             D.getDeclSpec().isFriendSpecified()
9117                               ? (D.isFunctionDefinition()
9118                                    ? TPC_FriendFunctionTemplateDefinition
9119                                    : TPC_FriendFunctionTemplate)
9120                               : (D.getCXXScopeSpec().isSet() &&
9121                                  DC && DC->isRecord() &&
9122                                  DC->isDependentContext())
9123                                   ? TPC_ClassTemplateMember
9124                                   : TPC_FunctionTemplate);
9125     }
9126
9127     if (NewFD->isInvalidDecl()) {
9128       // Ignore all the rest of this.
9129     } else if (!D.isRedeclaration()) {
9130       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9131                                        AddToScope };
9132       // Fake up an access specifier if it's supposed to be a class member.
9133       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9134         NewFD->setAccess(AS_public);
9135
9136       // Qualified decls generally require a previous declaration.
9137       if (D.getCXXScopeSpec().isSet()) {
9138         // ...with the major exception of templated-scope or
9139         // dependent-scope friend declarations.
9140
9141         // TODO: we currently also suppress this check in dependent
9142         // contexts because (1) the parameter depth will be off when
9143         // matching friend templates and (2) we might actually be
9144         // selecting a friend based on a dependent factor.  But there
9145         // are situations where these conditions don't apply and we
9146         // can actually do this check immediately.
9147         //
9148         // Unless the scope is dependent, it's always an error if qualified
9149         // redeclaration lookup found nothing at all. Diagnose that now;
9150         // nothing will diagnose that error later.
9151         if (isFriend &&
9152             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9153              (!Previous.empty() && CurContext->isDependentContext()))) {
9154           // ignore these
9155         } else {
9156           // The user tried to provide an out-of-line definition for a
9157           // function that is a member of a class or namespace, but there
9158           // was no such member function declared (C++ [class.mfct]p2,
9159           // C++ [namespace.memdef]p2). For example:
9160           //
9161           // class X {
9162           //   void f() const;
9163           // };
9164           //
9165           // void X::f() { } // ill-formed
9166           //
9167           // Complain about this problem, and attempt to suggest close
9168           // matches (e.g., those that differ only in cv-qualifiers and
9169           // whether the parameter types are references).
9170
9171           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9172                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9173             AddToScope = ExtraArgs.AddToScope;
9174             return Result;
9175           }
9176         }
9177
9178         // Unqualified local friend declarations are required to resolve
9179         // to something.
9180       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9181         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9182                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9183           AddToScope = ExtraArgs.AddToScope;
9184           return Result;
9185         }
9186       }
9187     } else if (!D.isFunctionDefinition() &&
9188                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9189                !isFriend && !isFunctionTemplateSpecialization &&
9190                !isMemberSpecialization) {
9191       // An out-of-line member function declaration must also be a
9192       // definition (C++ [class.mfct]p2).
9193       // Note that this is not the case for explicit specializations of
9194       // function templates or member functions of class templates, per
9195       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9196       // extension for compatibility with old SWIG code which likes to
9197       // generate them.
9198       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9199         << D.getCXXScopeSpec().getRange();
9200     }
9201   }
9202
9203   ProcessPragmaWeak(S, NewFD);
9204   checkAttributesAfterMerging(*this, *NewFD);
9205
9206   AddKnownFunctionAttributes(NewFD);
9207
9208   if (NewFD->hasAttr<OverloadableAttr>() &&
9209       !NewFD->getType()->getAs<FunctionProtoType>()) {
9210     Diag(NewFD->getLocation(),
9211          diag::err_attribute_overloadable_no_prototype)
9212       << NewFD;
9213
9214     // Turn this into a variadic function with no parameters.
9215     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9216     FunctionProtoType::ExtProtoInfo EPI(
9217         Context.getDefaultCallingConvention(true, false));
9218     EPI.Variadic = true;
9219     EPI.ExtInfo = FT->getExtInfo();
9220
9221     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9222     NewFD->setType(R);
9223   }
9224
9225   // If there's a #pragma GCC visibility in scope, and this isn't a class
9226   // member, set the visibility of this function.
9227   if (!DC->isRecord() && NewFD->isExternallyVisible())
9228     AddPushedVisibilityAttribute(NewFD);
9229
9230   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9231   // marking the function.
9232   AddCFAuditedAttribute(NewFD);
9233
9234   // If this is a function definition, check if we have to apply optnone due to
9235   // a pragma.
9236   if(D.isFunctionDefinition())
9237     AddRangeBasedOptnone(NewFD);
9238
9239   // If this is the first declaration of an extern C variable, update
9240   // the map of such variables.
9241   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9242       isIncompleteDeclExternC(*this, NewFD))
9243     RegisterLocallyScopedExternCDecl(NewFD, S);
9244
9245   // Set this FunctionDecl's range up to the right paren.
9246   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9247
9248   if (D.isRedeclaration() && !Previous.empty()) {
9249     NamedDecl *Prev = Previous.getRepresentativeDecl();
9250     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9251                                    isMemberSpecialization ||
9252                                        isFunctionTemplateSpecialization,
9253                                    D.isFunctionDefinition());
9254   }
9255
9256   if (getLangOpts().CUDA) {
9257     IdentifierInfo *II = NewFD->getIdentifier();
9258     if (II && II->isStr(getCudaConfigureFuncName()) &&
9259         !NewFD->isInvalidDecl() &&
9260         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9261       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9262         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9263             << getCudaConfigureFuncName();
9264       Context.setcudaConfigureCallDecl(NewFD);
9265     }
9266
9267     // Variadic functions, other than a *declaration* of printf, are not allowed
9268     // in device-side CUDA code, unless someone passed
9269     // -fcuda-allow-variadic-functions.
9270     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9271         (NewFD->hasAttr<CUDADeviceAttr>() ||
9272          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9273         !(II && II->isStr("printf") && NewFD->isExternC() &&
9274           !D.isFunctionDefinition())) {
9275       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9276     }
9277   }
9278
9279   MarkUnusedFileScopedDecl(NewFD);
9280
9281
9282
9283   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9284     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9285     if ((getLangOpts().OpenCLVersion >= 120)
9286         && (SC == SC_Static)) {
9287       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9288       D.setInvalidType();
9289     }
9290
9291     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9292     if (!NewFD->getReturnType()->isVoidType()) {
9293       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9294       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9295           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9296                                 : FixItHint());
9297       D.setInvalidType();
9298     }
9299
9300     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9301     for (auto Param : NewFD->parameters())
9302       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9303
9304     if (getLangOpts().OpenCLCPlusPlus) {
9305       if (DC->isRecord()) {
9306         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9307         D.setInvalidType();
9308       }
9309       if (FunctionTemplate) {
9310         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9311         D.setInvalidType();
9312       }
9313     }
9314   }
9315
9316   if (getLangOpts().CPlusPlus) {
9317     if (FunctionTemplate) {
9318       if (NewFD->isInvalidDecl())
9319         FunctionTemplate->setInvalidDecl();
9320       return FunctionTemplate;
9321     }
9322
9323     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9324       CompleteMemberSpecialization(NewFD, Previous);
9325   }
9326
9327   for (const ParmVarDecl *Param : NewFD->parameters()) {
9328     QualType PT = Param->getType();
9329
9330     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9331     // types.
9332     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9333       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9334         QualType ElemTy = PipeTy->getElementType();
9335           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9336             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9337             D.setInvalidType();
9338           }
9339       }
9340     }
9341   }
9342
9343   // Here we have an function template explicit specialization at class scope.
9344   // The actual specialization will be postponed to template instatiation
9345   // time via the ClassScopeFunctionSpecializationDecl node.
9346   if (isDependentClassScopeExplicitSpecialization) {
9347     ClassScopeFunctionSpecializationDecl *NewSpec =
9348                          ClassScopeFunctionSpecializationDecl::Create(
9349                                 Context, CurContext, NewFD->getLocation(),
9350                                 cast<CXXMethodDecl>(NewFD),
9351                                 HasExplicitTemplateArgs, TemplateArgs);
9352     CurContext->addDecl(NewSpec);
9353     AddToScope = false;
9354   }
9355
9356   // Diagnose availability attributes. Availability cannot be used on functions
9357   // that are run during load/unload.
9358   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9359     if (NewFD->hasAttr<ConstructorAttr>()) {
9360       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9361           << 1;
9362       NewFD->dropAttr<AvailabilityAttr>();
9363     }
9364     if (NewFD->hasAttr<DestructorAttr>()) {
9365       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9366           << 2;
9367       NewFD->dropAttr<AvailabilityAttr>();
9368     }
9369   }
9370
9371   return NewFD;
9372 }
9373
9374 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9375 /// when __declspec(code_seg) "is applied to a class, all member functions of
9376 /// the class and nested classes -- this includes compiler-generated special
9377 /// member functions -- are put in the specified segment."
9378 /// The actual behavior is a little more complicated. The Microsoft compiler
9379 /// won't check outer classes if there is an active value from #pragma code_seg.
9380 /// The CodeSeg is always applied from the direct parent but only from outer
9381 /// classes when the #pragma code_seg stack is empty. See:
9382 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9383 /// available since MS has removed the page.
9384 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9385   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9386   if (!Method)
9387     return nullptr;
9388   const CXXRecordDecl *Parent = Method->getParent();
9389   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9390     Attr *NewAttr = SAttr->clone(S.getASTContext());
9391     NewAttr->setImplicit(true);
9392     return NewAttr;
9393   }
9394
9395   // The Microsoft compiler won't check outer classes for the CodeSeg
9396   // when the #pragma code_seg stack is active.
9397   if (S.CodeSegStack.CurrentValue)
9398    return nullptr;
9399
9400   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9401     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9402       Attr *NewAttr = SAttr->clone(S.getASTContext());
9403       NewAttr->setImplicit(true);
9404       return NewAttr;
9405     }
9406   }
9407   return nullptr;
9408 }
9409
9410 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9411 /// containing class. Otherwise it will return implicit SectionAttr if the
9412 /// function is a definition and there is an active value on CodeSegStack
9413 /// (from the current #pragma code-seg value).
9414 ///
9415 /// \param FD Function being declared.
9416 /// \param IsDefinition Whether it is a definition or just a declarartion.
9417 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9418 ///          nullptr if no attribute should be added.
9419 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9420                                                        bool IsDefinition) {
9421   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9422     return A;
9423   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9424       CodeSegStack.CurrentValue) {
9425     return SectionAttr::CreateImplicit(getASTContext(),
9426                                        SectionAttr::Declspec_allocate,
9427                                        CodeSegStack.CurrentValue->getString(),
9428                                        CodeSegStack.CurrentPragmaLocation);
9429   }
9430   return nullptr;
9431 }
9432
9433 /// Determines if we can perform a correct type check for \p D as a
9434 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9435 /// best-effort check.
9436 ///
9437 /// \param NewD The new declaration.
9438 /// \param OldD The old declaration.
9439 /// \param NewT The portion of the type of the new declaration to check.
9440 /// \param OldT The portion of the type of the old declaration to check.
9441 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9442                                           QualType NewT, QualType OldT) {
9443   if (!NewD->getLexicalDeclContext()->isDependentContext())
9444     return true;
9445
9446   // For dependently-typed local extern declarations and friends, we can't
9447   // perform a correct type check in general until instantiation:
9448   //
9449   //   int f();
9450   //   template<typename T> void g() { T f(); }
9451   //
9452   // (valid if g() is only instantiated with T = int).
9453   if (NewT->isDependentType() &&
9454       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9455     return false;
9456
9457   // Similarly, if the previous declaration was a dependent local extern
9458   // declaration, we don't really know its type yet.
9459   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9460     return false;
9461
9462   return true;
9463 }
9464
9465 /// Checks if the new declaration declared in dependent context must be
9466 /// put in the same redeclaration chain as the specified declaration.
9467 ///
9468 /// \param D Declaration that is checked.
9469 /// \param PrevDecl Previous declaration found with proper lookup method for the
9470 ///                 same declaration name.
9471 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9472 ///          belongs to.
9473 ///
9474 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9475   if (!D->getLexicalDeclContext()->isDependentContext())
9476     return true;
9477
9478   // Don't chain dependent friend function definitions until instantiation, to
9479   // permit cases like
9480   //
9481   //   void func();
9482   //   template<typename T> class C1 { friend void func() {} };
9483   //   template<typename T> class C2 { friend void func() {} };
9484   //
9485   // ... which is valid if only one of C1 and C2 is ever instantiated.
9486   //
9487   // FIXME: This need only apply to function definitions. For now, we proxy
9488   // this by checking for a file-scope function. We do not want this to apply
9489   // to friend declarations nominating member functions, because that gets in
9490   // the way of access checks.
9491   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9492     return false;
9493
9494   auto *VD = dyn_cast<ValueDecl>(D);
9495   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9496   return !VD || !PrevVD ||
9497          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9498                                         PrevVD->getType());
9499 }
9500
9501 /// Check the target attribute of the function for MultiVersion
9502 /// validity.
9503 ///
9504 /// Returns true if there was an error, false otherwise.
9505 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9506   const auto *TA = FD->getAttr<TargetAttr>();
9507   assert(TA && "MultiVersion Candidate requires a target attribute");
9508   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9509   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9510   enum ErrType { Feature = 0, Architecture = 1 };
9511
9512   if (!ParseInfo.Architecture.empty() &&
9513       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9514     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9515         << Architecture << ParseInfo.Architecture;
9516     return true;
9517   }
9518
9519   for (const auto &Feat : ParseInfo.Features) {
9520     auto BareFeat = StringRef{Feat}.substr(1);
9521     if (Feat[0] == '-') {
9522       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9523           << Feature << ("no-" + BareFeat).str();
9524       return true;
9525     }
9526
9527     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9528         !TargetInfo.isValidFeatureName(BareFeat)) {
9529       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9530           << Feature << BareFeat;
9531       return true;
9532     }
9533   }
9534   return false;
9535 }
9536
9537 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9538                                          MultiVersionKind MVType) {
9539   for (const Attr *A : FD->attrs()) {
9540     switch (A->getKind()) {
9541     case attr::CPUDispatch:
9542     case attr::CPUSpecific:
9543       if (MVType != MultiVersionKind::CPUDispatch &&
9544           MVType != MultiVersionKind::CPUSpecific)
9545         return true;
9546       break;
9547     case attr::Target:
9548       if (MVType != MultiVersionKind::Target)
9549         return true;
9550       break;
9551     default:
9552       return true;
9553     }
9554   }
9555   return false;
9556 }
9557
9558 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9559                                              const FunctionDecl *NewFD,
9560                                              bool CausesMV,
9561                                              MultiVersionKind MVType) {
9562   enum DoesntSupport {
9563     FuncTemplates = 0,
9564     VirtFuncs = 1,
9565     DeducedReturn = 2,
9566     Constructors = 3,
9567     Destructors = 4,
9568     DeletedFuncs = 5,
9569     DefaultedFuncs = 6,
9570     ConstexprFuncs = 7,
9571     ConstevalFuncs = 8,
9572   };
9573   enum Different {
9574     CallingConv = 0,
9575     ReturnType = 1,
9576     ConstexprSpec = 2,
9577     InlineSpec = 3,
9578     StorageClass = 4,
9579     Linkage = 5
9580   };
9581
9582   bool IsCPUSpecificCPUDispatchMVType =
9583       MVType == MultiVersionKind::CPUDispatch ||
9584       MVType == MultiVersionKind::CPUSpecific;
9585
9586   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9587     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9588     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9589     return true;
9590   }
9591
9592   if (!NewFD->getType()->getAs<FunctionProtoType>())
9593     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9594
9595   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9596     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9597     if (OldFD)
9598       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9599     return true;
9600   }
9601
9602   // For now, disallow all other attributes.  These should be opt-in, but
9603   // an analysis of all of them is a future FIXME.
9604   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9605     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9606         << IsCPUSpecificCPUDispatchMVType;
9607     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9608     return true;
9609   }
9610
9611   if (HasNonMultiVersionAttributes(NewFD, MVType))
9612     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9613            << IsCPUSpecificCPUDispatchMVType;
9614
9615   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9616     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9617            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9618
9619   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9620     if (NewCXXFD->isVirtual())
9621       return S.Diag(NewCXXFD->getLocation(),
9622                     diag::err_multiversion_doesnt_support)
9623              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9624
9625     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9626       return S.Diag(NewCXXCtor->getLocation(),
9627                     diag::err_multiversion_doesnt_support)
9628              << IsCPUSpecificCPUDispatchMVType << Constructors;
9629
9630     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9631       return S.Diag(NewCXXDtor->getLocation(),
9632                     diag::err_multiversion_doesnt_support)
9633              << IsCPUSpecificCPUDispatchMVType << Destructors;
9634   }
9635
9636   if (NewFD->isDeleted())
9637     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9638            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9639
9640   if (NewFD->isDefaulted())
9641     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9642            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9643
9644   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9645                                MVType == MultiVersionKind::CPUSpecific))
9646     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9647            << IsCPUSpecificCPUDispatchMVType
9648            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9649
9650   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9651   const auto *NewType = cast<FunctionType>(NewQType);
9652   QualType NewReturnType = NewType->getReturnType();
9653
9654   if (NewReturnType->isUndeducedType())
9655     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9656            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9657
9658   // Only allow transition to MultiVersion if it hasn't been used.
9659   if (OldFD && CausesMV && OldFD->isUsed(false))
9660     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9661
9662   // Ensure the return type is identical.
9663   if (OldFD) {
9664     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9665     const auto *OldType = cast<FunctionType>(OldQType);
9666     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9667     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9668
9669     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9670       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9671              << CallingConv;
9672
9673     QualType OldReturnType = OldType->getReturnType();
9674
9675     if (OldReturnType != NewReturnType)
9676       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9677              << ReturnType;
9678
9679     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9680       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9681              << ConstexprSpec;
9682
9683     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9684       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9685              << InlineSpec;
9686
9687     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9688       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9689              << StorageClass;
9690
9691     if (OldFD->isExternC() != NewFD->isExternC())
9692       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9693              << Linkage;
9694
9695     if (S.CheckEquivalentExceptionSpec(
9696             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9697             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9698       return true;
9699   }
9700   return false;
9701 }
9702
9703 /// Check the validity of a multiversion function declaration that is the
9704 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9705 ///
9706 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9707 ///
9708 /// Returns true if there was an error, false otherwise.
9709 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9710                                            MultiVersionKind MVType,
9711                                            const TargetAttr *TA) {
9712   assert(MVType != MultiVersionKind::None &&
9713          "Function lacks multiversion attribute");
9714
9715   // Target only causes MV if it is default, otherwise this is a normal
9716   // function.
9717   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9718     return false;
9719
9720   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9721     FD->setInvalidDecl();
9722     return true;
9723   }
9724
9725   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9726     FD->setInvalidDecl();
9727     return true;
9728   }
9729
9730   FD->setIsMultiVersion();
9731   return false;
9732 }
9733
9734 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9735   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9736     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9737       return true;
9738   }
9739
9740   return false;
9741 }
9742
9743 static bool CheckTargetCausesMultiVersioning(
9744     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9745     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9746     LookupResult &Previous) {
9747   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9748   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9749   // Sort order doesn't matter, it just needs to be consistent.
9750   llvm::sort(NewParsed.Features);
9751
9752   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9753   // to change, this is a simple redeclaration.
9754   if (!NewTA->isDefaultVersion() &&
9755       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9756     return false;
9757
9758   // Otherwise, this decl causes MultiVersioning.
9759   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9760     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9761     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9762     NewFD->setInvalidDecl();
9763     return true;
9764   }
9765
9766   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9767                                        MultiVersionKind::Target)) {
9768     NewFD->setInvalidDecl();
9769     return true;
9770   }
9771
9772   if (CheckMultiVersionValue(S, NewFD)) {
9773     NewFD->setInvalidDecl();
9774     return true;
9775   }
9776
9777   // If this is 'default', permit the forward declaration.
9778   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9779     Redeclaration = true;
9780     OldDecl = OldFD;
9781     OldFD->setIsMultiVersion();
9782     NewFD->setIsMultiVersion();
9783     return false;
9784   }
9785
9786   if (CheckMultiVersionValue(S, OldFD)) {
9787     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9788     NewFD->setInvalidDecl();
9789     return true;
9790   }
9791
9792   TargetAttr::ParsedTargetAttr OldParsed =
9793       OldTA->parse(std::less<std::string>());
9794
9795   if (OldParsed == NewParsed) {
9796     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9797     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9798     NewFD->setInvalidDecl();
9799     return true;
9800   }
9801
9802   for (const auto *FD : OldFD->redecls()) {
9803     const auto *CurTA = FD->getAttr<TargetAttr>();
9804     // We allow forward declarations before ANY multiversioning attributes, but
9805     // nothing after the fact.
9806     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9807         (!CurTA || CurTA->isInherited())) {
9808       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9809           << 0;
9810       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9811       NewFD->setInvalidDecl();
9812       return true;
9813     }
9814   }
9815
9816   OldFD->setIsMultiVersion();
9817   NewFD->setIsMultiVersion();
9818   Redeclaration = false;
9819   MergeTypeWithPrevious = false;
9820   OldDecl = nullptr;
9821   Previous.clear();
9822   return false;
9823 }
9824
9825 /// Check the validity of a new function declaration being added to an existing
9826 /// multiversioned declaration collection.
9827 static bool CheckMultiVersionAdditionalDecl(
9828     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9829     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9830     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9831     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9832     LookupResult &Previous) {
9833
9834   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9835   // Disallow mixing of multiversioning types.
9836   if ((OldMVType == MultiVersionKind::Target &&
9837        NewMVType != MultiVersionKind::Target) ||
9838       (NewMVType == MultiVersionKind::Target &&
9839        OldMVType != MultiVersionKind::Target)) {
9840     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9841     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9842     NewFD->setInvalidDecl();
9843     return true;
9844   }
9845
9846   TargetAttr::ParsedTargetAttr NewParsed;
9847   if (NewTA) {
9848     NewParsed = NewTA->parse();
9849     llvm::sort(NewParsed.Features);
9850   }
9851
9852   bool UseMemberUsingDeclRules =
9853       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9854
9855   // Next, check ALL non-overloads to see if this is a redeclaration of a
9856   // previous member of the MultiVersion set.
9857   for (NamedDecl *ND : Previous) {
9858     FunctionDecl *CurFD = ND->getAsFunction();
9859     if (!CurFD)
9860       continue;
9861     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9862       continue;
9863
9864     if (NewMVType == MultiVersionKind::Target) {
9865       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9866       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9867         NewFD->setIsMultiVersion();
9868         Redeclaration = true;
9869         OldDecl = ND;
9870         return false;
9871       }
9872
9873       TargetAttr::ParsedTargetAttr CurParsed =
9874           CurTA->parse(std::less<std::string>());
9875       if (CurParsed == NewParsed) {
9876         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9877         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9878         NewFD->setInvalidDecl();
9879         return true;
9880       }
9881     } else {
9882       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9883       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9884       // Handle CPUDispatch/CPUSpecific versions.
9885       // Only 1 CPUDispatch function is allowed, this will make it go through
9886       // the redeclaration errors.
9887       if (NewMVType == MultiVersionKind::CPUDispatch &&
9888           CurFD->hasAttr<CPUDispatchAttr>()) {
9889         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9890             std::equal(
9891                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9892                 NewCPUDisp->cpus_begin(),
9893                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9894                   return Cur->getName() == New->getName();
9895                 })) {
9896           NewFD->setIsMultiVersion();
9897           Redeclaration = true;
9898           OldDecl = ND;
9899           return false;
9900         }
9901
9902         // If the declarations don't match, this is an error condition.
9903         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9904         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9905         NewFD->setInvalidDecl();
9906         return true;
9907       }
9908       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9909
9910         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9911             std::equal(
9912                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9913                 NewCPUSpec->cpus_begin(),
9914                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9915                   return Cur->getName() == New->getName();
9916                 })) {
9917           NewFD->setIsMultiVersion();
9918           Redeclaration = true;
9919           OldDecl = ND;
9920           return false;
9921         }
9922
9923         // Only 1 version of CPUSpecific is allowed for each CPU.
9924         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9925           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9926             if (CurII == NewII) {
9927               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9928                   << NewII;
9929               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9930               NewFD->setInvalidDecl();
9931               return true;
9932             }
9933           }
9934         }
9935       }
9936       // If the two decls aren't the same MVType, there is no possible error
9937       // condition.
9938     }
9939   }
9940
9941   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9942   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9943   // handled in the attribute adding step.
9944   if (NewMVType == MultiVersionKind::Target &&
9945       CheckMultiVersionValue(S, NewFD)) {
9946     NewFD->setInvalidDecl();
9947     return true;
9948   }
9949
9950   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9951                                        !OldFD->isMultiVersion(), NewMVType)) {
9952     NewFD->setInvalidDecl();
9953     return true;
9954   }
9955
9956   // Permit forward declarations in the case where these two are compatible.
9957   if (!OldFD->isMultiVersion()) {
9958     OldFD->setIsMultiVersion();
9959     NewFD->setIsMultiVersion();
9960     Redeclaration = true;
9961     OldDecl = OldFD;
9962     return false;
9963   }
9964
9965   NewFD->setIsMultiVersion();
9966   Redeclaration = false;
9967   MergeTypeWithPrevious = false;
9968   OldDecl = nullptr;
9969   Previous.clear();
9970   return false;
9971 }
9972
9973
9974 /// Check the validity of a mulitversion function declaration.
9975 /// Also sets the multiversion'ness' of the function itself.
9976 ///
9977 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9978 ///
9979 /// Returns true if there was an error, false otherwise.
9980 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9981                                       bool &Redeclaration, NamedDecl *&OldDecl,
9982                                       bool &MergeTypeWithPrevious,
9983                                       LookupResult &Previous) {
9984   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9985   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9986   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9987
9988   // Mixing Multiversioning types is prohibited.
9989   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9990       (NewCPUDisp && NewCPUSpec)) {
9991     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9992     NewFD->setInvalidDecl();
9993     return true;
9994   }
9995
9996   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9997
9998   // Main isn't allowed to become a multiversion function, however it IS
9999   // permitted to have 'main' be marked with the 'target' optimization hint.
10000   if (NewFD->isMain()) {
10001     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10002         MVType == MultiVersionKind::CPUDispatch ||
10003         MVType == MultiVersionKind::CPUSpecific) {
10004       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10005       NewFD->setInvalidDecl();
10006       return true;
10007     }
10008     return false;
10009   }
10010
10011   if (!OldDecl || !OldDecl->getAsFunction() ||
10012       OldDecl->getDeclContext()->getRedeclContext() !=
10013           NewFD->getDeclContext()->getRedeclContext()) {
10014     // If there's no previous declaration, AND this isn't attempting to cause
10015     // multiversioning, this isn't an error condition.
10016     if (MVType == MultiVersionKind::None)
10017       return false;
10018     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10019   }
10020
10021   FunctionDecl *OldFD = OldDecl->getAsFunction();
10022
10023   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10024     return false;
10025
10026   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10027     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10028         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10029     NewFD->setInvalidDecl();
10030     return true;
10031   }
10032
10033   // Handle the target potentially causes multiversioning case.
10034   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10035     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10036                                             Redeclaration, OldDecl,
10037                                             MergeTypeWithPrevious, Previous);
10038
10039   // At this point, we have a multiversion function decl (in OldFD) AND an
10040   // appropriate attribute in the current function decl.  Resolve that these are
10041   // still compatible with previous declarations.
10042   return CheckMultiVersionAdditionalDecl(
10043       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10044       OldDecl, MergeTypeWithPrevious, Previous);
10045 }
10046
10047 /// Perform semantic checking of a new function declaration.
10048 ///
10049 /// Performs semantic analysis of the new function declaration
10050 /// NewFD. This routine performs all semantic checking that does not
10051 /// require the actual declarator involved in the declaration, and is
10052 /// used both for the declaration of functions as they are parsed
10053 /// (called via ActOnDeclarator) and for the declaration of functions
10054 /// that have been instantiated via C++ template instantiation (called
10055 /// via InstantiateDecl).
10056 ///
10057 /// \param IsMemberSpecialization whether this new function declaration is
10058 /// a member specialization (that replaces any definition provided by the
10059 /// previous declaration).
10060 ///
10061 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10062 ///
10063 /// \returns true if the function declaration is a redeclaration.
10064 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10065                                     LookupResult &Previous,
10066                                     bool IsMemberSpecialization) {
10067   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10068          "Variably modified return types are not handled here");
10069
10070   // Determine whether the type of this function should be merged with
10071   // a previous visible declaration. This never happens for functions in C++,
10072   // and always happens in C if the previous declaration was visible.
10073   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10074                                !Previous.isShadowed();
10075
10076   bool Redeclaration = false;
10077   NamedDecl *OldDecl = nullptr;
10078   bool MayNeedOverloadableChecks = false;
10079
10080   // Merge or overload the declaration with an existing declaration of
10081   // the same name, if appropriate.
10082   if (!Previous.empty()) {
10083     // Determine whether NewFD is an overload of PrevDecl or
10084     // a declaration that requires merging. If it's an overload,
10085     // there's no more work to do here; we'll just add the new
10086     // function to the scope.
10087     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10088       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10089       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10090         Redeclaration = true;
10091         OldDecl = Candidate;
10092       }
10093     } else {
10094       MayNeedOverloadableChecks = true;
10095       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10096                             /*NewIsUsingDecl*/ false)) {
10097       case Ovl_Match:
10098         Redeclaration = true;
10099         break;
10100
10101       case Ovl_NonFunction:
10102         Redeclaration = true;
10103         break;
10104
10105       case Ovl_Overload:
10106         Redeclaration = false;
10107         break;
10108       }
10109     }
10110   }
10111
10112   // Check for a previous extern "C" declaration with this name.
10113   if (!Redeclaration &&
10114       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10115     if (!Previous.empty()) {
10116       // This is an extern "C" declaration with the same name as a previous
10117       // declaration, and thus redeclares that entity...
10118       Redeclaration = true;
10119       OldDecl = Previous.getFoundDecl();
10120       MergeTypeWithPrevious = false;
10121
10122       // ... except in the presence of __attribute__((overloadable)).
10123       if (OldDecl->hasAttr<OverloadableAttr>() ||
10124           NewFD->hasAttr<OverloadableAttr>()) {
10125         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10126           MayNeedOverloadableChecks = true;
10127           Redeclaration = false;
10128           OldDecl = nullptr;
10129         }
10130       }
10131     }
10132   }
10133
10134   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10135                                 MergeTypeWithPrevious, Previous))
10136     return Redeclaration;
10137
10138   // C++11 [dcl.constexpr]p8:
10139   //   A constexpr specifier for a non-static member function that is not
10140   //   a constructor declares that member function to be const.
10141   //
10142   // This needs to be delayed until we know whether this is an out-of-line
10143   // definition of a static member function.
10144   //
10145   // This rule is not present in C++1y, so we produce a backwards
10146   // compatibility warning whenever it happens in C++11.
10147   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10148   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10149       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10150       !MD->getMethodQualifiers().hasConst()) {
10151     CXXMethodDecl *OldMD = nullptr;
10152     if (OldDecl)
10153       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10154     if (!OldMD || !OldMD->isStatic()) {
10155       const FunctionProtoType *FPT =
10156         MD->getType()->castAs<FunctionProtoType>();
10157       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10158       EPI.TypeQuals.addConst();
10159       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10160                                           FPT->getParamTypes(), EPI));
10161
10162       // Warn that we did this, if we're not performing template instantiation.
10163       // In that case, we'll have warned already when the template was defined.
10164       if (!inTemplateInstantiation()) {
10165         SourceLocation AddConstLoc;
10166         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10167                 .IgnoreParens().getAs<FunctionTypeLoc>())
10168           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10169
10170         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10171           << FixItHint::CreateInsertion(AddConstLoc, " const");
10172       }
10173     }
10174   }
10175
10176   if (Redeclaration) {
10177     // NewFD and OldDecl represent declarations that need to be
10178     // merged.
10179     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10180       NewFD->setInvalidDecl();
10181       return Redeclaration;
10182     }
10183
10184     Previous.clear();
10185     Previous.addDecl(OldDecl);
10186
10187     if (FunctionTemplateDecl *OldTemplateDecl =
10188             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10189       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10190       FunctionTemplateDecl *NewTemplateDecl
10191         = NewFD->getDescribedFunctionTemplate();
10192       assert(NewTemplateDecl && "Template/non-template mismatch");
10193
10194       // The call to MergeFunctionDecl above may have created some state in
10195       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10196       // can add it as a redeclaration.
10197       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10198
10199       NewFD->setPreviousDeclaration(OldFD);
10200       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10201       if (NewFD->isCXXClassMember()) {
10202         NewFD->setAccess(OldTemplateDecl->getAccess());
10203         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10204       }
10205
10206       // If this is an explicit specialization of a member that is a function
10207       // template, mark it as a member specialization.
10208       if (IsMemberSpecialization &&
10209           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10210         NewTemplateDecl->setMemberSpecialization();
10211         assert(OldTemplateDecl->isMemberSpecialization());
10212         // Explicit specializations of a member template do not inherit deleted
10213         // status from the parent member template that they are specializing.
10214         if (OldFD->isDeleted()) {
10215           // FIXME: This assert will not hold in the presence of modules.
10216           assert(OldFD->getCanonicalDecl() == OldFD);
10217           // FIXME: We need an update record for this AST mutation.
10218           OldFD->setDeletedAsWritten(false);
10219         }
10220       }
10221
10222     } else {
10223       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10224         auto *OldFD = cast<FunctionDecl>(OldDecl);
10225         // This needs to happen first so that 'inline' propagates.
10226         NewFD->setPreviousDeclaration(OldFD);
10227         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10228         if (NewFD->isCXXClassMember())
10229           NewFD->setAccess(OldFD->getAccess());
10230       }
10231     }
10232   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10233              !NewFD->getAttr<OverloadableAttr>()) {
10234     assert((Previous.empty() ||
10235             llvm::any_of(Previous,
10236                          [](const NamedDecl *ND) {
10237                            return ND->hasAttr<OverloadableAttr>();
10238                          })) &&
10239            "Non-redecls shouldn't happen without overloadable present");
10240
10241     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10242       const auto *FD = dyn_cast<FunctionDecl>(ND);
10243       return FD && !FD->hasAttr<OverloadableAttr>();
10244     });
10245
10246     if (OtherUnmarkedIter != Previous.end()) {
10247       Diag(NewFD->getLocation(),
10248            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10249       Diag((*OtherUnmarkedIter)->getLocation(),
10250            diag::note_attribute_overloadable_prev_overload)
10251           << false;
10252
10253       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10254     }
10255   }
10256
10257   // Semantic checking for this function declaration (in isolation).
10258
10259   if (getLangOpts().CPlusPlus) {
10260     // C++-specific checks.
10261     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10262       CheckConstructor(Constructor);
10263     } else if (CXXDestructorDecl *Destructor =
10264                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10265       CXXRecordDecl *Record = Destructor->getParent();
10266       QualType ClassType = Context.getTypeDeclType(Record);
10267
10268       // FIXME: Shouldn't we be able to perform this check even when the class
10269       // type is dependent? Both gcc and edg can handle that.
10270       if (!ClassType->isDependentType()) {
10271         DeclarationName Name
10272           = Context.DeclarationNames.getCXXDestructorName(
10273                                         Context.getCanonicalType(ClassType));
10274         if (NewFD->getDeclName() != Name) {
10275           Diag(NewFD->getLocation(), diag::err_destructor_name);
10276           NewFD->setInvalidDecl();
10277           return Redeclaration;
10278         }
10279       }
10280     } else if (CXXConversionDecl *Conversion
10281                = dyn_cast<CXXConversionDecl>(NewFD)) {
10282       ActOnConversionDeclarator(Conversion);
10283     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10284       if (auto *TD = Guide->getDescribedFunctionTemplate())
10285         CheckDeductionGuideTemplate(TD);
10286
10287       // A deduction guide is not on the list of entities that can be
10288       // explicitly specialized.
10289       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10290         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10291             << /*explicit specialization*/ 1;
10292     }
10293
10294     // Find any virtual functions that this function overrides.
10295     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10296       if (!Method->isFunctionTemplateSpecialization() &&
10297           !Method->getDescribedFunctionTemplate() &&
10298           Method->isCanonicalDecl()) {
10299         if (AddOverriddenMethods(Method->getParent(), Method)) {
10300           // If the function was marked as "static", we have a problem.
10301           if (NewFD->getStorageClass() == SC_Static) {
10302             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10303           }
10304         }
10305       }
10306
10307       if (Method->isStatic())
10308         checkThisInStaticMemberFunctionType(Method);
10309     }
10310
10311     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10312     if (NewFD->isOverloadedOperator() &&
10313         CheckOverloadedOperatorDeclaration(NewFD)) {
10314       NewFD->setInvalidDecl();
10315       return Redeclaration;
10316     }
10317
10318     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10319     if (NewFD->getLiteralIdentifier() &&
10320         CheckLiteralOperatorDeclaration(NewFD)) {
10321       NewFD->setInvalidDecl();
10322       return Redeclaration;
10323     }
10324
10325     // In C++, check default arguments now that we have merged decls. Unless
10326     // the lexical context is the class, because in this case this is done
10327     // during delayed parsing anyway.
10328     if (!CurContext->isRecord())
10329       CheckCXXDefaultArguments(NewFD);
10330
10331     // If this function declares a builtin function, check the type of this
10332     // declaration against the expected type for the builtin.
10333     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10334       ASTContext::GetBuiltinTypeError Error;
10335       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10336       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10337       // If the type of the builtin differs only in its exception
10338       // specification, that's OK.
10339       // FIXME: If the types do differ in this way, it would be better to
10340       // retain the 'noexcept' form of the type.
10341       if (!T.isNull() &&
10342           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10343                                                             NewFD->getType()))
10344         // The type of this function differs from the type of the builtin,
10345         // so forget about the builtin entirely.
10346         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10347     }
10348
10349     // If this function is declared as being extern "C", then check to see if
10350     // the function returns a UDT (class, struct, or union type) that is not C
10351     // compatible, and if it does, warn the user.
10352     // But, issue any diagnostic on the first declaration only.
10353     if (Previous.empty() && NewFD->isExternC()) {
10354       QualType R = NewFD->getReturnType();
10355       if (R->isIncompleteType() && !R->isVoidType())
10356         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10357             << NewFD << R;
10358       else if (!R.isPODType(Context) && !R->isVoidType() &&
10359                !R->isObjCObjectPointerType())
10360         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10361     }
10362
10363     // C++1z [dcl.fct]p6:
10364     //   [...] whether the function has a non-throwing exception-specification
10365     //   [is] part of the function type
10366     //
10367     // This results in an ABI break between C++14 and C++17 for functions whose
10368     // declared type includes an exception-specification in a parameter or
10369     // return type. (Exception specifications on the function itself are OK in
10370     // most cases, and exception specifications are not permitted in most other
10371     // contexts where they could make it into a mangling.)
10372     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10373       auto HasNoexcept = [&](QualType T) -> bool {
10374         // Strip off declarator chunks that could be between us and a function
10375         // type. We don't need to look far, exception specifications are very
10376         // restricted prior to C++17.
10377         if (auto *RT = T->getAs<ReferenceType>())
10378           T = RT->getPointeeType();
10379         else if (T->isAnyPointerType())
10380           T = T->getPointeeType();
10381         else if (auto *MPT = T->getAs<MemberPointerType>())
10382           T = MPT->getPointeeType();
10383         if (auto *FPT = T->getAs<FunctionProtoType>())
10384           if (FPT->isNothrow())
10385             return true;
10386         return false;
10387       };
10388
10389       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10390       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10391       for (QualType T : FPT->param_types())
10392         AnyNoexcept |= HasNoexcept(T);
10393       if (AnyNoexcept)
10394         Diag(NewFD->getLocation(),
10395              diag::warn_cxx17_compat_exception_spec_in_signature)
10396             << NewFD;
10397     }
10398
10399     if (!Redeclaration && LangOpts.CUDA)
10400       checkCUDATargetOverload(NewFD, Previous);
10401   }
10402   return Redeclaration;
10403 }
10404
10405 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10406   // C++11 [basic.start.main]p3:
10407   //   A program that [...] declares main to be inline, static or
10408   //   constexpr is ill-formed.
10409   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10410   //   appear in a declaration of main.
10411   // static main is not an error under C99, but we should warn about it.
10412   // We accept _Noreturn main as an extension.
10413   if (FD->getStorageClass() == SC_Static)
10414     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10415          ? diag::err_static_main : diag::warn_static_main)
10416       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10417   if (FD->isInlineSpecified())
10418     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10419       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10420   if (DS.isNoreturnSpecified()) {
10421     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10422     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10423     Diag(NoreturnLoc, diag::ext_noreturn_main);
10424     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10425       << FixItHint::CreateRemoval(NoreturnRange);
10426   }
10427   if (FD->isConstexpr()) {
10428     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10429         << FD->isConsteval()
10430         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10431     FD->setConstexprKind(CSK_unspecified);
10432   }
10433
10434   if (getLangOpts().OpenCL) {
10435     Diag(FD->getLocation(), diag::err_opencl_no_main)
10436         << FD->hasAttr<OpenCLKernelAttr>();
10437     FD->setInvalidDecl();
10438     return;
10439   }
10440
10441   QualType T = FD->getType();
10442   assert(T->isFunctionType() && "function decl is not of function type");
10443   const FunctionType* FT = T->castAs<FunctionType>();
10444
10445   // Set default calling convention for main()
10446   if (FT->getCallConv() != CC_C) {
10447     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10448     FD->setType(QualType(FT, 0));
10449     T = Context.getCanonicalType(FD->getType());
10450   }
10451
10452   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10453     // In C with GNU extensions we allow main() to have non-integer return
10454     // type, but we should warn about the extension, and we disable the
10455     // implicit-return-zero rule.
10456
10457     // GCC in C mode accepts qualified 'int'.
10458     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10459       FD->setHasImplicitReturnZero(true);
10460     else {
10461       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10462       SourceRange RTRange = FD->getReturnTypeSourceRange();
10463       if (RTRange.isValid())
10464         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10465             << FixItHint::CreateReplacement(RTRange, "int");
10466     }
10467   } else {
10468     // In C and C++, main magically returns 0 if you fall off the end;
10469     // set the flag which tells us that.
10470     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10471
10472     // All the standards say that main() should return 'int'.
10473     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10474       FD->setHasImplicitReturnZero(true);
10475     else {
10476       // Otherwise, this is just a flat-out error.
10477       SourceRange RTRange = FD->getReturnTypeSourceRange();
10478       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10479           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10480                                 : FixItHint());
10481       FD->setInvalidDecl(true);
10482     }
10483   }
10484
10485   // Treat protoless main() as nullary.
10486   if (isa<FunctionNoProtoType>(FT)) return;
10487
10488   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10489   unsigned nparams = FTP->getNumParams();
10490   assert(FD->getNumParams() == nparams);
10491
10492   bool HasExtraParameters = (nparams > 3);
10493
10494   if (FTP->isVariadic()) {
10495     Diag(FD->getLocation(), diag::ext_variadic_main);
10496     // FIXME: if we had information about the location of the ellipsis, we
10497     // could add a FixIt hint to remove it as a parameter.
10498   }
10499
10500   // Darwin passes an undocumented fourth argument of type char**.  If
10501   // other platforms start sprouting these, the logic below will start
10502   // getting shifty.
10503   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10504     HasExtraParameters = false;
10505
10506   if (HasExtraParameters) {
10507     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10508     FD->setInvalidDecl(true);
10509     nparams = 3;
10510   }
10511
10512   // FIXME: a lot of the following diagnostics would be improved
10513   // if we had some location information about types.
10514
10515   QualType CharPP =
10516     Context.getPointerType(Context.getPointerType(Context.CharTy));
10517   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10518
10519   for (unsigned i = 0; i < nparams; ++i) {
10520     QualType AT = FTP->getParamType(i);
10521
10522     bool mismatch = true;
10523
10524     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10525       mismatch = false;
10526     else if (Expected[i] == CharPP) {
10527       // As an extension, the following forms are okay:
10528       //   char const **
10529       //   char const * const *
10530       //   char * const *
10531
10532       QualifierCollector qs;
10533       const PointerType* PT;
10534       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10535           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10536           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10537                               Context.CharTy)) {
10538         qs.removeConst();
10539         mismatch = !qs.empty();
10540       }
10541     }
10542
10543     if (mismatch) {
10544       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10545       // TODO: suggest replacing given type with expected type
10546       FD->setInvalidDecl(true);
10547     }
10548   }
10549
10550   if (nparams == 1 && !FD->isInvalidDecl()) {
10551     Diag(FD->getLocation(), diag::warn_main_one_arg);
10552   }
10553
10554   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10555     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10556     FD->setInvalidDecl();
10557   }
10558 }
10559
10560 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10561   QualType T = FD->getType();
10562   assert(T->isFunctionType() && "function decl is not of function type");
10563   const FunctionType *FT = T->castAs<FunctionType>();
10564
10565   // Set an implicit return of 'zero' if the function can return some integral,
10566   // enumeration, pointer or nullptr type.
10567   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10568       FT->getReturnType()->isAnyPointerType() ||
10569       FT->getReturnType()->isNullPtrType())
10570     // DllMain is exempt because a return value of zero means it failed.
10571     if (FD->getName() != "DllMain")
10572       FD->setHasImplicitReturnZero(true);
10573
10574   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10575     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10576     FD->setInvalidDecl();
10577   }
10578 }
10579
10580 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10581   // FIXME: Need strict checking.  In C89, we need to check for
10582   // any assignment, increment, decrement, function-calls, or
10583   // commas outside of a sizeof.  In C99, it's the same list,
10584   // except that the aforementioned are allowed in unevaluated
10585   // expressions.  Everything else falls under the
10586   // "may accept other forms of constant expressions" exception.
10587   // (We never end up here for C++, so the constant expression
10588   // rules there don't matter.)
10589   const Expr *Culprit;
10590   if (Init->isConstantInitializer(Context, false, &Culprit))
10591     return false;
10592   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10593     << Culprit->getSourceRange();
10594   return true;
10595 }
10596
10597 namespace {
10598   // Visits an initialization expression to see if OrigDecl is evaluated in
10599   // its own initialization and throws a warning if it does.
10600   class SelfReferenceChecker
10601       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10602     Sema &S;
10603     Decl *OrigDecl;
10604     bool isRecordType;
10605     bool isPODType;
10606     bool isReferenceType;
10607
10608     bool isInitList;
10609     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10610
10611   public:
10612     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10613
10614     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10615                                                     S(S), OrigDecl(OrigDecl) {
10616       isPODType = false;
10617       isRecordType = false;
10618       isReferenceType = false;
10619       isInitList = false;
10620       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10621         isPODType = VD->getType().isPODType(S.Context);
10622         isRecordType = VD->getType()->isRecordType();
10623         isReferenceType = VD->getType()->isReferenceType();
10624       }
10625     }
10626
10627     // For most expressions, just call the visitor.  For initializer lists,
10628     // track the index of the field being initialized since fields are
10629     // initialized in order allowing use of previously initialized fields.
10630     void CheckExpr(Expr *E) {
10631       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10632       if (!InitList) {
10633         Visit(E);
10634         return;
10635       }
10636
10637       // Track and increment the index here.
10638       isInitList = true;
10639       InitFieldIndex.push_back(0);
10640       for (auto Child : InitList->children()) {
10641         CheckExpr(cast<Expr>(Child));
10642         ++InitFieldIndex.back();
10643       }
10644       InitFieldIndex.pop_back();
10645     }
10646
10647     // Returns true if MemberExpr is checked and no further checking is needed.
10648     // Returns false if additional checking is required.
10649     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10650       llvm::SmallVector<FieldDecl*, 4> Fields;
10651       Expr *Base = E;
10652       bool ReferenceField = false;
10653
10654       // Get the field members used.
10655       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10656         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10657         if (!FD)
10658           return false;
10659         Fields.push_back(FD);
10660         if (FD->getType()->isReferenceType())
10661           ReferenceField = true;
10662         Base = ME->getBase()->IgnoreParenImpCasts();
10663       }
10664
10665       // Keep checking only if the base Decl is the same.
10666       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10667       if (!DRE || DRE->getDecl() != OrigDecl)
10668         return false;
10669
10670       // A reference field can be bound to an unininitialized field.
10671       if (CheckReference && !ReferenceField)
10672         return true;
10673
10674       // Convert FieldDecls to their index number.
10675       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10676       for (const FieldDecl *I : llvm::reverse(Fields))
10677         UsedFieldIndex.push_back(I->getFieldIndex());
10678
10679       // See if a warning is needed by checking the first difference in index
10680       // numbers.  If field being used has index less than the field being
10681       // initialized, then the use is safe.
10682       for (auto UsedIter = UsedFieldIndex.begin(),
10683                 UsedEnd = UsedFieldIndex.end(),
10684                 OrigIter = InitFieldIndex.begin(),
10685                 OrigEnd = InitFieldIndex.end();
10686            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10687         if (*UsedIter < *OrigIter)
10688           return true;
10689         if (*UsedIter > *OrigIter)
10690           break;
10691       }
10692
10693       // TODO: Add a different warning which will print the field names.
10694       HandleDeclRefExpr(DRE);
10695       return true;
10696     }
10697
10698     // For most expressions, the cast is directly above the DeclRefExpr.
10699     // For conditional operators, the cast can be outside the conditional
10700     // operator if both expressions are DeclRefExpr's.
10701     void HandleValue(Expr *E) {
10702       E = E->IgnoreParens();
10703       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10704         HandleDeclRefExpr(DRE);
10705         return;
10706       }
10707
10708       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10709         Visit(CO->getCond());
10710         HandleValue(CO->getTrueExpr());
10711         HandleValue(CO->getFalseExpr());
10712         return;
10713       }
10714
10715       if (BinaryConditionalOperator *BCO =
10716               dyn_cast<BinaryConditionalOperator>(E)) {
10717         Visit(BCO->getCond());
10718         HandleValue(BCO->getFalseExpr());
10719         return;
10720       }
10721
10722       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10723         HandleValue(OVE->getSourceExpr());
10724         return;
10725       }
10726
10727       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10728         if (BO->getOpcode() == BO_Comma) {
10729           Visit(BO->getLHS());
10730           HandleValue(BO->getRHS());
10731           return;
10732         }
10733       }
10734
10735       if (isa<MemberExpr>(E)) {
10736         if (isInitList) {
10737           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10738                                       false /*CheckReference*/))
10739             return;
10740         }
10741
10742         Expr *Base = E->IgnoreParenImpCasts();
10743         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10744           // Check for static member variables and don't warn on them.
10745           if (!isa<FieldDecl>(ME->getMemberDecl()))
10746             return;
10747           Base = ME->getBase()->IgnoreParenImpCasts();
10748         }
10749         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10750           HandleDeclRefExpr(DRE);
10751         return;
10752       }
10753
10754       Visit(E);
10755     }
10756
10757     // Reference types not handled in HandleValue are handled here since all
10758     // uses of references are bad, not just r-value uses.
10759     void VisitDeclRefExpr(DeclRefExpr *E) {
10760       if (isReferenceType)
10761         HandleDeclRefExpr(E);
10762     }
10763
10764     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10765       if (E->getCastKind() == CK_LValueToRValue) {
10766         HandleValue(E->getSubExpr());
10767         return;
10768       }
10769
10770       Inherited::VisitImplicitCastExpr(E);
10771     }
10772
10773     void VisitMemberExpr(MemberExpr *E) {
10774       if (isInitList) {
10775         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10776           return;
10777       }
10778
10779       // Don't warn on arrays since they can be treated as pointers.
10780       if (E->getType()->canDecayToPointerType()) return;
10781
10782       // Warn when a non-static method call is followed by non-static member
10783       // field accesses, which is followed by a DeclRefExpr.
10784       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10785       bool Warn = (MD && !MD->isStatic());
10786       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10787       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10788         if (!isa<FieldDecl>(ME->getMemberDecl()))
10789           Warn = false;
10790         Base = ME->getBase()->IgnoreParenImpCasts();
10791       }
10792
10793       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10794         if (Warn)
10795           HandleDeclRefExpr(DRE);
10796         return;
10797       }
10798
10799       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10800       // Visit that expression.
10801       Visit(Base);
10802     }
10803
10804     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10805       Expr *Callee = E->getCallee();
10806
10807       if (isa<UnresolvedLookupExpr>(Callee))
10808         return Inherited::VisitCXXOperatorCallExpr(E);
10809
10810       Visit(Callee);
10811       for (auto Arg: E->arguments())
10812         HandleValue(Arg->IgnoreParenImpCasts());
10813     }
10814
10815     void VisitUnaryOperator(UnaryOperator *E) {
10816       // For POD record types, addresses of its own members are well-defined.
10817       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10818           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10819         if (!isPODType)
10820           HandleValue(E->getSubExpr());
10821         return;
10822       }
10823
10824       if (E->isIncrementDecrementOp()) {
10825         HandleValue(E->getSubExpr());
10826         return;
10827       }
10828
10829       Inherited::VisitUnaryOperator(E);
10830     }
10831
10832     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10833
10834     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10835       if (E->getConstructor()->isCopyConstructor()) {
10836         Expr *ArgExpr = E->getArg(0);
10837         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10838           if (ILE->getNumInits() == 1)
10839             ArgExpr = ILE->getInit(0);
10840         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10841           if (ICE->getCastKind() == CK_NoOp)
10842             ArgExpr = ICE->getSubExpr();
10843         HandleValue(ArgExpr);
10844         return;
10845       }
10846       Inherited::VisitCXXConstructExpr(E);
10847     }
10848
10849     void VisitCallExpr(CallExpr *E) {
10850       // Treat std::move as a use.
10851       if (E->isCallToStdMove()) {
10852         HandleValue(E->getArg(0));
10853         return;
10854       }
10855
10856       Inherited::VisitCallExpr(E);
10857     }
10858
10859     void VisitBinaryOperator(BinaryOperator *E) {
10860       if (E->isCompoundAssignmentOp()) {
10861         HandleValue(E->getLHS());
10862         Visit(E->getRHS());
10863         return;
10864       }
10865
10866       Inherited::VisitBinaryOperator(E);
10867     }
10868
10869     // A custom visitor for BinaryConditionalOperator is needed because the
10870     // regular visitor would check the condition and true expression separately
10871     // but both point to the same place giving duplicate diagnostics.
10872     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10873       Visit(E->getCond());
10874       Visit(E->getFalseExpr());
10875     }
10876
10877     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10878       Decl* ReferenceDecl = DRE->getDecl();
10879       if (OrigDecl != ReferenceDecl) return;
10880       unsigned diag;
10881       if (isReferenceType) {
10882         diag = diag::warn_uninit_self_reference_in_reference_init;
10883       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10884         diag = diag::warn_static_self_reference_in_init;
10885       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10886                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10887                  DRE->getDecl()->getType()->isRecordType()) {
10888         diag = diag::warn_uninit_self_reference_in_init;
10889       } else {
10890         // Local variables will be handled by the CFG analysis.
10891         return;
10892       }
10893
10894       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10895                             S.PDiag(diag)
10896                                 << DRE->getDecl() << OrigDecl->getLocation()
10897                                 << DRE->getSourceRange());
10898     }
10899   };
10900
10901   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10902   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10903                                  bool DirectInit) {
10904     // Parameters arguments are occassionially constructed with itself,
10905     // for instance, in recursive functions.  Skip them.
10906     if (isa<ParmVarDecl>(OrigDecl))
10907       return;
10908
10909     E = E->IgnoreParens();
10910
10911     // Skip checking T a = a where T is not a record or reference type.
10912     // Doing so is a way to silence uninitialized warnings.
10913     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10914       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10915         if (ICE->getCastKind() == CK_LValueToRValue)
10916           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10917             if (DRE->getDecl() == OrigDecl)
10918               return;
10919
10920     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10921   }
10922 } // end anonymous namespace
10923
10924 namespace {
10925   // Simple wrapper to add the name of a variable or (if no variable is
10926   // available) a DeclarationName into a diagnostic.
10927   struct VarDeclOrName {
10928     VarDecl *VDecl;
10929     DeclarationName Name;
10930
10931     friend const Sema::SemaDiagnosticBuilder &
10932     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10933       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10934     }
10935   };
10936 } // end anonymous namespace
10937
10938 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10939                                             DeclarationName Name, QualType Type,
10940                                             TypeSourceInfo *TSI,
10941                                             SourceRange Range, bool DirectInit,
10942                                             Expr *Init) {
10943   bool IsInitCapture = !VDecl;
10944   assert((!VDecl || !VDecl->isInitCapture()) &&
10945          "init captures are expected to be deduced prior to initialization");
10946
10947   VarDeclOrName VN{VDecl, Name};
10948
10949   DeducedType *Deduced = Type->getContainedDeducedType();
10950   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10951
10952   // C++11 [dcl.spec.auto]p3
10953   if (!Init) {
10954     assert(VDecl && "no init for init capture deduction?");
10955
10956     // Except for class argument deduction, and then for an initializing
10957     // declaration only, i.e. no static at class scope or extern.
10958     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10959         VDecl->hasExternalStorage() ||
10960         VDecl->isStaticDataMember()) {
10961       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10962         << VDecl->getDeclName() << Type;
10963       return QualType();
10964     }
10965   }
10966
10967   ArrayRef<Expr*> DeduceInits;
10968   if (Init)
10969     DeduceInits = Init;
10970
10971   if (DirectInit) {
10972     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10973       DeduceInits = PL->exprs();
10974   }
10975
10976   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10977     assert(VDecl && "non-auto type for init capture deduction?");
10978     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10979     InitializationKind Kind = InitializationKind::CreateForInit(
10980         VDecl->getLocation(), DirectInit, Init);
10981     // FIXME: Initialization should not be taking a mutable list of inits.
10982     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10983     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10984                                                        InitsCopy);
10985   }
10986
10987   if (DirectInit) {
10988     if (auto *IL = dyn_cast<InitListExpr>(Init))
10989       DeduceInits = IL->inits();
10990   }
10991
10992   // Deduction only works if we have exactly one source expression.
10993   if (DeduceInits.empty()) {
10994     // It isn't possible to write this directly, but it is possible to
10995     // end up in this situation with "auto x(some_pack...);"
10996     Diag(Init->getBeginLoc(), IsInitCapture
10997                                   ? diag::err_init_capture_no_expression
10998                                   : diag::err_auto_var_init_no_expression)
10999         << VN << Type << Range;
11000     return QualType();
11001   }
11002
11003   if (DeduceInits.size() > 1) {
11004     Diag(DeduceInits[1]->getBeginLoc(),
11005          IsInitCapture ? diag::err_init_capture_multiple_expressions
11006                        : diag::err_auto_var_init_multiple_expressions)
11007         << VN << Type << Range;
11008     return QualType();
11009   }
11010
11011   Expr *DeduceInit = DeduceInits[0];
11012   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11013     Diag(Init->getBeginLoc(), IsInitCapture
11014                                   ? diag::err_init_capture_paren_braces
11015                                   : diag::err_auto_var_init_paren_braces)
11016         << isa<InitListExpr>(Init) << VN << Type << Range;
11017     return QualType();
11018   }
11019
11020   // Expressions default to 'id' when we're in a debugger.
11021   bool DefaultedAnyToId = false;
11022   if (getLangOpts().DebuggerCastResultToId &&
11023       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11024     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11025     if (Result.isInvalid()) {
11026       return QualType();
11027     }
11028     Init = Result.get();
11029     DefaultedAnyToId = true;
11030   }
11031
11032   // C++ [dcl.decomp]p1:
11033   //   If the assignment-expression [...] has array type A and no ref-qualifier
11034   //   is present, e has type cv A
11035   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11036       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11037       DeduceInit->getType()->isConstantArrayType())
11038     return Context.getQualifiedType(DeduceInit->getType(),
11039                                     Type.getQualifiers());
11040
11041   QualType DeducedType;
11042   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11043     if (!IsInitCapture)
11044       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11045     else if (isa<InitListExpr>(Init))
11046       Diag(Range.getBegin(),
11047            diag::err_init_capture_deduction_failure_from_init_list)
11048           << VN
11049           << (DeduceInit->getType().isNull() ? TSI->getType()
11050                                              : DeduceInit->getType())
11051           << DeduceInit->getSourceRange();
11052     else
11053       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11054           << VN << TSI->getType()
11055           << (DeduceInit->getType().isNull() ? TSI->getType()
11056                                              : DeduceInit->getType())
11057           << DeduceInit->getSourceRange();
11058   }
11059
11060   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11061   // 'id' instead of a specific object type prevents most of our usual
11062   // checks.
11063   // We only want to warn outside of template instantiations, though:
11064   // inside a template, the 'id' could have come from a parameter.
11065   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11066       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11067     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11068     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11069   }
11070
11071   return DeducedType;
11072 }
11073
11074 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11075                                          Expr *Init) {
11076   QualType DeducedType = deduceVarTypeFromInitializer(
11077       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11078       VDecl->getSourceRange(), DirectInit, Init);
11079   if (DeducedType.isNull()) {
11080     VDecl->setInvalidDecl();
11081     return true;
11082   }
11083
11084   VDecl->setType(DeducedType);
11085   assert(VDecl->isLinkageValid());
11086
11087   // In ARC, infer lifetime.
11088   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11089     VDecl->setInvalidDecl();
11090
11091   // If this is a redeclaration, check that the type we just deduced matches
11092   // the previously declared type.
11093   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11094     // We never need to merge the type, because we cannot form an incomplete
11095     // array of auto, nor deduce such a type.
11096     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11097   }
11098
11099   // Check the deduced type is valid for a variable declaration.
11100   CheckVariableDeclarationType(VDecl);
11101   return VDecl->isInvalidDecl();
11102 }
11103
11104 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11105                                               SourceLocation Loc) {
11106   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11107     Init = CE->getSubExpr();
11108
11109   QualType InitType = Init->getType();
11110   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11111           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11112          "shouldn't be called if type doesn't have a non-trivial C struct");
11113   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11114     for (auto I : ILE->inits()) {
11115       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11116           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11117         continue;
11118       SourceLocation SL = I->getExprLoc();
11119       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11120     }
11121     return;
11122   }
11123
11124   if (isa<ImplicitValueInitExpr>(Init)) {
11125     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11126       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11127                             NTCUK_Init);
11128   } else {
11129     // Assume all other explicit initializers involving copying some existing
11130     // object.
11131     // TODO: ignore any explicit initializers where we can guarantee
11132     // copy-elision.
11133     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11134       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11135   }
11136 }
11137
11138 namespace {
11139
11140 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11141     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11142                                     void> {
11143   using Super =
11144       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11145                                     void>;
11146
11147   DiagNonTrivalCUnionDefaultInitializeVisitor(
11148       QualType OrigTy, SourceLocation OrigLoc,
11149       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11150       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11151
11152   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11153                      const FieldDecl *FD, bool InNonTrivialUnion) {
11154     if (const auto *AT = S.Context.getAsArrayType(QT))
11155       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11156                                      InNonTrivialUnion);
11157     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11158   }
11159
11160   void visitARCStrong(QualType QT, const FieldDecl *FD,
11161                       bool InNonTrivialUnion) {
11162     if (InNonTrivialUnion)
11163       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11164           << 1 << 0 << QT << FD->getName();
11165   }
11166
11167   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11168     if (InNonTrivialUnion)
11169       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11170           << 1 << 0 << QT << FD->getName();
11171   }
11172
11173   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11174     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11175     if (RD->isUnion()) {
11176       if (OrigLoc.isValid()) {
11177         bool IsUnion = false;
11178         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11179           IsUnion = OrigRD->isUnion();
11180         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11181             << 0 << OrigTy << IsUnion << UseContext;
11182         // Reset OrigLoc so that this diagnostic is emitted only once.
11183         OrigLoc = SourceLocation();
11184       }
11185       InNonTrivialUnion = true;
11186     }
11187
11188     if (InNonTrivialUnion)
11189       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11190           << 0 << 0 << QT.getUnqualifiedType() << "";
11191
11192     for (const FieldDecl *FD : RD->fields())
11193       asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11194   }
11195
11196   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11197
11198   // The non-trivial C union type or the struct/union type that contains a
11199   // non-trivial C union.
11200   QualType OrigTy;
11201   SourceLocation OrigLoc;
11202   Sema::NonTrivialCUnionContext UseContext;
11203   Sema &S;
11204 };
11205
11206 struct DiagNonTrivalCUnionDestructedTypeVisitor
11207     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11208   using Super =
11209       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11210
11211   DiagNonTrivalCUnionDestructedTypeVisitor(
11212       QualType OrigTy, SourceLocation OrigLoc,
11213       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11214       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11215
11216   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11217                      const FieldDecl *FD, bool InNonTrivialUnion) {
11218     if (const auto *AT = S.Context.getAsArrayType(QT))
11219       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11220                                      InNonTrivialUnion);
11221     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11222   }
11223
11224   void visitARCStrong(QualType QT, const FieldDecl *FD,
11225                       bool InNonTrivialUnion) {
11226     if (InNonTrivialUnion)
11227       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11228           << 1 << 1 << QT << FD->getName();
11229   }
11230
11231   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11232     if (InNonTrivialUnion)
11233       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11234           << 1 << 1 << QT << FD->getName();
11235   }
11236
11237   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11238     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11239     if (RD->isUnion()) {
11240       if (OrigLoc.isValid()) {
11241         bool IsUnion = false;
11242         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11243           IsUnion = OrigRD->isUnion();
11244         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11245             << 1 << OrigTy << IsUnion << UseContext;
11246         // Reset OrigLoc so that this diagnostic is emitted only once.
11247         OrigLoc = SourceLocation();
11248       }
11249       InNonTrivialUnion = true;
11250     }
11251
11252     if (InNonTrivialUnion)
11253       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11254           << 0 << 1 << QT.getUnqualifiedType() << "";
11255
11256     for (const FieldDecl *FD : RD->fields())
11257       asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11258   }
11259
11260   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11261   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11262                           bool InNonTrivialUnion) {}
11263
11264   // The non-trivial C union type or the struct/union type that contains a
11265   // non-trivial C union.
11266   QualType OrigTy;
11267   SourceLocation OrigLoc;
11268   Sema::NonTrivialCUnionContext UseContext;
11269   Sema &S;
11270 };
11271
11272 struct DiagNonTrivalCUnionCopyVisitor
11273     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11274   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11275
11276   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11277                                  Sema::NonTrivialCUnionContext UseContext,
11278                                  Sema &S)
11279       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11280
11281   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11282                      const FieldDecl *FD, bool InNonTrivialUnion) {
11283     if (const auto *AT = S.Context.getAsArrayType(QT))
11284       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11285                                      InNonTrivialUnion);
11286     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11287   }
11288
11289   void visitARCStrong(QualType QT, const FieldDecl *FD,
11290                       bool InNonTrivialUnion) {
11291     if (InNonTrivialUnion)
11292       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11293           << 1 << 2 << QT << FD->getName();
11294   }
11295
11296   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11297     if (InNonTrivialUnion)
11298       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11299           << 1 << 2 << QT << FD->getName();
11300   }
11301
11302   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11303     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11304     if (RD->isUnion()) {
11305       if (OrigLoc.isValid()) {
11306         bool IsUnion = false;
11307         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11308           IsUnion = OrigRD->isUnion();
11309         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11310             << 2 << OrigTy << IsUnion << UseContext;
11311         // Reset OrigLoc so that this diagnostic is emitted only once.
11312         OrigLoc = SourceLocation();
11313       }
11314       InNonTrivialUnion = true;
11315     }
11316
11317     if (InNonTrivialUnion)
11318       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11319           << 0 << 2 << QT.getUnqualifiedType() << "";
11320
11321     for (const FieldDecl *FD : RD->fields())
11322       asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11323   }
11324
11325   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11326                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11327   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11328   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11329                             bool InNonTrivialUnion) {}
11330
11331   // The non-trivial C union type or the struct/union type that contains a
11332   // non-trivial C union.
11333   QualType OrigTy;
11334   SourceLocation OrigLoc;
11335   Sema::NonTrivialCUnionContext UseContext;
11336   Sema &S;
11337 };
11338
11339 } // namespace
11340
11341 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11342                                  NonTrivialCUnionContext UseContext,
11343                                  unsigned NonTrivialKind) {
11344   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11345           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11346           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11347          "shouldn't be called if type doesn't have a non-trivial C union");
11348
11349   if ((NonTrivialKind & NTCUK_Init) &&
11350       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11351     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11352         .visit(QT, nullptr, false);
11353   if ((NonTrivialKind & NTCUK_Destruct) &&
11354       QT.hasNonTrivialToPrimitiveDestructCUnion())
11355     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11356         .visit(QT, nullptr, false);
11357   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11358     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11359         .visit(QT, nullptr, false);
11360 }
11361
11362 /// AddInitializerToDecl - Adds the initializer Init to the
11363 /// declaration dcl. If DirectInit is true, this is C++ direct
11364 /// initialization rather than copy initialization.
11365 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11366   // If there is no declaration, there was an error parsing it.  Just ignore
11367   // the initializer.
11368   if (!RealDecl || RealDecl->isInvalidDecl()) {
11369     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11370     return;
11371   }
11372
11373   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11374     // Pure-specifiers are handled in ActOnPureSpecifier.
11375     Diag(Method->getLocation(), diag::err_member_function_initialization)
11376       << Method->getDeclName() << Init->getSourceRange();
11377     Method->setInvalidDecl();
11378     return;
11379   }
11380
11381   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11382   if (!VDecl) {
11383     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11384     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11385     RealDecl->setInvalidDecl();
11386     return;
11387   }
11388
11389   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11390   if (VDecl->getType()->isUndeducedType()) {
11391     // Attempt typo correction early so that the type of the init expression can
11392     // be deduced based on the chosen correction if the original init contains a
11393     // TypoExpr.
11394     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11395     if (!Res.isUsable()) {
11396       RealDecl->setInvalidDecl();
11397       return;
11398     }
11399     Init = Res.get();
11400
11401     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11402       return;
11403   }
11404
11405   // dllimport cannot be used on variable definitions.
11406   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11407     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11408     VDecl->setInvalidDecl();
11409     return;
11410   }
11411
11412   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11413     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11414     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11415     VDecl->setInvalidDecl();
11416     return;
11417   }
11418
11419   if (!VDecl->getType()->isDependentType()) {
11420     // A definition must end up with a complete type, which means it must be
11421     // complete with the restriction that an array type might be completed by
11422     // the initializer; note that later code assumes this restriction.
11423     QualType BaseDeclType = VDecl->getType();
11424     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11425       BaseDeclType = Array->getElementType();
11426     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11427                             diag::err_typecheck_decl_incomplete_type)) {
11428       RealDecl->setInvalidDecl();
11429       return;
11430     }
11431
11432     // The variable can not have an abstract class type.
11433     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11434                                diag::err_abstract_type_in_decl,
11435                                AbstractVariableType))
11436       VDecl->setInvalidDecl();
11437   }
11438
11439   // If adding the initializer will turn this declaration into a definition,
11440   // and we already have a definition for this variable, diagnose or otherwise
11441   // handle the situation.
11442   VarDecl *Def;
11443   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11444       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11445       !VDecl->isThisDeclarationADemotedDefinition() &&
11446       checkVarDeclRedefinition(Def, VDecl))
11447     return;
11448
11449   if (getLangOpts().CPlusPlus) {
11450     // C++ [class.static.data]p4
11451     //   If a static data member is of const integral or const
11452     //   enumeration type, its declaration in the class definition can
11453     //   specify a constant-initializer which shall be an integral
11454     //   constant expression (5.19). In that case, the member can appear
11455     //   in integral constant expressions. The member shall still be
11456     //   defined in a namespace scope if it is used in the program and the
11457     //   namespace scope definition shall not contain an initializer.
11458     //
11459     // We already performed a redefinition check above, but for static
11460     // data members we also need to check whether there was an in-class
11461     // declaration with an initializer.
11462     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11463       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11464           << VDecl->getDeclName();
11465       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11466            diag::note_previous_initializer)
11467           << 0;
11468       return;
11469     }
11470
11471     if (VDecl->hasLocalStorage())
11472       setFunctionHasBranchProtectedScope();
11473
11474     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11475       VDecl->setInvalidDecl();
11476       return;
11477     }
11478   }
11479
11480   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11481   // a kernel function cannot be initialized."
11482   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11483     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11484     VDecl->setInvalidDecl();
11485     return;
11486   }
11487
11488   // Get the decls type and save a reference for later, since
11489   // CheckInitializerTypes may change it.
11490   QualType DclT = VDecl->getType(), SavT = DclT;
11491
11492   // Expressions default to 'id' when we're in a debugger
11493   // and we are assigning it to a variable of Objective-C pointer type.
11494   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11495       Init->getType() == Context.UnknownAnyTy) {
11496     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11497     if (Result.isInvalid()) {
11498       VDecl->setInvalidDecl();
11499       return;
11500     }
11501     Init = Result.get();
11502   }
11503
11504   // Perform the initialization.
11505   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11506   if (!VDecl->isInvalidDecl()) {
11507     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11508     InitializationKind Kind = InitializationKind::CreateForInit(
11509         VDecl->getLocation(), DirectInit, Init);
11510
11511     MultiExprArg Args = Init;
11512     if (CXXDirectInit)
11513       Args = MultiExprArg(CXXDirectInit->getExprs(),
11514                           CXXDirectInit->getNumExprs());
11515
11516     // Try to correct any TypoExprs in the initialization arguments.
11517     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11518       ExprResult Res = CorrectDelayedTyposInExpr(
11519           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11520             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11521             return Init.Failed() ? ExprError() : E;
11522           });
11523       if (Res.isInvalid()) {
11524         VDecl->setInvalidDecl();
11525       } else if (Res.get() != Args[Idx]) {
11526         Args[Idx] = Res.get();
11527       }
11528     }
11529     if (VDecl->isInvalidDecl())
11530       return;
11531
11532     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11533                                    /*TopLevelOfInitList=*/false,
11534                                    /*TreatUnavailableAsInvalid=*/false);
11535     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11536     if (Result.isInvalid()) {
11537       VDecl->setInvalidDecl();
11538       return;
11539     }
11540
11541     Init = Result.getAs<Expr>();
11542   }
11543
11544   // Check for self-references within variable initializers.
11545   // Variables declared within a function/method body (except for references)
11546   // are handled by a dataflow analysis.
11547   // This is undefined behavior in C++, but valid in C.
11548   if (getLangOpts().CPlusPlus) {
11549     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11550         VDecl->getType()->isReferenceType()) {
11551       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11552     }
11553   }
11554
11555   // If the type changed, it means we had an incomplete type that was
11556   // completed by the initializer. For example:
11557   //   int ary[] = { 1, 3, 5 };
11558   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11559   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11560     VDecl->setType(DclT);
11561
11562   if (!VDecl->isInvalidDecl()) {
11563     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11564
11565     if (VDecl->hasAttr<BlocksAttr>())
11566       checkRetainCycles(VDecl, Init);
11567
11568     // It is safe to assign a weak reference into a strong variable.
11569     // Although this code can still have problems:
11570     //   id x = self.weakProp;
11571     //   id y = self.weakProp;
11572     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11573     // paths through the function. This should be revisited if
11574     // -Wrepeated-use-of-weak is made flow-sensitive.
11575     if (FunctionScopeInfo *FSI = getCurFunction())
11576       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11577            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11578           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11579                            Init->getBeginLoc()))
11580         FSI->markSafeWeakUse(Init);
11581   }
11582
11583   // The initialization is usually a full-expression.
11584   //
11585   // FIXME: If this is a braced initialization of an aggregate, it is not
11586   // an expression, and each individual field initializer is a separate
11587   // full-expression. For instance, in:
11588   //
11589   //   struct Temp { ~Temp(); };
11590   //   struct S { S(Temp); };
11591   //   struct T { S a, b; } t = { Temp(), Temp() }
11592   //
11593   // we should destroy the first Temp before constructing the second.
11594   ExprResult Result =
11595       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11596                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11597   if (Result.isInvalid()) {
11598     VDecl->setInvalidDecl();
11599     return;
11600   }
11601   Init = Result.get();
11602
11603   // Attach the initializer to the decl.
11604   VDecl->setInit(Init);
11605
11606   if (VDecl->isLocalVarDecl()) {
11607     // Don't check the initializer if the declaration is malformed.
11608     if (VDecl->isInvalidDecl()) {
11609       // do nothing
11610
11611     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11612     // This is true even in C++ for OpenCL.
11613     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11614       CheckForConstantInitializer(Init, DclT);
11615
11616     // Otherwise, C++ does not restrict the initializer.
11617     } else if (getLangOpts().CPlusPlus) {
11618       // do nothing
11619
11620     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11621     // static storage duration shall be constant expressions or string literals.
11622     } else if (VDecl->getStorageClass() == SC_Static) {
11623       CheckForConstantInitializer(Init, DclT);
11624
11625     // C89 is stricter than C99 for aggregate initializers.
11626     // C89 6.5.7p3: All the expressions [...] in an initializer list
11627     // for an object that has aggregate or union type shall be
11628     // constant expressions.
11629     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11630                isa<InitListExpr>(Init)) {
11631       const Expr *Culprit;
11632       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11633         Diag(Culprit->getExprLoc(),
11634              diag::ext_aggregate_init_not_constant)
11635           << Culprit->getSourceRange();
11636       }
11637     }
11638
11639     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11640       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11641         if (VDecl->hasLocalStorage())
11642           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11643   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11644              VDecl->getLexicalDeclContext()->isRecord()) {
11645     // This is an in-class initialization for a static data member, e.g.,
11646     //
11647     // struct S {
11648     //   static const int value = 17;
11649     // };
11650
11651     // C++ [class.mem]p4:
11652     //   A member-declarator can contain a constant-initializer only
11653     //   if it declares a static member (9.4) of const integral or
11654     //   const enumeration type, see 9.4.2.
11655     //
11656     // C++11 [class.static.data]p3:
11657     //   If a non-volatile non-inline const static data member is of integral
11658     //   or enumeration type, its declaration in the class definition can
11659     //   specify a brace-or-equal-initializer in which every initializer-clause
11660     //   that is an assignment-expression is a constant expression. A static
11661     //   data member of literal type can be declared in the class definition
11662     //   with the constexpr specifier; if so, its declaration shall specify a
11663     //   brace-or-equal-initializer in which every initializer-clause that is
11664     //   an assignment-expression is a constant expression.
11665
11666     // Do nothing on dependent types.
11667     if (DclT->isDependentType()) {
11668
11669     // Allow any 'static constexpr' members, whether or not they are of literal
11670     // type. We separately check that every constexpr variable is of literal
11671     // type.
11672     } else if (VDecl->isConstexpr()) {
11673
11674     // Require constness.
11675     } else if (!DclT.isConstQualified()) {
11676       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11677         << Init->getSourceRange();
11678       VDecl->setInvalidDecl();
11679
11680     // We allow integer constant expressions in all cases.
11681     } else if (DclT->isIntegralOrEnumerationType()) {
11682       // Check whether the expression is a constant expression.
11683       SourceLocation Loc;
11684       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11685         // In C++11, a non-constexpr const static data member with an
11686         // in-class initializer cannot be volatile.
11687         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11688       else if (Init->isValueDependent())
11689         ; // Nothing to check.
11690       else if (Init->isIntegerConstantExpr(Context, &Loc))
11691         ; // Ok, it's an ICE!
11692       else if (Init->getType()->isScopedEnumeralType() &&
11693                Init->isCXX11ConstantExpr(Context))
11694         ; // Ok, it is a scoped-enum constant expression.
11695       else if (Init->isEvaluatable(Context)) {
11696         // If we can constant fold the initializer through heroics, accept it,
11697         // but report this as a use of an extension for -pedantic.
11698         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11699           << Init->getSourceRange();
11700       } else {
11701         // Otherwise, this is some crazy unknown case.  Report the issue at the
11702         // location provided by the isIntegerConstantExpr failed check.
11703         Diag(Loc, diag::err_in_class_initializer_non_constant)
11704           << Init->getSourceRange();
11705         VDecl->setInvalidDecl();
11706       }
11707
11708     // We allow foldable floating-point constants as an extension.
11709     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11710       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11711       // it anyway and provide a fixit to add the 'constexpr'.
11712       if (getLangOpts().CPlusPlus11) {
11713         Diag(VDecl->getLocation(),
11714              diag::ext_in_class_initializer_float_type_cxx11)
11715             << DclT << Init->getSourceRange();
11716         Diag(VDecl->getBeginLoc(),
11717              diag::note_in_class_initializer_float_type_cxx11)
11718             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11719       } else {
11720         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11721           << DclT << Init->getSourceRange();
11722
11723         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11724           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11725             << Init->getSourceRange();
11726           VDecl->setInvalidDecl();
11727         }
11728       }
11729
11730     // Suggest adding 'constexpr' in C++11 for literal types.
11731     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11732       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11733           << DclT << Init->getSourceRange()
11734           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11735       VDecl->setConstexpr(true);
11736
11737     } else {
11738       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11739         << DclT << Init->getSourceRange();
11740       VDecl->setInvalidDecl();
11741     }
11742   } else if (VDecl->isFileVarDecl()) {
11743     // In C, extern is typically used to avoid tentative definitions when
11744     // declaring variables in headers, but adding an intializer makes it a
11745     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11746     // In C++, extern is often used to give implictly static const variables
11747     // external linkage, so don't warn in that case. If selectany is present,
11748     // this might be header code intended for C and C++ inclusion, so apply the
11749     // C++ rules.
11750     if (VDecl->getStorageClass() == SC_Extern &&
11751         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11752          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11753         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11754         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11755       Diag(VDecl->getLocation(), diag::warn_extern_init);
11756
11757     // In Microsoft C++ mode, a const variable defined in namespace scope has
11758     // external linkage by default if the variable is declared with
11759     // __declspec(dllexport).
11760     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11761         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11762         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11763       VDecl->setStorageClass(SC_Extern);
11764
11765     // C99 6.7.8p4. All file scoped initializers need to be constant.
11766     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11767       CheckForConstantInitializer(Init, DclT);
11768   }
11769
11770   QualType InitType = Init->getType();
11771   if (!InitType.isNull() &&
11772       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11773        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11774     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11775
11776   // We will represent direct-initialization similarly to copy-initialization:
11777   //    int x(1);  -as-> int x = 1;
11778   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11779   //
11780   // Clients that want to distinguish between the two forms, can check for
11781   // direct initializer using VarDecl::getInitStyle().
11782   // A major benefit is that clients that don't particularly care about which
11783   // exactly form was it (like the CodeGen) can handle both cases without
11784   // special case code.
11785
11786   // C++ 8.5p11:
11787   // The form of initialization (using parentheses or '=') is generally
11788   // insignificant, but does matter when the entity being initialized has a
11789   // class type.
11790   if (CXXDirectInit) {
11791     assert(DirectInit && "Call-style initializer must be direct init.");
11792     VDecl->setInitStyle(VarDecl::CallInit);
11793   } else if (DirectInit) {
11794     // This must be list-initialization. No other way is direct-initialization.
11795     VDecl->setInitStyle(VarDecl::ListInit);
11796   }
11797
11798   CheckCompleteVariableDeclaration(VDecl);
11799 }
11800
11801 /// ActOnInitializerError - Given that there was an error parsing an
11802 /// initializer for the given declaration, try to return to some form
11803 /// of sanity.
11804 void Sema::ActOnInitializerError(Decl *D) {
11805   // Our main concern here is re-establishing invariants like "a
11806   // variable's type is either dependent or complete".
11807   if (!D || D->isInvalidDecl()) return;
11808
11809   VarDecl *VD = dyn_cast<VarDecl>(D);
11810   if (!VD) return;
11811
11812   // Bindings are not usable if we can't make sense of the initializer.
11813   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11814     for (auto *BD : DD->bindings())
11815       BD->setInvalidDecl();
11816
11817   // Auto types are meaningless if we can't make sense of the initializer.
11818   if (ParsingInitForAutoVars.count(D)) {
11819     D->setInvalidDecl();
11820     return;
11821   }
11822
11823   QualType Ty = VD->getType();
11824   if (Ty->isDependentType()) return;
11825
11826   // Require a complete type.
11827   if (RequireCompleteType(VD->getLocation(),
11828                           Context.getBaseElementType(Ty),
11829                           diag::err_typecheck_decl_incomplete_type)) {
11830     VD->setInvalidDecl();
11831     return;
11832   }
11833
11834   // Require a non-abstract type.
11835   if (RequireNonAbstractType(VD->getLocation(), Ty,
11836                              diag::err_abstract_type_in_decl,
11837                              AbstractVariableType)) {
11838     VD->setInvalidDecl();
11839     return;
11840   }
11841
11842   // Don't bother complaining about constructors or destructors,
11843   // though.
11844 }
11845
11846 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11847   // If there is no declaration, there was an error parsing it. Just ignore it.
11848   if (!RealDecl)
11849     return;
11850
11851   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11852     QualType Type = Var->getType();
11853
11854     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11855     if (isa<DecompositionDecl>(RealDecl)) {
11856       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11857       Var->setInvalidDecl();
11858       return;
11859     }
11860
11861     if (Type->isUndeducedType() &&
11862         DeduceVariableDeclarationType(Var, false, nullptr))
11863       return;
11864
11865     // C++11 [class.static.data]p3: A static data member can be declared with
11866     // the constexpr specifier; if so, its declaration shall specify
11867     // a brace-or-equal-initializer.
11868     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11869     // the definition of a variable [...] or the declaration of a static data
11870     // member.
11871     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11872         !Var->isThisDeclarationADemotedDefinition()) {
11873       if (Var->isStaticDataMember()) {
11874         // C++1z removes the relevant rule; the in-class declaration is always
11875         // a definition there.
11876         if (!getLangOpts().CPlusPlus17) {
11877           Diag(Var->getLocation(),
11878                diag::err_constexpr_static_mem_var_requires_init)
11879             << Var->getDeclName();
11880           Var->setInvalidDecl();
11881           return;
11882         }
11883       } else {
11884         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11885         Var->setInvalidDecl();
11886         return;
11887       }
11888     }
11889
11890     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11891     // be initialized.
11892     if (!Var->isInvalidDecl() &&
11893         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11894         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11895       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11896       Var->setInvalidDecl();
11897       return;
11898     }
11899
11900     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
11901     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
11902         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11903       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
11904                             NTCUC_DefaultInitializedObject, NTCUK_Init);
11905
11906
11907     switch (DefKind) {
11908     case VarDecl::Definition:
11909       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11910         break;
11911
11912       // We have an out-of-line definition of a static data member
11913       // that has an in-class initializer, so we type-check this like
11914       // a declaration.
11915       //
11916       LLVM_FALLTHROUGH;
11917
11918     case VarDecl::DeclarationOnly:
11919       // It's only a declaration.
11920
11921       // Block scope. C99 6.7p7: If an identifier for an object is
11922       // declared with no linkage (C99 6.2.2p6), the type for the
11923       // object shall be complete.
11924       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11925           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11926           RequireCompleteType(Var->getLocation(), Type,
11927                               diag::err_typecheck_decl_incomplete_type))
11928         Var->setInvalidDecl();
11929
11930       // Make sure that the type is not abstract.
11931       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11932           RequireNonAbstractType(Var->getLocation(), Type,
11933                                  diag::err_abstract_type_in_decl,
11934                                  AbstractVariableType))
11935         Var->setInvalidDecl();
11936       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11937           Var->getStorageClass() == SC_PrivateExtern) {
11938         Diag(Var->getLocation(), diag::warn_private_extern);
11939         Diag(Var->getLocation(), diag::note_private_extern);
11940       }
11941
11942       return;
11943
11944     case VarDecl::TentativeDefinition:
11945       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11946       // object that has file scope without an initializer, and without a
11947       // storage-class specifier or with the storage-class specifier "static",
11948       // constitutes a tentative definition. Note: A tentative definition with
11949       // external linkage is valid (C99 6.2.2p5).
11950       if (!Var->isInvalidDecl()) {
11951         if (const IncompleteArrayType *ArrayT
11952                                     = Context.getAsIncompleteArrayType(Type)) {
11953           if (RequireCompleteType(Var->getLocation(),
11954                                   ArrayT->getElementType(),
11955                                   diag::err_illegal_decl_array_incomplete_type))
11956             Var->setInvalidDecl();
11957         } else if (Var->getStorageClass() == SC_Static) {
11958           // C99 6.9.2p3: If the declaration of an identifier for an object is
11959           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11960           // declared type shall not be an incomplete type.
11961           // NOTE: code such as the following
11962           //     static struct s;
11963           //     struct s { int a; };
11964           // is accepted by gcc. Hence here we issue a warning instead of
11965           // an error and we do not invalidate the static declaration.
11966           // NOTE: to avoid multiple warnings, only check the first declaration.
11967           if (Var->isFirstDecl())
11968             RequireCompleteType(Var->getLocation(), Type,
11969                                 diag::ext_typecheck_decl_incomplete_type);
11970         }
11971       }
11972
11973       // Record the tentative definition; we're done.
11974       if (!Var->isInvalidDecl())
11975         TentativeDefinitions.push_back(Var);
11976       return;
11977     }
11978
11979     // Provide a specific diagnostic for uninitialized variable
11980     // definitions with incomplete array type.
11981     if (Type->isIncompleteArrayType()) {
11982       Diag(Var->getLocation(),
11983            diag::err_typecheck_incomplete_array_needs_initializer);
11984       Var->setInvalidDecl();
11985       return;
11986     }
11987
11988     // Provide a specific diagnostic for uninitialized variable
11989     // definitions with reference type.
11990     if (Type->isReferenceType()) {
11991       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11992         << Var->getDeclName()
11993         << SourceRange(Var->getLocation(), Var->getLocation());
11994       Var->setInvalidDecl();
11995       return;
11996     }
11997
11998     // Do not attempt to type-check the default initializer for a
11999     // variable with dependent type.
12000     if (Type->isDependentType())
12001       return;
12002
12003     if (Var->isInvalidDecl())
12004       return;
12005
12006     if (!Var->hasAttr<AliasAttr>()) {
12007       if (RequireCompleteType(Var->getLocation(),
12008                               Context.getBaseElementType(Type),
12009                               diag::err_typecheck_decl_incomplete_type)) {
12010         Var->setInvalidDecl();
12011         return;
12012       }
12013     } else {
12014       return;
12015     }
12016
12017     // The variable can not have an abstract class type.
12018     if (RequireNonAbstractType(Var->getLocation(), Type,
12019                                diag::err_abstract_type_in_decl,
12020                                AbstractVariableType)) {
12021       Var->setInvalidDecl();
12022       return;
12023     }
12024
12025     // Check for jumps past the implicit initializer.  C++0x
12026     // clarifies that this applies to a "variable with automatic
12027     // storage duration", not a "local variable".
12028     // C++11 [stmt.dcl]p3
12029     //   A program that jumps from a point where a variable with automatic
12030     //   storage duration is not in scope to a point where it is in scope is
12031     //   ill-formed unless the variable has scalar type, class type with a
12032     //   trivial default constructor and a trivial destructor, a cv-qualified
12033     //   version of one of these types, or an array of one of the preceding
12034     //   types and is declared without an initializer.
12035     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12036       if (const RecordType *Record
12037             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12038         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12039         // Mark the function (if we're in one) for further checking even if the
12040         // looser rules of C++11 do not require such checks, so that we can
12041         // diagnose incompatibilities with C++98.
12042         if (!CXXRecord->isPOD())
12043           setFunctionHasBranchProtectedScope();
12044       }
12045     }
12046     // In OpenCL, we can't initialize objects in the __local address space,
12047     // even implicitly, so don't synthesize an implicit initializer.
12048     if (getLangOpts().OpenCL &&
12049         Var->getType().getAddressSpace() == LangAS::opencl_local)
12050       return;
12051     // C++03 [dcl.init]p9:
12052     //   If no initializer is specified for an object, and the
12053     //   object is of (possibly cv-qualified) non-POD class type (or
12054     //   array thereof), the object shall be default-initialized; if
12055     //   the object is of const-qualified type, the underlying class
12056     //   type shall have a user-declared default
12057     //   constructor. Otherwise, if no initializer is specified for
12058     //   a non- static object, the object and its subobjects, if
12059     //   any, have an indeterminate initial value); if the object
12060     //   or any of its subobjects are of const-qualified type, the
12061     //   program is ill-formed.
12062     // C++0x [dcl.init]p11:
12063     //   If no initializer is specified for an object, the object is
12064     //   default-initialized; [...].
12065     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12066     InitializationKind Kind
12067       = InitializationKind::CreateDefault(Var->getLocation());
12068
12069     InitializationSequence InitSeq(*this, Entity, Kind, None);
12070     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12071     if (Init.isInvalid())
12072       Var->setInvalidDecl();
12073     else if (Init.get()) {
12074       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12075       // This is important for template substitution.
12076       Var->setInitStyle(VarDecl::CallInit);
12077     }
12078
12079     CheckCompleteVariableDeclaration(Var);
12080   }
12081 }
12082
12083 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12084   // If there is no declaration, there was an error parsing it. Ignore it.
12085   if (!D)
12086     return;
12087
12088   VarDecl *VD = dyn_cast<VarDecl>(D);
12089   if (!VD) {
12090     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12091     D->setInvalidDecl();
12092     return;
12093   }
12094
12095   VD->setCXXForRangeDecl(true);
12096
12097   // for-range-declaration cannot be given a storage class specifier.
12098   int Error = -1;
12099   switch (VD->getStorageClass()) {
12100   case SC_None:
12101     break;
12102   case SC_Extern:
12103     Error = 0;
12104     break;
12105   case SC_Static:
12106     Error = 1;
12107     break;
12108   case SC_PrivateExtern:
12109     Error = 2;
12110     break;
12111   case SC_Auto:
12112     Error = 3;
12113     break;
12114   case SC_Register:
12115     Error = 4;
12116     break;
12117   }
12118   if (Error != -1) {
12119     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12120       << VD->getDeclName() << Error;
12121     D->setInvalidDecl();
12122   }
12123 }
12124
12125 StmtResult
12126 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12127                                  IdentifierInfo *Ident,
12128                                  ParsedAttributes &Attrs,
12129                                  SourceLocation AttrEnd) {
12130   // C++1y [stmt.iter]p1:
12131   //   A range-based for statement of the form
12132   //      for ( for-range-identifier : for-range-initializer ) statement
12133   //   is equivalent to
12134   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12135   DeclSpec DS(Attrs.getPool().getFactory());
12136
12137   const char *PrevSpec;
12138   unsigned DiagID;
12139   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12140                      getPrintingPolicy());
12141
12142   Declarator D(DS, DeclaratorContext::ForContext);
12143   D.SetIdentifier(Ident, IdentLoc);
12144   D.takeAttributes(Attrs, AttrEnd);
12145
12146   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12147                 IdentLoc);
12148   Decl *Var = ActOnDeclarator(S, D);
12149   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12150   FinalizeDeclaration(Var);
12151   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12152                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12153 }
12154
12155 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12156   if (var->isInvalidDecl()) return;
12157
12158   if (getLangOpts().OpenCL) {
12159     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12160     // initialiser
12161     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12162         !var->hasInit()) {
12163       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12164           << 1 /*Init*/;
12165       var->setInvalidDecl();
12166       return;
12167     }
12168   }
12169
12170   // In Objective-C, don't allow jumps past the implicit initialization of a
12171   // local retaining variable.
12172   if (getLangOpts().ObjC &&
12173       var->hasLocalStorage()) {
12174     switch (var->getType().getObjCLifetime()) {
12175     case Qualifiers::OCL_None:
12176     case Qualifiers::OCL_ExplicitNone:
12177     case Qualifiers::OCL_Autoreleasing:
12178       break;
12179
12180     case Qualifiers::OCL_Weak:
12181     case Qualifiers::OCL_Strong:
12182       setFunctionHasBranchProtectedScope();
12183       break;
12184     }
12185   }
12186
12187   if (var->hasLocalStorage() &&
12188       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12189     setFunctionHasBranchProtectedScope();
12190
12191   // Warn about externally-visible variables being defined without a
12192   // prior declaration.  We only want to do this for global
12193   // declarations, but we also specifically need to avoid doing it for
12194   // class members because the linkage of an anonymous class can
12195   // change if it's later given a typedef name.
12196   if (var->isThisDeclarationADefinition() &&
12197       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12198       var->isExternallyVisible() && var->hasLinkage() &&
12199       !var->isInline() && !var->getDescribedVarTemplate() &&
12200       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12201       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12202                                   var->getLocation())) {
12203     // Find a previous declaration that's not a definition.
12204     VarDecl *prev = var->getPreviousDecl();
12205     while (prev && prev->isThisDeclarationADefinition())
12206       prev = prev->getPreviousDecl();
12207
12208     if (!prev) {
12209       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12210       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12211           << /* variable */ 0;
12212     }
12213   }
12214
12215   // Cache the result of checking for constant initialization.
12216   Optional<bool> CacheHasConstInit;
12217   const Expr *CacheCulprit = nullptr;
12218   auto checkConstInit = [&]() mutable {
12219     if (!CacheHasConstInit)
12220       CacheHasConstInit = var->getInit()->isConstantInitializer(
12221             Context, var->getType()->isReferenceType(), &CacheCulprit);
12222     return *CacheHasConstInit;
12223   };
12224
12225   if (var->getTLSKind() == VarDecl::TLS_Static) {
12226     if (var->getType().isDestructedType()) {
12227       // GNU C++98 edits for __thread, [basic.start.term]p3:
12228       //   The type of an object with thread storage duration shall not
12229       //   have a non-trivial destructor.
12230       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12231       if (getLangOpts().CPlusPlus11)
12232         Diag(var->getLocation(), diag::note_use_thread_local);
12233     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12234       if (!checkConstInit()) {
12235         // GNU C++98 edits for __thread, [basic.start.init]p4:
12236         //   An object of thread storage duration shall not require dynamic
12237         //   initialization.
12238         // FIXME: Need strict checking here.
12239         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12240           << CacheCulprit->getSourceRange();
12241         if (getLangOpts().CPlusPlus11)
12242           Diag(var->getLocation(), diag::note_use_thread_local);
12243       }
12244     }
12245   }
12246
12247   // Apply section attributes and pragmas to global variables.
12248   bool GlobalStorage = var->hasGlobalStorage();
12249   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12250       !inTemplateInstantiation()) {
12251     PragmaStack<StringLiteral *> *Stack = nullptr;
12252     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12253     if (var->getType().isConstQualified())
12254       Stack = &ConstSegStack;
12255     else if (!var->getInit()) {
12256       Stack = &BSSSegStack;
12257       SectionFlags |= ASTContext::PSF_Write;
12258     } else {
12259       Stack = &DataSegStack;
12260       SectionFlags |= ASTContext::PSF_Write;
12261     }
12262     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
12263       var->addAttr(SectionAttr::CreateImplicit(
12264           Context, SectionAttr::Declspec_allocate,
12265           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
12266     }
12267     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12268       if (UnifySection(SA->getName(), SectionFlags, var))
12269         var->dropAttr<SectionAttr>();
12270
12271     // Apply the init_seg attribute if this has an initializer.  If the
12272     // initializer turns out to not be dynamic, we'll end up ignoring this
12273     // attribute.
12274     if (CurInitSeg && var->getInit())
12275       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12276                                                CurInitSegLoc));
12277   }
12278
12279   // All the following checks are C++ only.
12280   if (!getLangOpts().CPlusPlus) {
12281       // If this variable must be emitted, add it as an initializer for the
12282       // current module.
12283      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12284        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12285      return;
12286   }
12287
12288   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12289     CheckCompleteDecompositionDeclaration(DD);
12290
12291   QualType type = var->getType();
12292   if (type->isDependentType()) return;
12293
12294   if (var->hasAttr<BlocksAttr>())
12295     getCurFunction()->addByrefBlockVar(var);
12296
12297   Expr *Init = var->getInit();
12298   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12299   QualType baseType = Context.getBaseElementType(type);
12300
12301   if (Init && !Init->isValueDependent()) {
12302     if (var->isConstexpr()) {
12303       SmallVector<PartialDiagnosticAt, 8> Notes;
12304       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12305         SourceLocation DiagLoc = var->getLocation();
12306         // If the note doesn't add any useful information other than a source
12307         // location, fold it into the primary diagnostic.
12308         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12309               diag::note_invalid_subexpr_in_const_expr) {
12310           DiagLoc = Notes[0].first;
12311           Notes.clear();
12312         }
12313         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12314           << var << Init->getSourceRange();
12315         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12316           Diag(Notes[I].first, Notes[I].second);
12317       }
12318     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12319       // Check whether the initializer of a const variable of integral or
12320       // enumeration type is an ICE now, since we can't tell whether it was
12321       // initialized by a constant expression if we check later.
12322       var->checkInitIsICE();
12323     }
12324
12325     // Don't emit further diagnostics about constexpr globals since they
12326     // were just diagnosed.
12327     if (!var->isConstexpr() && GlobalStorage &&
12328             var->hasAttr<RequireConstantInitAttr>()) {
12329       // FIXME: Need strict checking in C++03 here.
12330       bool DiagErr = getLangOpts().CPlusPlus11
12331           ? !var->checkInitIsICE() : !checkConstInit();
12332       if (DiagErr) {
12333         auto attr = var->getAttr<RequireConstantInitAttr>();
12334         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12335           << Init->getSourceRange();
12336         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12337           << attr->getRange();
12338         if (getLangOpts().CPlusPlus11) {
12339           APValue Value;
12340           SmallVector<PartialDiagnosticAt, 8> Notes;
12341           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12342           for (auto &it : Notes)
12343             Diag(it.first, it.second);
12344         } else {
12345           Diag(CacheCulprit->getExprLoc(),
12346                diag::note_invalid_subexpr_in_const_expr)
12347               << CacheCulprit->getSourceRange();
12348         }
12349       }
12350     }
12351     else if (!var->isConstexpr() && IsGlobal &&
12352              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12353                                     var->getLocation())) {
12354       // Warn about globals which don't have a constant initializer.  Don't
12355       // warn about globals with a non-trivial destructor because we already
12356       // warned about them.
12357       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12358       if (!(RD && !RD->hasTrivialDestructor())) {
12359         if (!checkConstInit())
12360           Diag(var->getLocation(), diag::warn_global_constructor)
12361             << Init->getSourceRange();
12362       }
12363     }
12364   }
12365
12366   // Require the destructor.
12367   if (const RecordType *recordType = baseType->getAs<RecordType>())
12368     FinalizeVarWithDestructor(var, recordType);
12369
12370   // If this variable must be emitted, add it as an initializer for the current
12371   // module.
12372   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12373     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12374 }
12375
12376 /// Determines if a variable's alignment is dependent.
12377 static bool hasDependentAlignment(VarDecl *VD) {
12378   if (VD->getType()->isDependentType())
12379     return true;
12380   for (auto *I : VD->specific_attrs<AlignedAttr>())
12381     if (I->isAlignmentDependent())
12382       return true;
12383   return false;
12384 }
12385
12386 /// Check if VD needs to be dllexport/dllimport due to being in a
12387 /// dllexport/import function.
12388 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12389   assert(VD->isStaticLocal());
12390
12391   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12392
12393   // Find outermost function when VD is in lambda function.
12394   while (FD && !getDLLAttr(FD) &&
12395          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12396          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12397     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12398   }
12399
12400   if (!FD)
12401     return;
12402
12403   // Static locals inherit dll attributes from their function.
12404   if (Attr *A = getDLLAttr(FD)) {
12405     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12406     NewAttr->setInherited(true);
12407     VD->addAttr(NewAttr);
12408   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12409     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12410                                                           getASTContext(),
12411                                                           A->getSpellingListIndex());
12412     NewAttr->setInherited(true);
12413     VD->addAttr(NewAttr);
12414
12415     // Export this function to enforce exporting this static variable even
12416     // if it is not used in this compilation unit.
12417     if (!FD->hasAttr<DLLExportAttr>())
12418       FD->addAttr(NewAttr);
12419
12420   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12421     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12422                                                           getASTContext(),
12423                                                           A->getSpellingListIndex());
12424     NewAttr->setInherited(true);
12425     VD->addAttr(NewAttr);
12426   }
12427 }
12428
12429 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12430 /// any semantic actions necessary after any initializer has been attached.
12431 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12432   // Note that we are no longer parsing the initializer for this declaration.
12433   ParsingInitForAutoVars.erase(ThisDecl);
12434
12435   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12436   if (!VD)
12437     return;
12438
12439   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12440   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12441       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12442     if (PragmaClangBSSSection.Valid)
12443       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12444                                                             PragmaClangBSSSection.SectionName,
12445                                                             PragmaClangBSSSection.PragmaLocation));
12446     if (PragmaClangDataSection.Valid)
12447       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12448                                                              PragmaClangDataSection.SectionName,
12449                                                              PragmaClangDataSection.PragmaLocation));
12450     if (PragmaClangRodataSection.Valid)
12451       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12452                                                                PragmaClangRodataSection.SectionName,
12453                                                                PragmaClangRodataSection.PragmaLocation));
12454   }
12455
12456   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12457     for (auto *BD : DD->bindings()) {
12458       FinalizeDeclaration(BD);
12459     }
12460   }
12461
12462   checkAttributesAfterMerging(*this, *VD);
12463
12464   // Perform TLS alignment check here after attributes attached to the variable
12465   // which may affect the alignment have been processed. Only perform the check
12466   // if the target has a maximum TLS alignment (zero means no constraints).
12467   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12468     // Protect the check so that it's not performed on dependent types and
12469     // dependent alignments (we can't determine the alignment in that case).
12470     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12471         !VD->isInvalidDecl()) {
12472       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12473       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12474         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12475           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12476           << (unsigned)MaxAlignChars.getQuantity();
12477       }
12478     }
12479   }
12480
12481   if (VD->isStaticLocal()) {
12482     CheckStaticLocalForDllExport(VD);
12483
12484     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12485       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12486       // function, only __shared__ variables or variables without any device
12487       // memory qualifiers may be declared with static storage class.
12488       // Note: It is unclear how a function-scope non-const static variable
12489       // without device memory qualifier is implemented, therefore only static
12490       // const variable without device memory qualifier is allowed.
12491       [&]() {
12492         if (!getLangOpts().CUDA)
12493           return;
12494         if (VD->hasAttr<CUDASharedAttr>())
12495           return;
12496         if (VD->getType().isConstQualified() &&
12497             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12498           return;
12499         if (CUDADiagIfDeviceCode(VD->getLocation(),
12500                                  diag::err_device_static_local_var)
12501             << CurrentCUDATarget())
12502           VD->setInvalidDecl();
12503       }();
12504     }
12505   }
12506
12507   // Perform check for initializers of device-side global variables.
12508   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12509   // 7.5). We must also apply the same checks to all __shared__
12510   // variables whether they are local or not. CUDA also allows
12511   // constant initializers for __constant__ and __device__ variables.
12512   if (getLangOpts().CUDA)
12513     checkAllowedCUDAInitializer(VD);
12514
12515   // Grab the dllimport or dllexport attribute off of the VarDecl.
12516   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12517
12518   // Imported static data members cannot be defined out-of-line.
12519   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12520     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12521         VD->isThisDeclarationADefinition()) {
12522       // We allow definitions of dllimport class template static data members
12523       // with a warning.
12524       CXXRecordDecl *Context =
12525         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12526       bool IsClassTemplateMember =
12527           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12528           Context->getDescribedClassTemplate();
12529
12530       Diag(VD->getLocation(),
12531            IsClassTemplateMember
12532                ? diag::warn_attribute_dllimport_static_field_definition
12533                : diag::err_attribute_dllimport_static_field_definition);
12534       Diag(IA->getLocation(), diag::note_attribute);
12535       if (!IsClassTemplateMember)
12536         VD->setInvalidDecl();
12537     }
12538   }
12539
12540   // dllimport/dllexport variables cannot be thread local, their TLS index
12541   // isn't exported with the variable.
12542   if (DLLAttr && VD->getTLSKind()) {
12543     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12544     if (F && getDLLAttr(F)) {
12545       assert(VD->isStaticLocal());
12546       // But if this is a static local in a dlimport/dllexport function, the
12547       // function will never be inlined, which means the var would never be
12548       // imported, so having it marked import/export is safe.
12549     } else {
12550       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12551                                                                     << DLLAttr;
12552       VD->setInvalidDecl();
12553     }
12554   }
12555
12556   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12557     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12558       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12559       VD->dropAttr<UsedAttr>();
12560     }
12561   }
12562
12563   const DeclContext *DC = VD->getDeclContext();
12564   // If there's a #pragma GCC visibility in scope, and this isn't a class
12565   // member, set the visibility of this variable.
12566   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12567     AddPushedVisibilityAttribute(VD);
12568
12569   // FIXME: Warn on unused var template partial specializations.
12570   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12571     MarkUnusedFileScopedDecl(VD);
12572
12573   // Now we have parsed the initializer and can update the table of magic
12574   // tag values.
12575   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12576       !VD->getType()->isIntegralOrEnumerationType())
12577     return;
12578
12579   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12580     const Expr *MagicValueExpr = VD->getInit();
12581     if (!MagicValueExpr) {
12582       continue;
12583     }
12584     llvm::APSInt MagicValueInt;
12585     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12586       Diag(I->getRange().getBegin(),
12587            diag::err_type_tag_for_datatype_not_ice)
12588         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12589       continue;
12590     }
12591     if (MagicValueInt.getActiveBits() > 64) {
12592       Diag(I->getRange().getBegin(),
12593            diag::err_type_tag_for_datatype_too_large)
12594         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12595       continue;
12596     }
12597     uint64_t MagicValue = MagicValueInt.getZExtValue();
12598     RegisterTypeTagForDatatype(I->getArgumentKind(),
12599                                MagicValue,
12600                                I->getMatchingCType(),
12601                                I->getLayoutCompatible(),
12602                                I->getMustBeNull());
12603   }
12604 }
12605
12606 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12607   auto *VD = dyn_cast<VarDecl>(DD);
12608   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12609 }
12610
12611 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12612                                                    ArrayRef<Decl *> Group) {
12613   SmallVector<Decl*, 8> Decls;
12614
12615   if (DS.isTypeSpecOwned())
12616     Decls.push_back(DS.getRepAsDecl());
12617
12618   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12619   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12620   bool DiagnosedMultipleDecomps = false;
12621   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12622   bool DiagnosedNonDeducedAuto = false;
12623
12624   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12625     if (Decl *D = Group[i]) {
12626       // For declarators, there are some additional syntactic-ish checks we need
12627       // to perform.
12628       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12629         if (!FirstDeclaratorInGroup)
12630           FirstDeclaratorInGroup = DD;
12631         if (!FirstDecompDeclaratorInGroup)
12632           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12633         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12634             !hasDeducedAuto(DD))
12635           FirstNonDeducedAutoInGroup = DD;
12636
12637         if (FirstDeclaratorInGroup != DD) {
12638           // A decomposition declaration cannot be combined with any other
12639           // declaration in the same group.
12640           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12641             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12642                  diag::err_decomp_decl_not_alone)
12643                 << FirstDeclaratorInGroup->getSourceRange()
12644                 << DD->getSourceRange();
12645             DiagnosedMultipleDecomps = true;
12646           }
12647
12648           // A declarator that uses 'auto' in any way other than to declare a
12649           // variable with a deduced type cannot be combined with any other
12650           // declarator in the same group.
12651           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12652             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12653                  diag::err_auto_non_deduced_not_alone)
12654                 << FirstNonDeducedAutoInGroup->getType()
12655                        ->hasAutoForTrailingReturnType()
12656                 << FirstDeclaratorInGroup->getSourceRange()
12657                 << DD->getSourceRange();
12658             DiagnosedNonDeducedAuto = true;
12659           }
12660         }
12661       }
12662
12663       Decls.push_back(D);
12664     }
12665   }
12666
12667   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12668     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12669       handleTagNumbering(Tag, S);
12670       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12671           getLangOpts().CPlusPlus)
12672         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12673     }
12674   }
12675
12676   return BuildDeclaratorGroup(Decls);
12677 }
12678
12679 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12680 /// group, performing any necessary semantic checking.
12681 Sema::DeclGroupPtrTy
12682 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12683   // C++14 [dcl.spec.auto]p7: (DR1347)
12684   //   If the type that replaces the placeholder type is not the same in each
12685   //   deduction, the program is ill-formed.
12686   if (Group.size() > 1) {
12687     QualType Deduced;
12688     VarDecl *DeducedDecl = nullptr;
12689     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12690       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12691       if (!D || D->isInvalidDecl())
12692         break;
12693       DeducedType *DT = D->getType()->getContainedDeducedType();
12694       if (!DT || DT->getDeducedType().isNull())
12695         continue;
12696       if (Deduced.isNull()) {
12697         Deduced = DT->getDeducedType();
12698         DeducedDecl = D;
12699       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12700         auto *AT = dyn_cast<AutoType>(DT);
12701         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12702              diag::err_auto_different_deductions)
12703           << (AT ? (unsigned)AT->getKeyword() : 3)
12704           << Deduced << DeducedDecl->getDeclName()
12705           << DT->getDeducedType() << D->getDeclName()
12706           << DeducedDecl->getInit()->getSourceRange()
12707           << D->getInit()->getSourceRange();
12708         D->setInvalidDecl();
12709         break;
12710       }
12711     }
12712   }
12713
12714   ActOnDocumentableDecls(Group);
12715
12716   return DeclGroupPtrTy::make(
12717       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12718 }
12719
12720 void Sema::ActOnDocumentableDecl(Decl *D) {
12721   ActOnDocumentableDecls(D);
12722 }
12723
12724 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12725   // Don't parse the comment if Doxygen diagnostics are ignored.
12726   if (Group.empty() || !Group[0])
12727     return;
12728
12729   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12730                       Group[0]->getLocation()) &&
12731       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12732                       Group[0]->getLocation()))
12733     return;
12734
12735   if (Group.size() >= 2) {
12736     // This is a decl group.  Normally it will contain only declarations
12737     // produced from declarator list.  But in case we have any definitions or
12738     // additional declaration references:
12739     //   'typedef struct S {} S;'
12740     //   'typedef struct S *S;'
12741     //   'struct S *pS;'
12742     // FinalizeDeclaratorGroup adds these as separate declarations.
12743     Decl *MaybeTagDecl = Group[0];
12744     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12745       Group = Group.slice(1);
12746     }
12747   }
12748
12749   // See if there are any new comments that are not attached to a decl.
12750   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12751   if (!Comments.empty() &&
12752       !Comments.back()->isAttached()) {
12753     // There is at least one comment that not attached to a decl.
12754     // Maybe it should be attached to one of these decls?
12755     //
12756     // Note that this way we pick up not only comments that precede the
12757     // declaration, but also comments that *follow* the declaration -- thanks to
12758     // the lookahead in the lexer: we've consumed the semicolon and looked
12759     // ahead through comments.
12760     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12761       Context.getCommentForDecl(Group[i], &PP);
12762   }
12763 }
12764
12765 /// Common checks for a parameter-declaration that should apply to both function
12766 /// parameters and non-type template parameters.
12767 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12768   // Check that there are no default arguments inside the type of this
12769   // parameter.
12770   if (getLangOpts().CPlusPlus)
12771     CheckExtraCXXDefaultArguments(D);
12772
12773   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12774   if (D.getCXXScopeSpec().isSet()) {
12775     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12776       << D.getCXXScopeSpec().getRange();
12777   }
12778
12779   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12780   // simple identifier except [...irrelevant cases...].
12781   switch (D.getName().getKind()) {
12782   case UnqualifiedIdKind::IK_Identifier:
12783     break;
12784
12785   case UnqualifiedIdKind::IK_OperatorFunctionId:
12786   case UnqualifiedIdKind::IK_ConversionFunctionId:
12787   case UnqualifiedIdKind::IK_LiteralOperatorId:
12788   case UnqualifiedIdKind::IK_ConstructorName:
12789   case UnqualifiedIdKind::IK_DestructorName:
12790   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12791   case UnqualifiedIdKind::IK_DeductionGuideName:
12792     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12793       << GetNameForDeclarator(D).getName();
12794     break;
12795
12796   case UnqualifiedIdKind::IK_TemplateId:
12797   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12798     // GetNameForDeclarator would not produce a useful name in this case.
12799     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12800     break;
12801   }
12802 }
12803
12804 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12805 /// to introduce parameters into function prototype scope.
12806 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12807   const DeclSpec &DS = D.getDeclSpec();
12808
12809   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12810
12811   // C++03 [dcl.stc]p2 also permits 'auto'.
12812   StorageClass SC = SC_None;
12813   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12814     SC = SC_Register;
12815     // In C++11, the 'register' storage class specifier is deprecated.
12816     // In C++17, it is not allowed, but we tolerate it as an extension.
12817     if (getLangOpts().CPlusPlus11) {
12818       Diag(DS.getStorageClassSpecLoc(),
12819            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12820                                      : diag::warn_deprecated_register)
12821         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12822     }
12823   } else if (getLangOpts().CPlusPlus &&
12824              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12825     SC = SC_Auto;
12826   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12827     Diag(DS.getStorageClassSpecLoc(),
12828          diag::err_invalid_storage_class_in_func_decl);
12829     D.getMutableDeclSpec().ClearStorageClassSpecs();
12830   }
12831
12832   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12833     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12834       << DeclSpec::getSpecifierName(TSCS);
12835   if (DS.isInlineSpecified())
12836     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12837         << getLangOpts().CPlusPlus17;
12838   if (DS.hasConstexprSpecifier())
12839     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12840         << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
12841
12842   DiagnoseFunctionSpecifiers(DS);
12843
12844   CheckFunctionOrTemplateParamDeclarator(S, D);
12845
12846   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12847   QualType parmDeclType = TInfo->getType();
12848
12849   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12850   IdentifierInfo *II = D.getIdentifier();
12851   if (II) {
12852     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12853                    ForVisibleRedeclaration);
12854     LookupName(R, S);
12855     if (R.isSingleResult()) {
12856       NamedDecl *PrevDecl = R.getFoundDecl();
12857       if (PrevDecl->isTemplateParameter()) {
12858         // Maybe we will complain about the shadowed template parameter.
12859         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12860         // Just pretend that we didn't see the previous declaration.
12861         PrevDecl = nullptr;
12862       } else if (S->isDeclScope(PrevDecl)) {
12863         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12864         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12865
12866         // Recover by removing the name
12867         II = nullptr;
12868         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12869         D.setInvalidType(true);
12870       }
12871     }
12872   }
12873
12874   // Temporarily put parameter variables in the translation unit, not
12875   // the enclosing context.  This prevents them from accidentally
12876   // looking like class members in C++.
12877   ParmVarDecl *New =
12878       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12879                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12880
12881   if (D.isInvalidType())
12882     New->setInvalidDecl();
12883
12884   assert(S->isFunctionPrototypeScope());
12885   assert(S->getFunctionPrototypeDepth() >= 1);
12886   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12887                     S->getNextFunctionPrototypeIndex());
12888
12889   // Add the parameter declaration into this scope.
12890   S->AddDecl(New);
12891   if (II)
12892     IdResolver.AddDecl(New);
12893
12894   ProcessDeclAttributes(S, New, D);
12895
12896   if (D.getDeclSpec().isModulePrivateSpecified())
12897     Diag(New->getLocation(), diag::err_module_private_local)
12898       << 1 << New->getDeclName()
12899       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12900       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12901
12902   if (New->hasAttr<BlocksAttr>()) {
12903     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12904   }
12905   return New;
12906 }
12907
12908 /// Synthesizes a variable for a parameter arising from a
12909 /// typedef.
12910 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12911                                               SourceLocation Loc,
12912                                               QualType T) {
12913   /* FIXME: setting StartLoc == Loc.
12914      Would it be worth to modify callers so as to provide proper source
12915      location for the unnamed parameters, embedding the parameter's type? */
12916   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12917                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12918                                            SC_None, nullptr);
12919   Param->setImplicit();
12920   return Param;
12921 }
12922
12923 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12924   // Don't diagnose unused-parameter errors in template instantiations; we
12925   // will already have done so in the template itself.
12926   if (inTemplateInstantiation())
12927     return;
12928
12929   for (const ParmVarDecl *Parameter : Parameters) {
12930     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12931         !Parameter->hasAttr<UnusedAttr>()) {
12932       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12933         << Parameter->getDeclName();
12934     }
12935   }
12936 }
12937
12938 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12939     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12940   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12941     return;
12942
12943   // Warn if the return value is pass-by-value and larger than the specified
12944   // threshold.
12945   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12946     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12947     if (Size > LangOpts.NumLargeByValueCopy)
12948       Diag(D->getLocation(), diag::warn_return_value_size)
12949           << D->getDeclName() << Size;
12950   }
12951
12952   // Warn if any parameter is pass-by-value and larger than the specified
12953   // threshold.
12954   for (const ParmVarDecl *Parameter : Parameters) {
12955     QualType T = Parameter->getType();
12956     if (T->isDependentType() || !T.isPODType(Context))
12957       continue;
12958     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12959     if (Size > LangOpts.NumLargeByValueCopy)
12960       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12961           << Parameter->getDeclName() << Size;
12962   }
12963 }
12964
12965 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12966                                   SourceLocation NameLoc, IdentifierInfo *Name,
12967                                   QualType T, TypeSourceInfo *TSInfo,
12968                                   StorageClass SC) {
12969   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12970   if (getLangOpts().ObjCAutoRefCount &&
12971       T.getObjCLifetime() == Qualifiers::OCL_None &&
12972       T->isObjCLifetimeType()) {
12973
12974     Qualifiers::ObjCLifetime lifetime;
12975
12976     // Special cases for arrays:
12977     //   - if it's const, use __unsafe_unretained
12978     //   - otherwise, it's an error
12979     if (T->isArrayType()) {
12980       if (!T.isConstQualified()) {
12981         if (DelayedDiagnostics.shouldDelayDiagnostics())
12982           DelayedDiagnostics.add(
12983               sema::DelayedDiagnostic::makeForbiddenType(
12984               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12985         else
12986           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12987               << TSInfo->getTypeLoc().getSourceRange();
12988       }
12989       lifetime = Qualifiers::OCL_ExplicitNone;
12990     } else {
12991       lifetime = T->getObjCARCImplicitLifetime();
12992     }
12993     T = Context.getLifetimeQualifiedType(T, lifetime);
12994   }
12995
12996   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12997                                          Context.getAdjustedParameterType(T),
12998                                          TSInfo, SC, nullptr);
12999
13000   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13001       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13002     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13003                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13004
13005   // Parameters can not be abstract class types.
13006   // For record types, this is done by the AbstractClassUsageDiagnoser once
13007   // the class has been completely parsed.
13008   if (!CurContext->isRecord() &&
13009       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13010                              AbstractParamType))
13011     New->setInvalidDecl();
13012
13013   // Parameter declarators cannot be interface types. All ObjC objects are
13014   // passed by reference.
13015   if (T->isObjCObjectType()) {
13016     SourceLocation TypeEndLoc =
13017         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13018     Diag(NameLoc,
13019          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13020       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13021     T = Context.getObjCObjectPointerType(T);
13022     New->setType(T);
13023   }
13024
13025   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13026   // duration shall not be qualified by an address-space qualifier."
13027   // Since all parameters have automatic store duration, they can not have
13028   // an address space.
13029   if (T.getAddressSpace() != LangAS::Default &&
13030       // OpenCL allows function arguments declared to be an array of a type
13031       // to be qualified with an address space.
13032       !(getLangOpts().OpenCL &&
13033         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13034     Diag(NameLoc, diag::err_arg_with_address_space);
13035     New->setInvalidDecl();
13036   }
13037
13038   return New;
13039 }
13040
13041 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13042                                            SourceLocation LocAfterDecls) {
13043   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13044
13045   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13046   // for a K&R function.
13047   if (!FTI.hasPrototype) {
13048     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13049       --i;
13050       if (FTI.Params[i].Param == nullptr) {
13051         SmallString<256> Code;
13052         llvm::raw_svector_ostream(Code)
13053             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13054         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13055             << FTI.Params[i].Ident
13056             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13057
13058         // Implicitly declare the argument as type 'int' for lack of a better
13059         // type.
13060         AttributeFactory attrs;
13061         DeclSpec DS(attrs);
13062         const char* PrevSpec; // unused
13063         unsigned DiagID; // unused
13064         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13065                            DiagID, Context.getPrintingPolicy());
13066         // Use the identifier location for the type source range.
13067         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13068         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13069         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13070         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13071         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13072       }
13073     }
13074   }
13075 }
13076
13077 Decl *
13078 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13079                               MultiTemplateParamsArg TemplateParameterLists,
13080                               SkipBodyInfo *SkipBody) {
13081   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13082   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13083   Scope *ParentScope = FnBodyScope->getParent();
13084
13085   D.setFunctionDefinitionKind(FDK_Definition);
13086   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13087   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13088 }
13089
13090 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13091   Consumer.HandleInlineFunctionDefinition(D);
13092 }
13093
13094 static bool
13095 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13096                                 const FunctionDecl *&PossiblePrototype) {
13097   // Don't warn about invalid declarations.
13098   if (FD->isInvalidDecl())
13099     return false;
13100
13101   // Or declarations that aren't global.
13102   if (!FD->isGlobal())
13103     return false;
13104
13105   // Don't warn about C++ member functions.
13106   if (isa<CXXMethodDecl>(FD))
13107     return false;
13108
13109   // Don't warn about 'main'.
13110   if (FD->isMain())
13111     return false;
13112
13113   // Don't warn about inline functions.
13114   if (FD->isInlined())
13115     return false;
13116
13117   // Don't warn about function templates.
13118   if (FD->getDescribedFunctionTemplate())
13119     return false;
13120
13121   // Don't warn about function template specializations.
13122   if (FD->isFunctionTemplateSpecialization())
13123     return false;
13124
13125   // Don't warn for OpenCL kernels.
13126   if (FD->hasAttr<OpenCLKernelAttr>())
13127     return false;
13128
13129   // Don't warn on explicitly deleted functions.
13130   if (FD->isDeleted())
13131     return false;
13132
13133   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13134        Prev; Prev = Prev->getPreviousDecl()) {
13135     // Ignore any declarations that occur in function or method
13136     // scope, because they aren't visible from the header.
13137     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13138       continue;
13139
13140     PossiblePrototype = Prev;
13141     return Prev->getType()->isFunctionNoProtoType();
13142   }
13143
13144   return true;
13145 }
13146
13147 void
13148 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13149                                    const FunctionDecl *EffectiveDefinition,
13150                                    SkipBodyInfo *SkipBody) {
13151   const FunctionDecl *Definition = EffectiveDefinition;
13152   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13153     // If this is a friend function defined in a class template, it does not
13154     // have a body until it is used, nevertheless it is a definition, see
13155     // [temp.inst]p2:
13156     //
13157     // ... for the purpose of determining whether an instantiated redeclaration
13158     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13159     // corresponds to a definition in the template is considered to be a
13160     // definition.
13161     //
13162     // The following code must produce redefinition error:
13163     //
13164     //     template<typename T> struct C20 { friend void func_20() {} };
13165     //     C20<int> c20i;
13166     //     void func_20() {}
13167     //
13168     for (auto I : FD->redecls()) {
13169       if (I != FD && !I->isInvalidDecl() &&
13170           I->getFriendObjectKind() != Decl::FOK_None) {
13171         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13172           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13173             // A merged copy of the same function, instantiated as a member of
13174             // the same class, is OK.
13175             if (declaresSameEntity(OrigFD, Original) &&
13176                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13177                                    cast<Decl>(FD->getLexicalDeclContext())))
13178               continue;
13179           }
13180
13181           if (Original->isThisDeclarationADefinition()) {
13182             Definition = I;
13183             break;
13184           }
13185         }
13186       }
13187     }
13188   }
13189
13190   if (!Definition)
13191     // Similar to friend functions a friend function template may be a
13192     // definition and do not have a body if it is instantiated in a class
13193     // template.
13194     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13195       for (auto I : FTD->redecls()) {
13196         auto D = cast<FunctionTemplateDecl>(I);
13197         if (D != FTD) {
13198           assert(!D->isThisDeclarationADefinition() &&
13199                  "More than one definition in redeclaration chain");
13200           if (D->getFriendObjectKind() != Decl::FOK_None)
13201             if (FunctionTemplateDecl *FT =
13202                                        D->getInstantiatedFromMemberTemplate()) {
13203               if (FT->isThisDeclarationADefinition()) {
13204                 Definition = D->getTemplatedDecl();
13205                 break;
13206               }
13207             }
13208         }
13209       }
13210     }
13211
13212   if (!Definition)
13213     return;
13214
13215   if (canRedefineFunction(Definition, getLangOpts()))
13216     return;
13217
13218   // Don't emit an error when this is redefinition of a typo-corrected
13219   // definition.
13220   if (TypoCorrectedFunctionDefinitions.count(Definition))
13221     return;
13222
13223   // If we don't have a visible definition of the function, and it's inline or
13224   // a template, skip the new definition.
13225   if (SkipBody && !hasVisibleDefinition(Definition) &&
13226       (Definition->getFormalLinkage() == InternalLinkage ||
13227        Definition->isInlined() ||
13228        Definition->getDescribedFunctionTemplate() ||
13229        Definition->getNumTemplateParameterLists())) {
13230     SkipBody->ShouldSkip = true;
13231     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13232     if (auto *TD = Definition->getDescribedFunctionTemplate())
13233       makeMergedDefinitionVisible(TD);
13234     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13235     return;
13236   }
13237
13238   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13239       Definition->getStorageClass() == SC_Extern)
13240     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13241         << FD->getDeclName() << getLangOpts().CPlusPlus;
13242   else
13243     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13244
13245   Diag(Definition->getLocation(), diag::note_previous_definition);
13246   FD->setInvalidDecl();
13247 }
13248
13249 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13250                                    Sema &S) {
13251   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13252
13253   LambdaScopeInfo *LSI = S.PushLambdaScope();
13254   LSI->CallOperator = CallOperator;
13255   LSI->Lambda = LambdaClass;
13256   LSI->ReturnType = CallOperator->getReturnType();
13257   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13258
13259   if (LCD == LCD_None)
13260     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13261   else if (LCD == LCD_ByCopy)
13262     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13263   else if (LCD == LCD_ByRef)
13264     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13265   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13266
13267   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13268   LSI->Mutable = !CallOperator->isConst();
13269
13270   // Add the captures to the LSI so they can be noted as already
13271   // captured within tryCaptureVar.
13272   auto I = LambdaClass->field_begin();
13273   for (const auto &C : LambdaClass->captures()) {
13274     if (C.capturesVariable()) {
13275       VarDecl *VD = C.getCapturedVar();
13276       if (VD->isInitCapture())
13277         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13278       QualType CaptureType = VD->getType();
13279       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13280       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13281           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13282           /*EllipsisLoc*/C.isPackExpansion()
13283                          ? C.getEllipsisLoc() : SourceLocation(),
13284           CaptureType, /*Invalid*/false);
13285
13286     } else if (C.capturesThis()) {
13287       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13288                           C.getCaptureKind() == LCK_StarThis);
13289     } else {
13290       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13291                              I->getType());
13292     }
13293     ++I;
13294   }
13295 }
13296
13297 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13298                                     SkipBodyInfo *SkipBody) {
13299   if (!D) {
13300     // Parsing the function declaration failed in some way. Push on a fake scope
13301     // anyway so we can try to parse the function body.
13302     PushFunctionScope();
13303     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13304     return D;
13305   }
13306
13307   FunctionDecl *FD = nullptr;
13308
13309   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13310     FD = FunTmpl->getTemplatedDecl();
13311   else
13312     FD = cast<FunctionDecl>(D);
13313
13314   // Do not push if it is a lambda because one is already pushed when building
13315   // the lambda in ActOnStartOfLambdaDefinition().
13316   if (!isLambdaCallOperator(FD))
13317     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13318
13319   // Check for defining attributes before the check for redefinition.
13320   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13321     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13322     FD->dropAttr<AliasAttr>();
13323     FD->setInvalidDecl();
13324   }
13325   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13326     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13327     FD->dropAttr<IFuncAttr>();
13328     FD->setInvalidDecl();
13329   }
13330
13331   // See if this is a redefinition. If 'will have body' is already set, then
13332   // these checks were already performed when it was set.
13333   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13334     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13335
13336     // If we're skipping the body, we're done. Don't enter the scope.
13337     if (SkipBody && SkipBody->ShouldSkip)
13338       return D;
13339   }
13340
13341   // Mark this function as "will have a body eventually".  This lets users to
13342   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13343   // this function.
13344   FD->setWillHaveBody();
13345
13346   // If we are instantiating a generic lambda call operator, push
13347   // a LambdaScopeInfo onto the function stack.  But use the information
13348   // that's already been calculated (ActOnLambdaExpr) to prime the current
13349   // LambdaScopeInfo.
13350   // When the template operator is being specialized, the LambdaScopeInfo,
13351   // has to be properly restored so that tryCaptureVariable doesn't try
13352   // and capture any new variables. In addition when calculating potential
13353   // captures during transformation of nested lambdas, it is necessary to
13354   // have the LSI properly restored.
13355   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13356     assert(inTemplateInstantiation() &&
13357            "There should be an active template instantiation on the stack "
13358            "when instantiating a generic lambda!");
13359     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13360   } else {
13361     // Enter a new function scope
13362     PushFunctionScope();
13363   }
13364
13365   // Builtin functions cannot be defined.
13366   if (unsigned BuiltinID = FD->getBuiltinID()) {
13367     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13368         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13369       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13370       FD->setInvalidDecl();
13371     }
13372   }
13373
13374   // The return type of a function definition must be complete
13375   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13376   QualType ResultType = FD->getReturnType();
13377   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13378       !FD->isInvalidDecl() &&
13379       RequireCompleteType(FD->getLocation(), ResultType,
13380                           diag::err_func_def_incomplete_result))
13381     FD->setInvalidDecl();
13382
13383   if (FnBodyScope)
13384     PushDeclContext(FnBodyScope, FD);
13385
13386   // Check the validity of our function parameters
13387   CheckParmsForFunctionDef(FD->parameters(),
13388                            /*CheckParameterNames=*/true);
13389
13390   // Add non-parameter declarations already in the function to the current
13391   // scope.
13392   if (FnBodyScope) {
13393     for (Decl *NPD : FD->decls()) {
13394       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13395       if (!NonParmDecl)
13396         continue;
13397       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13398              "parameters should not be in newly created FD yet");
13399
13400       // If the decl has a name, make it accessible in the current scope.
13401       if (NonParmDecl->getDeclName())
13402         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13403
13404       // Similarly, dive into enums and fish their constants out, making them
13405       // accessible in this scope.
13406       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13407         for (auto *EI : ED->enumerators())
13408           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13409       }
13410     }
13411   }
13412
13413   // Introduce our parameters into the function scope
13414   for (auto Param : FD->parameters()) {
13415     Param->setOwningFunction(FD);
13416
13417     // If this has an identifier, add it to the scope stack.
13418     if (Param->getIdentifier() && FnBodyScope) {
13419       CheckShadow(FnBodyScope, Param);
13420
13421       PushOnScopeChains(Param, FnBodyScope);
13422     }
13423   }
13424
13425   // Ensure that the function's exception specification is instantiated.
13426   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13427     ResolveExceptionSpec(D->getLocation(), FPT);
13428
13429   // dllimport cannot be applied to non-inline function definitions.
13430   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13431       !FD->isTemplateInstantiation()) {
13432     assert(!FD->hasAttr<DLLExportAttr>());
13433     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13434     FD->setInvalidDecl();
13435     return D;
13436   }
13437   // We want to attach documentation to original Decl (which might be
13438   // a function template).
13439   ActOnDocumentableDecl(D);
13440   if (getCurLexicalContext()->isObjCContainer() &&
13441       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13442       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13443     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13444
13445   return D;
13446 }
13447
13448 /// Given the set of return statements within a function body,
13449 /// compute the variables that are subject to the named return value
13450 /// optimization.
13451 ///
13452 /// Each of the variables that is subject to the named return value
13453 /// optimization will be marked as NRVO variables in the AST, and any
13454 /// return statement that has a marked NRVO variable as its NRVO candidate can
13455 /// use the named return value optimization.
13456 ///
13457 /// This function applies a very simplistic algorithm for NRVO: if every return
13458 /// statement in the scope of a variable has the same NRVO candidate, that
13459 /// candidate is an NRVO variable.
13460 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13461   ReturnStmt **Returns = Scope->Returns.data();
13462
13463   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13464     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13465       if (!NRVOCandidate->isNRVOVariable())
13466         Returns[I]->setNRVOCandidate(nullptr);
13467     }
13468   }
13469 }
13470
13471 bool Sema::canDelayFunctionBody(const Declarator &D) {
13472   // We can't delay parsing the body of a constexpr function template (yet).
13473   if (D.getDeclSpec().hasConstexprSpecifier())
13474     return false;
13475
13476   // We can't delay parsing the body of a function template with a deduced
13477   // return type (yet).
13478   if (D.getDeclSpec().hasAutoTypeSpec()) {
13479     // If the placeholder introduces a non-deduced trailing return type,
13480     // we can still delay parsing it.
13481     if (D.getNumTypeObjects()) {
13482       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13483       if (Outer.Kind == DeclaratorChunk::Function &&
13484           Outer.Fun.hasTrailingReturnType()) {
13485         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13486         return Ty.isNull() || !Ty->isUndeducedType();
13487       }
13488     }
13489     return false;
13490   }
13491
13492   return true;
13493 }
13494
13495 bool Sema::canSkipFunctionBody(Decl *D) {
13496   // We cannot skip the body of a function (or function template) which is
13497   // constexpr, since we may need to evaluate its body in order to parse the
13498   // rest of the file.
13499   // We cannot skip the body of a function with an undeduced return type,
13500   // because any callers of that function need to know the type.
13501   if (const FunctionDecl *FD = D->getAsFunction()) {
13502     if (FD->isConstexpr())
13503       return false;
13504     // We can't simply call Type::isUndeducedType here, because inside template
13505     // auto can be deduced to a dependent type, which is not considered
13506     // "undeduced".
13507     if (FD->getReturnType()->getContainedDeducedType())
13508       return false;
13509   }
13510   return Consumer.shouldSkipFunctionBody(D);
13511 }
13512
13513 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13514   if (!Decl)
13515     return nullptr;
13516   if (FunctionDecl *FD = Decl->getAsFunction())
13517     FD->setHasSkippedBody();
13518   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13519     MD->setHasSkippedBody();
13520   return Decl;
13521 }
13522
13523 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13524   return ActOnFinishFunctionBody(D, BodyArg, false);
13525 }
13526
13527 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13528 /// body.
13529 class ExitFunctionBodyRAII {
13530 public:
13531   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13532   ~ExitFunctionBodyRAII() {
13533     if (!IsLambda)
13534       S.PopExpressionEvaluationContext();
13535   }
13536
13537 private:
13538   Sema &S;
13539   bool IsLambda = false;
13540 };
13541
13542 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13543   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13544
13545   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13546     if (EscapeInfo.count(BD))
13547       return EscapeInfo[BD];
13548
13549     bool R = false;
13550     const BlockDecl *CurBD = BD;
13551
13552     do {
13553       R = !CurBD->doesNotEscape();
13554       if (R)
13555         break;
13556       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13557     } while (CurBD);
13558
13559     return EscapeInfo[BD] = R;
13560   };
13561
13562   // If the location where 'self' is implicitly retained is inside a escaping
13563   // block, emit a diagnostic.
13564   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13565        S.ImplicitlyRetainedSelfLocs)
13566     if (IsOrNestedInEscapingBlock(P.second))
13567       S.Diag(P.first, diag::warn_implicitly_retains_self)
13568           << FixItHint::CreateInsertion(P.first, "self->");
13569 }
13570
13571 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13572                                     bool IsInstantiation) {
13573   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13574
13575   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13576   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13577
13578   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13579     CheckCompletedCoroutineBody(FD, Body);
13580
13581   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13582   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13583   // meant to pop the context added in ActOnStartOfFunctionDef().
13584   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13585
13586   if (FD) {
13587     FD->setBody(Body);
13588     FD->setWillHaveBody(false);
13589
13590     if (getLangOpts().CPlusPlus14) {
13591       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13592           FD->getReturnType()->isUndeducedType()) {
13593         // If the function has a deduced result type but contains no 'return'
13594         // statements, the result type as written must be exactly 'auto', and
13595         // the deduced result type is 'void'.
13596         if (!FD->getReturnType()->getAs<AutoType>()) {
13597           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13598               << FD->getReturnType();
13599           FD->setInvalidDecl();
13600         } else {
13601           // Substitute 'void' for the 'auto' in the type.
13602           TypeLoc ResultType = getReturnTypeLoc(FD);
13603           Context.adjustDeducedFunctionResultType(
13604               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13605         }
13606       }
13607     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13608       // In C++11, we don't use 'auto' deduction rules for lambda call
13609       // operators because we don't support return type deduction.
13610       auto *LSI = getCurLambda();
13611       if (LSI->HasImplicitReturnType) {
13612         deduceClosureReturnType(*LSI);
13613
13614         // C++11 [expr.prim.lambda]p4:
13615         //   [...] if there are no return statements in the compound-statement
13616         //   [the deduced type is] the type void
13617         QualType RetType =
13618             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13619
13620         // Update the return type to the deduced type.
13621         const FunctionProtoType *Proto =
13622             FD->getType()->getAs<FunctionProtoType>();
13623         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13624                                             Proto->getExtProtoInfo()));
13625       }
13626     }
13627
13628     // If the function implicitly returns zero (like 'main') or is naked,
13629     // don't complain about missing return statements.
13630     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13631       WP.disableCheckFallThrough();
13632
13633     // MSVC permits the use of pure specifier (=0) on function definition,
13634     // defined at class scope, warn about this non-standard construct.
13635     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13636       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13637
13638     if (!FD->isInvalidDecl()) {
13639       // Don't diagnose unused parameters of defaulted or deleted functions.
13640       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13641         DiagnoseUnusedParameters(FD->parameters());
13642       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13643                                              FD->getReturnType(), FD);
13644
13645       // If this is a structor, we need a vtable.
13646       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13647         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13648       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13649         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13650
13651       // Try to apply the named return value optimization. We have to check
13652       // if we can do this here because lambdas keep return statements around
13653       // to deduce an implicit return type.
13654       if (FD->getReturnType()->isRecordType() &&
13655           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13656         computeNRVO(Body, getCurFunction());
13657     }
13658
13659     // GNU warning -Wmissing-prototypes:
13660     //   Warn if a global function is defined without a previous
13661     //   prototype declaration. This warning is issued even if the
13662     //   definition itself provides a prototype. The aim is to detect
13663     //   global functions that fail to be declared in header files.
13664     const FunctionDecl *PossiblePrototype = nullptr;
13665     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13666       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13667
13668       if (PossiblePrototype) {
13669         // We found a declaration that is not a prototype,
13670         // but that could be a zero-parameter prototype
13671         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13672           TypeLoc TL = TI->getTypeLoc();
13673           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13674             Diag(PossiblePrototype->getLocation(),
13675                  diag::note_declaration_not_a_prototype)
13676                 << (FD->getNumParams() != 0)
13677                 << (FD->getNumParams() == 0
13678                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13679                         : FixItHint{});
13680         }
13681       } else {
13682         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13683             << /* function */ 1
13684             << (FD->getStorageClass() == SC_None
13685                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13686                                                  "static ")
13687                     : FixItHint{});
13688       }
13689
13690       // GNU warning -Wstrict-prototypes
13691       //   Warn if K&R function is defined without a previous declaration.
13692       //   This warning is issued only if the definition itself does not provide
13693       //   a prototype. Only K&R definitions do not provide a prototype.
13694       //   An empty list in a function declarator that is part of a definition
13695       //   of that function specifies that the function has no parameters
13696       //   (C99 6.7.5.3p14)
13697       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13698           !LangOpts.CPlusPlus) {
13699         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13700         TypeLoc TL = TI->getTypeLoc();
13701         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13702         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13703       }
13704     }
13705
13706     // Warn on CPUDispatch with an actual body.
13707     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13708       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13709         if (!CmpndBody->body_empty())
13710           Diag(CmpndBody->body_front()->getBeginLoc(),
13711                diag::warn_dispatch_body_ignored);
13712
13713     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13714       const CXXMethodDecl *KeyFunction;
13715       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13716           MD->isVirtual() &&
13717           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13718           MD == KeyFunction->getCanonicalDecl()) {
13719         // Update the key-function state if necessary for this ABI.
13720         if (FD->isInlined() &&
13721             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13722           Context.setNonKeyFunction(MD);
13723
13724           // If the newly-chosen key function is already defined, then we
13725           // need to mark the vtable as used retroactively.
13726           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13727           const FunctionDecl *Definition;
13728           if (KeyFunction && KeyFunction->isDefined(Definition))
13729             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13730         } else {
13731           // We just defined they key function; mark the vtable as used.
13732           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13733         }
13734       }
13735     }
13736
13737     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13738            "Function parsing confused");
13739   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13740     assert(MD == getCurMethodDecl() && "Method parsing confused");
13741     MD->setBody(Body);
13742     if (!MD->isInvalidDecl()) {
13743       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13744                                              MD->getReturnType(), MD);
13745
13746       if (Body)
13747         computeNRVO(Body, getCurFunction());
13748     }
13749     if (getCurFunction()->ObjCShouldCallSuper) {
13750       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13751           << MD->getSelector().getAsString();
13752       getCurFunction()->ObjCShouldCallSuper = false;
13753     }
13754     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13755       const ObjCMethodDecl *InitMethod = nullptr;
13756       bool isDesignated =
13757           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13758       assert(isDesignated && InitMethod);
13759       (void)isDesignated;
13760
13761       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13762         auto IFace = MD->getClassInterface();
13763         if (!IFace)
13764           return false;
13765         auto SuperD = IFace->getSuperClass();
13766         if (!SuperD)
13767           return false;
13768         return SuperD->getIdentifier() ==
13769             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13770       };
13771       // Don't issue this warning for unavailable inits or direct subclasses
13772       // of NSObject.
13773       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13774         Diag(MD->getLocation(),
13775              diag::warn_objc_designated_init_missing_super_call);
13776         Diag(InitMethod->getLocation(),
13777              diag::note_objc_designated_init_marked_here);
13778       }
13779       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13780     }
13781     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13782       // Don't issue this warning for unavaialable inits.
13783       if (!MD->isUnavailable())
13784         Diag(MD->getLocation(),
13785              diag::warn_objc_secondary_init_missing_init_call);
13786       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13787     }
13788
13789     diagnoseImplicitlyRetainedSelf(*this);
13790   } else {
13791     // Parsing the function declaration failed in some way. Pop the fake scope
13792     // we pushed on.
13793     PopFunctionScopeInfo(ActivePolicy, dcl);
13794     return nullptr;
13795   }
13796
13797   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13798     DiagnoseUnguardedAvailabilityViolations(dcl);
13799
13800   assert(!getCurFunction()->ObjCShouldCallSuper &&
13801          "This should only be set for ObjC methods, which should have been "
13802          "handled in the block above.");
13803
13804   // Verify and clean out per-function state.
13805   if (Body && (!FD || !FD->isDefaulted())) {
13806     // C++ constructors that have function-try-blocks can't have return
13807     // statements in the handlers of that block. (C++ [except.handle]p14)
13808     // Verify this.
13809     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13810       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13811
13812     // Verify that gotos and switch cases don't jump into scopes illegally.
13813     if (getCurFunction()->NeedsScopeChecking() &&
13814         !PP.isCodeCompletionEnabled())
13815       DiagnoseInvalidJumps(Body);
13816
13817     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13818       if (!Destructor->getParent()->isDependentType())
13819         CheckDestructor(Destructor);
13820
13821       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13822                                              Destructor->getParent());
13823     }
13824
13825     // If any errors have occurred, clear out any temporaries that may have
13826     // been leftover. This ensures that these temporaries won't be picked up for
13827     // deletion in some later function.
13828     if (getDiagnostics().hasErrorOccurred() ||
13829         getDiagnostics().getSuppressAllDiagnostics()) {
13830       DiscardCleanupsInEvaluationContext();
13831     }
13832     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13833         !isa<FunctionTemplateDecl>(dcl)) {
13834       // Since the body is valid, issue any analysis-based warnings that are
13835       // enabled.
13836       ActivePolicy = &WP;
13837     }
13838
13839     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13840         (!CheckConstexprFunctionDecl(FD) ||
13841          !CheckConstexprFunctionBody(FD, Body)))
13842       FD->setInvalidDecl();
13843
13844     if (FD && FD->hasAttr<NakedAttr>()) {
13845       for (const Stmt *S : Body->children()) {
13846         // Allow local register variables without initializer as they don't
13847         // require prologue.
13848         bool RegisterVariables = false;
13849         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13850           for (const auto *Decl : DS->decls()) {
13851             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13852               RegisterVariables =
13853                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13854               if (!RegisterVariables)
13855                 break;
13856             }
13857           }
13858         }
13859         if (RegisterVariables)
13860           continue;
13861         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13862           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13863           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13864           FD->setInvalidDecl();
13865           break;
13866         }
13867       }
13868     }
13869
13870     assert(ExprCleanupObjects.size() ==
13871                ExprEvalContexts.back().NumCleanupObjects &&
13872            "Leftover temporaries in function");
13873     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13874     assert(MaybeODRUseExprs.empty() &&
13875            "Leftover expressions for odr-use checking");
13876   }
13877
13878   if (!IsInstantiation)
13879     PopDeclContext();
13880
13881   PopFunctionScopeInfo(ActivePolicy, dcl);
13882   // If any errors have occurred, clear out any temporaries that may have
13883   // been leftover. This ensures that these temporaries won't be picked up for
13884   // deletion in some later function.
13885   if (getDiagnostics().hasErrorOccurred()) {
13886     DiscardCleanupsInEvaluationContext();
13887   }
13888
13889   return dcl;
13890 }
13891
13892 /// When we finish delayed parsing of an attribute, we must attach it to the
13893 /// relevant Decl.
13894 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13895                                        ParsedAttributes &Attrs) {
13896   // Always attach attributes to the underlying decl.
13897   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13898     D = TD->getTemplatedDecl();
13899   ProcessDeclAttributeList(S, D, Attrs);
13900
13901   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13902     if (Method->isStatic())
13903       checkThisInStaticMemberFunctionAttributes(Method);
13904 }
13905
13906 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13907 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13908 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13909                                           IdentifierInfo &II, Scope *S) {
13910   // Find the scope in which the identifier is injected and the corresponding
13911   // DeclContext.
13912   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13913   // In that case, we inject the declaration into the translation unit scope
13914   // instead.
13915   Scope *BlockScope = S;
13916   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13917     BlockScope = BlockScope->getParent();
13918
13919   Scope *ContextScope = BlockScope;
13920   while (!ContextScope->getEntity())
13921     ContextScope = ContextScope->getParent();
13922   ContextRAII SavedContext(*this, ContextScope->getEntity());
13923
13924   // Before we produce a declaration for an implicitly defined
13925   // function, see whether there was a locally-scoped declaration of
13926   // this name as a function or variable. If so, use that
13927   // (non-visible) declaration, and complain about it.
13928   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13929   if (ExternCPrev) {
13930     // We still need to inject the function into the enclosing block scope so
13931     // that later (non-call) uses can see it.
13932     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13933
13934     // C89 footnote 38:
13935     //   If in fact it is not defined as having type "function returning int",
13936     //   the behavior is undefined.
13937     if (!isa<FunctionDecl>(ExternCPrev) ||
13938         !Context.typesAreCompatible(
13939             cast<FunctionDecl>(ExternCPrev)->getType(),
13940             Context.getFunctionNoProtoType(Context.IntTy))) {
13941       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13942           << ExternCPrev << !getLangOpts().C99;
13943       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13944       return ExternCPrev;
13945     }
13946   }
13947
13948   // Extension in C99.  Legal in C90, but warn about it.
13949   unsigned diag_id;
13950   if (II.getName().startswith("__builtin_"))
13951     diag_id = diag::warn_builtin_unknown;
13952   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13953   else if (getLangOpts().OpenCL)
13954     diag_id = diag::err_opencl_implicit_function_decl;
13955   else if (getLangOpts().C99)
13956     diag_id = diag::ext_implicit_function_decl;
13957   else
13958     diag_id = diag::warn_implicit_function_decl;
13959   Diag(Loc, diag_id) << &II;
13960
13961   // If we found a prior declaration of this function, don't bother building
13962   // another one. We've already pushed that one into scope, so there's nothing
13963   // more to do.
13964   if (ExternCPrev)
13965     return ExternCPrev;
13966
13967   // Because typo correction is expensive, only do it if the implicit
13968   // function declaration is going to be treated as an error.
13969   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13970     TypoCorrection Corrected;
13971     DeclFilterCCC<FunctionDecl> CCC{};
13972     if (S && (Corrected =
13973                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13974                               S, nullptr, CCC, CTK_NonError)))
13975       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13976                    /*ErrorRecovery*/false);
13977   }
13978
13979   // Set a Declarator for the implicit definition: int foo();
13980   const char *Dummy;
13981   AttributeFactory attrFactory;
13982   DeclSpec DS(attrFactory);
13983   unsigned DiagID;
13984   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13985                                   Context.getPrintingPolicy());
13986   (void)Error; // Silence warning.
13987   assert(!Error && "Error setting up implicit decl!");
13988   SourceLocation NoLoc;
13989   Declarator D(DS, DeclaratorContext::BlockContext);
13990   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13991                                              /*IsAmbiguous=*/false,
13992                                              /*LParenLoc=*/NoLoc,
13993                                              /*Params=*/nullptr,
13994                                              /*NumParams=*/0,
13995                                              /*EllipsisLoc=*/NoLoc,
13996                                              /*RParenLoc=*/NoLoc,
13997                                              /*RefQualifierIsLvalueRef=*/true,
13998                                              /*RefQualifierLoc=*/NoLoc,
13999                                              /*MutableLoc=*/NoLoc, EST_None,
14000                                              /*ESpecRange=*/SourceRange(),
14001                                              /*Exceptions=*/nullptr,
14002                                              /*ExceptionRanges=*/nullptr,
14003                                              /*NumExceptions=*/0,
14004                                              /*NoexceptExpr=*/nullptr,
14005                                              /*ExceptionSpecTokens=*/nullptr,
14006                                              /*DeclsInPrototype=*/None, Loc,
14007                                              Loc, D),
14008                 std::move(DS.getAttributes()), SourceLocation());
14009   D.SetIdentifier(&II, Loc);
14010
14011   // Insert this function into the enclosing block scope.
14012   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14013   FD->setImplicit();
14014
14015   AddKnownFunctionAttributes(FD);
14016
14017   return FD;
14018 }
14019
14020 /// Adds any function attributes that we know a priori based on
14021 /// the declaration of this function.
14022 ///
14023 /// These attributes can apply both to implicitly-declared builtins
14024 /// (like __builtin___printf_chk) or to library-declared functions
14025 /// like NSLog or printf.
14026 ///
14027 /// We need to check for duplicate attributes both here and where user-written
14028 /// attributes are applied to declarations.
14029 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14030   if (FD->isInvalidDecl())
14031     return;
14032
14033   // If this is a built-in function, map its builtin attributes to
14034   // actual attributes.
14035   if (unsigned BuiltinID = FD->getBuiltinID()) {
14036     // Handle printf-formatting attributes.
14037     unsigned FormatIdx;
14038     bool HasVAListArg;
14039     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14040       if (!FD->hasAttr<FormatAttr>()) {
14041         const char *fmt = "printf";
14042         unsigned int NumParams = FD->getNumParams();
14043         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14044             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14045           fmt = "NSString";
14046         FD->addAttr(FormatAttr::CreateImplicit(Context,
14047                                                &Context.Idents.get(fmt),
14048                                                FormatIdx+1,
14049                                                HasVAListArg ? 0 : FormatIdx+2,
14050                                                FD->getLocation()));
14051       }
14052     }
14053     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14054                                              HasVAListArg)) {
14055      if (!FD->hasAttr<FormatAttr>())
14056        FD->addAttr(FormatAttr::CreateImplicit(Context,
14057                                               &Context.Idents.get("scanf"),
14058                                               FormatIdx+1,
14059                                               HasVAListArg ? 0 : FormatIdx+2,
14060                                               FD->getLocation()));
14061     }
14062
14063     // Handle automatically recognized callbacks.
14064     SmallVector<int, 4> Encoding;
14065     if (!FD->hasAttr<CallbackAttr>() &&
14066         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14067       FD->addAttr(CallbackAttr::CreateImplicit(
14068           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14069
14070     // Mark const if we don't care about errno and that is the only thing
14071     // preventing the function from being const. This allows IRgen to use LLVM
14072     // intrinsics for such functions.
14073     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14074         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14075       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14076
14077     // We make "fma" on some platforms const because we know it does not set
14078     // errno in those environments even though it could set errno based on the
14079     // C standard.
14080     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14081     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14082         !FD->hasAttr<ConstAttr>()) {
14083       switch (BuiltinID) {
14084       case Builtin::BI__builtin_fma:
14085       case Builtin::BI__builtin_fmaf:
14086       case Builtin::BI__builtin_fmal:
14087       case Builtin::BIfma:
14088       case Builtin::BIfmaf:
14089       case Builtin::BIfmal:
14090         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14091         break;
14092       default:
14093         break;
14094       }
14095     }
14096
14097     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14098         !FD->hasAttr<ReturnsTwiceAttr>())
14099       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14100                                          FD->getLocation()));
14101     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14102       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14103     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14104       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14105     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14106       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14107     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14108         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14109       // Add the appropriate attribute, depending on the CUDA compilation mode
14110       // and which target the builtin belongs to. For example, during host
14111       // compilation, aux builtins are __device__, while the rest are __host__.
14112       if (getLangOpts().CUDAIsDevice !=
14113           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14114         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14115       else
14116         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14117     }
14118   }
14119
14120   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14121   // throw, add an implicit nothrow attribute to any extern "C" function we come
14122   // across.
14123   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14124       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14125     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14126     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14127       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14128   }
14129
14130   IdentifierInfo *Name = FD->getIdentifier();
14131   if (!Name)
14132     return;
14133   if ((!getLangOpts().CPlusPlus &&
14134        FD->getDeclContext()->isTranslationUnit()) ||
14135       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14136        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14137        LinkageSpecDecl::lang_c)) {
14138     // Okay: this could be a libc/libm/Objective-C function we know
14139     // about.
14140   } else
14141     return;
14142
14143   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14144     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14145     // target-specific builtins, perhaps?
14146     if (!FD->hasAttr<FormatAttr>())
14147       FD->addAttr(FormatAttr::CreateImplicit(Context,
14148                                              &Context.Idents.get("printf"), 2,
14149                                              Name->isStr("vasprintf") ? 0 : 3,
14150                                              FD->getLocation()));
14151   }
14152
14153   if (Name->isStr("__CFStringMakeConstantString")) {
14154     // We already have a __builtin___CFStringMakeConstantString,
14155     // but builds that use -fno-constant-cfstrings don't go through that.
14156     if (!FD->hasAttr<FormatArgAttr>())
14157       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14158                                                 FD->getLocation()));
14159   }
14160 }
14161
14162 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14163                                     TypeSourceInfo *TInfo) {
14164   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14165   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14166
14167   if (!TInfo) {
14168     assert(D.isInvalidType() && "no declarator info for valid type");
14169     TInfo = Context.getTrivialTypeSourceInfo(T);
14170   }
14171
14172   // Scope manipulation handled by caller.
14173   TypedefDecl *NewTD =
14174       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14175                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14176
14177   // Bail out immediately if we have an invalid declaration.
14178   if (D.isInvalidType()) {
14179     NewTD->setInvalidDecl();
14180     return NewTD;
14181   }
14182
14183   if (D.getDeclSpec().isModulePrivateSpecified()) {
14184     if (CurContext->isFunctionOrMethod())
14185       Diag(NewTD->getLocation(), diag::err_module_private_local)
14186         << 2 << NewTD->getDeclName()
14187         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14188         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14189     else
14190       NewTD->setModulePrivate();
14191   }
14192
14193   // C++ [dcl.typedef]p8:
14194   //   If the typedef declaration defines an unnamed class (or
14195   //   enum), the first typedef-name declared by the declaration
14196   //   to be that class type (or enum type) is used to denote the
14197   //   class type (or enum type) for linkage purposes only.
14198   // We need to check whether the type was declared in the declaration.
14199   switch (D.getDeclSpec().getTypeSpecType()) {
14200   case TST_enum:
14201   case TST_struct:
14202   case TST_interface:
14203   case TST_union:
14204   case TST_class: {
14205     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14206     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14207     break;
14208   }
14209
14210   default:
14211     break;
14212   }
14213
14214   return NewTD;
14215 }
14216
14217 /// Check that this is a valid underlying type for an enum declaration.
14218 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14219   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14220   QualType T = TI->getType();
14221
14222   if (T->isDependentType())
14223     return false;
14224
14225   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14226     if (BT->isInteger())
14227       return false;
14228
14229   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14230   return true;
14231 }
14232
14233 /// Check whether this is a valid redeclaration of a previous enumeration.
14234 /// \return true if the redeclaration was invalid.
14235 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14236                                   QualType EnumUnderlyingTy, bool IsFixed,
14237                                   const EnumDecl *Prev) {
14238   if (IsScoped != Prev->isScoped()) {
14239     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14240       << Prev->isScoped();
14241     Diag(Prev->getLocation(), diag::note_previous_declaration);
14242     return true;
14243   }
14244
14245   if (IsFixed && Prev->isFixed()) {
14246     if (!EnumUnderlyingTy->isDependentType() &&
14247         !Prev->getIntegerType()->isDependentType() &&
14248         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14249                                         Prev->getIntegerType())) {
14250       // TODO: Highlight the underlying type of the redeclaration.
14251       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14252         << EnumUnderlyingTy << Prev->getIntegerType();
14253       Diag(Prev->getLocation(), diag::note_previous_declaration)
14254           << Prev->getIntegerTypeRange();
14255       return true;
14256     }
14257   } else if (IsFixed != Prev->isFixed()) {
14258     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14259       << Prev->isFixed();
14260     Diag(Prev->getLocation(), diag::note_previous_declaration);
14261     return true;
14262   }
14263
14264   return false;
14265 }
14266
14267 /// Get diagnostic %select index for tag kind for
14268 /// redeclaration diagnostic message.
14269 /// WARNING: Indexes apply to particular diagnostics only!
14270 ///
14271 /// \returns diagnostic %select index.
14272 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14273   switch (Tag) {
14274   case TTK_Struct: return 0;
14275   case TTK_Interface: return 1;
14276   case TTK_Class:  return 2;
14277   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14278   }
14279 }
14280
14281 /// Determine if tag kind is a class-key compatible with
14282 /// class for redeclaration (class, struct, or __interface).
14283 ///
14284 /// \returns true iff the tag kind is compatible.
14285 static bool isClassCompatTagKind(TagTypeKind Tag)
14286 {
14287   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14288 }
14289
14290 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14291                                              TagTypeKind TTK) {
14292   if (isa<TypedefDecl>(PrevDecl))
14293     return NTK_Typedef;
14294   else if (isa<TypeAliasDecl>(PrevDecl))
14295     return NTK_TypeAlias;
14296   else if (isa<ClassTemplateDecl>(PrevDecl))
14297     return NTK_Template;
14298   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14299     return NTK_TypeAliasTemplate;
14300   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14301     return NTK_TemplateTemplateArgument;
14302   switch (TTK) {
14303   case TTK_Struct:
14304   case TTK_Interface:
14305   case TTK_Class:
14306     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14307   case TTK_Union:
14308     return NTK_NonUnion;
14309   case TTK_Enum:
14310     return NTK_NonEnum;
14311   }
14312   llvm_unreachable("invalid TTK");
14313 }
14314
14315 /// Determine whether a tag with a given kind is acceptable
14316 /// as a redeclaration of the given tag declaration.
14317 ///
14318 /// \returns true if the new tag kind is acceptable, false otherwise.
14319 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14320                                         TagTypeKind NewTag, bool isDefinition,
14321                                         SourceLocation NewTagLoc,
14322                                         const IdentifierInfo *Name) {
14323   // C++ [dcl.type.elab]p3:
14324   //   The class-key or enum keyword present in the
14325   //   elaborated-type-specifier shall agree in kind with the
14326   //   declaration to which the name in the elaborated-type-specifier
14327   //   refers. This rule also applies to the form of
14328   //   elaborated-type-specifier that declares a class-name or
14329   //   friend class since it can be construed as referring to the
14330   //   definition of the class. Thus, in any
14331   //   elaborated-type-specifier, the enum keyword shall be used to
14332   //   refer to an enumeration (7.2), the union class-key shall be
14333   //   used to refer to a union (clause 9), and either the class or
14334   //   struct class-key shall be used to refer to a class (clause 9)
14335   //   declared using the class or struct class-key.
14336   TagTypeKind OldTag = Previous->getTagKind();
14337   if (OldTag != NewTag &&
14338       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14339     return false;
14340
14341   // Tags are compatible, but we might still want to warn on mismatched tags.
14342   // Non-class tags can't be mismatched at this point.
14343   if (!isClassCompatTagKind(NewTag))
14344     return true;
14345
14346   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14347   // by our warning analysis. We don't want to warn about mismatches with (eg)
14348   // declarations in system headers that are designed to be specialized, but if
14349   // a user asks us to warn, we should warn if their code contains mismatched
14350   // declarations.
14351   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14352     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14353                                       Loc);
14354   };
14355   if (IsIgnoredLoc(NewTagLoc))
14356     return true;
14357
14358   auto IsIgnored = [&](const TagDecl *Tag) {
14359     return IsIgnoredLoc(Tag->getLocation());
14360   };
14361   while (IsIgnored(Previous)) {
14362     Previous = Previous->getPreviousDecl();
14363     if (!Previous)
14364       return true;
14365     OldTag = Previous->getTagKind();
14366   }
14367
14368   bool isTemplate = false;
14369   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14370     isTemplate = Record->getDescribedClassTemplate();
14371
14372   if (inTemplateInstantiation()) {
14373     if (OldTag != NewTag) {
14374       // In a template instantiation, do not offer fix-its for tag mismatches
14375       // since they usually mess up the template instead of fixing the problem.
14376       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14377         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14378         << getRedeclDiagFromTagKind(OldTag);
14379       // FIXME: Note previous location?
14380     }
14381     return true;
14382   }
14383
14384   if (isDefinition) {
14385     // On definitions, check all previous tags and issue a fix-it for each
14386     // one that doesn't match the current tag.
14387     if (Previous->getDefinition()) {
14388       // Don't suggest fix-its for redefinitions.
14389       return true;
14390     }
14391
14392     bool previousMismatch = false;
14393     for (const TagDecl *I : Previous->redecls()) {
14394       if (I->getTagKind() != NewTag) {
14395         // Ignore previous declarations for which the warning was disabled.
14396         if (IsIgnored(I))
14397           continue;
14398
14399         if (!previousMismatch) {
14400           previousMismatch = true;
14401           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14402             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14403             << getRedeclDiagFromTagKind(I->getTagKind());
14404         }
14405         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14406           << getRedeclDiagFromTagKind(NewTag)
14407           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14408                TypeWithKeyword::getTagTypeKindName(NewTag));
14409       }
14410     }
14411     return true;
14412   }
14413
14414   // Identify the prevailing tag kind: this is the kind of the definition (if
14415   // there is a non-ignored definition), or otherwise the kind of the prior
14416   // (non-ignored) declaration.
14417   const TagDecl *PrevDef = Previous->getDefinition();
14418   if (PrevDef && IsIgnored(PrevDef))
14419     PrevDef = nullptr;
14420   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14421   if (Redecl->getTagKind() != NewTag) {
14422     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14423       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14424       << getRedeclDiagFromTagKind(OldTag);
14425     Diag(Redecl->getLocation(), diag::note_previous_use);
14426
14427     // If there is a previous definition, suggest a fix-it.
14428     if (PrevDef) {
14429       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14430         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14431         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14432              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14433     }
14434   }
14435
14436   return true;
14437 }
14438
14439 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14440 /// from an outer enclosing namespace or file scope inside a friend declaration.
14441 /// This should provide the commented out code in the following snippet:
14442 ///   namespace N {
14443 ///     struct X;
14444 ///     namespace M {
14445 ///       struct Y { friend struct /*N::*/ X; };
14446 ///     }
14447 ///   }
14448 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14449                                          SourceLocation NameLoc) {
14450   // While the decl is in a namespace, do repeated lookup of that name and see
14451   // if we get the same namespace back.  If we do not, continue until
14452   // translation unit scope, at which point we have a fully qualified NNS.
14453   SmallVector<IdentifierInfo *, 4> Namespaces;
14454   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14455   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14456     // This tag should be declared in a namespace, which can only be enclosed by
14457     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14458     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14459     if (!Namespace || Namespace->isAnonymousNamespace())
14460       return FixItHint();
14461     IdentifierInfo *II = Namespace->getIdentifier();
14462     Namespaces.push_back(II);
14463     NamedDecl *Lookup = SemaRef.LookupSingleName(
14464         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14465     if (Lookup == Namespace)
14466       break;
14467   }
14468
14469   // Once we have all the namespaces, reverse them to go outermost first, and
14470   // build an NNS.
14471   SmallString<64> Insertion;
14472   llvm::raw_svector_ostream OS(Insertion);
14473   if (DC->isTranslationUnit())
14474     OS << "::";
14475   std::reverse(Namespaces.begin(), Namespaces.end());
14476   for (auto *II : Namespaces)
14477     OS << II->getName() << "::";
14478   return FixItHint::CreateInsertion(NameLoc, Insertion);
14479 }
14480
14481 /// Determine whether a tag originally declared in context \p OldDC can
14482 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14483 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14484 /// using-declaration).
14485 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14486                                          DeclContext *NewDC) {
14487   OldDC = OldDC->getRedeclContext();
14488   NewDC = NewDC->getRedeclContext();
14489
14490   if (OldDC->Equals(NewDC))
14491     return true;
14492
14493   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14494   // encloses the other).
14495   if (S.getLangOpts().MSVCCompat &&
14496       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14497     return true;
14498
14499   return false;
14500 }
14501
14502 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14503 /// former case, Name will be non-null.  In the later case, Name will be null.
14504 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14505 /// reference/declaration/definition of a tag.
14506 ///
14507 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14508 /// trailing-type-specifier) other than one in an alias-declaration.
14509 ///
14510 /// \param SkipBody If non-null, will be set to indicate if the caller should
14511 /// skip the definition of this tag and treat it as if it were a declaration.
14512 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14513                      SourceLocation KWLoc, CXXScopeSpec &SS,
14514                      IdentifierInfo *Name, SourceLocation NameLoc,
14515                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14516                      SourceLocation ModulePrivateLoc,
14517                      MultiTemplateParamsArg TemplateParameterLists,
14518                      bool &OwnedDecl, bool &IsDependent,
14519                      SourceLocation ScopedEnumKWLoc,
14520                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14521                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14522                      SkipBodyInfo *SkipBody) {
14523   // If this is not a definition, it must have a name.
14524   IdentifierInfo *OrigName = Name;
14525   assert((Name != nullptr || TUK == TUK_Definition) &&
14526          "Nameless record must be a definition!");
14527   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14528
14529   OwnedDecl = false;
14530   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14531   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14532
14533   // FIXME: Check member specializations more carefully.
14534   bool isMemberSpecialization = false;
14535   bool Invalid = false;
14536
14537   // We only need to do this matching if we have template parameters
14538   // or a scope specifier, which also conveniently avoids this work
14539   // for non-C++ cases.
14540   if (TemplateParameterLists.size() > 0 ||
14541       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14542     if (TemplateParameterList *TemplateParams =
14543             MatchTemplateParametersToScopeSpecifier(
14544                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14545                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14546       if (Kind == TTK_Enum) {
14547         Diag(KWLoc, diag::err_enum_template);
14548         return nullptr;
14549       }
14550
14551       if (TemplateParams->size() > 0) {
14552         // This is a declaration or definition of a class template (which may
14553         // be a member of another template).
14554
14555         if (Invalid)
14556           return nullptr;
14557
14558         OwnedDecl = false;
14559         DeclResult Result = CheckClassTemplate(
14560             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14561             AS, ModulePrivateLoc,
14562             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14563             TemplateParameterLists.data(), SkipBody);
14564         return Result.get();
14565       } else {
14566         // The "template<>" header is extraneous.
14567         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14568           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14569         isMemberSpecialization = true;
14570       }
14571     }
14572   }
14573
14574   // Figure out the underlying type if this a enum declaration. We need to do
14575   // this early, because it's needed to detect if this is an incompatible
14576   // redeclaration.
14577   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14578   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14579
14580   if (Kind == TTK_Enum) {
14581     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14582       // No underlying type explicitly specified, or we failed to parse the
14583       // type, default to int.
14584       EnumUnderlying = Context.IntTy.getTypePtr();
14585     } else if (UnderlyingType.get()) {
14586       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14587       // integral type; any cv-qualification is ignored.
14588       TypeSourceInfo *TI = nullptr;
14589       GetTypeFromParser(UnderlyingType.get(), &TI);
14590       EnumUnderlying = TI;
14591
14592       if (CheckEnumUnderlyingType(TI))
14593         // Recover by falling back to int.
14594         EnumUnderlying = Context.IntTy.getTypePtr();
14595
14596       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14597                                           UPPC_FixedUnderlyingType))
14598         EnumUnderlying = Context.IntTy.getTypePtr();
14599
14600     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14601       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14602       // of 'int'. However, if this is an unfixed forward declaration, don't set
14603       // the underlying type unless the user enables -fms-compatibility. This
14604       // makes unfixed forward declared enums incomplete and is more conforming.
14605       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14606         EnumUnderlying = Context.IntTy.getTypePtr();
14607     }
14608   }
14609
14610   DeclContext *SearchDC = CurContext;
14611   DeclContext *DC = CurContext;
14612   bool isStdBadAlloc = false;
14613   bool isStdAlignValT = false;
14614
14615   RedeclarationKind Redecl = forRedeclarationInCurContext();
14616   if (TUK == TUK_Friend || TUK == TUK_Reference)
14617     Redecl = NotForRedeclaration;
14618
14619   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14620   /// implemented asks for structural equivalence checking, the returned decl
14621   /// here is passed back to the parser, allowing the tag body to be parsed.
14622   auto createTagFromNewDecl = [&]() -> TagDecl * {
14623     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14624     // If there is an identifier, use the location of the identifier as the
14625     // location of the decl, otherwise use the location of the struct/union
14626     // keyword.
14627     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14628     TagDecl *New = nullptr;
14629
14630     if (Kind == TTK_Enum) {
14631       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14632                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14633       // If this is an undefined enum, bail.
14634       if (TUK != TUK_Definition && !Invalid)
14635         return nullptr;
14636       if (EnumUnderlying) {
14637         EnumDecl *ED = cast<EnumDecl>(New);
14638         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14639           ED->setIntegerTypeSourceInfo(TI);
14640         else
14641           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14642         ED->setPromotionType(ED->getIntegerType());
14643       }
14644     } else { // struct/union
14645       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14646                                nullptr);
14647     }
14648
14649     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14650       // Add alignment attributes if necessary; these attributes are checked
14651       // when the ASTContext lays out the structure.
14652       //
14653       // It is important for implementing the correct semantics that this
14654       // happen here (in ActOnTag). The #pragma pack stack is
14655       // maintained as a result of parser callbacks which can occur at
14656       // many points during the parsing of a struct declaration (because
14657       // the #pragma tokens are effectively skipped over during the
14658       // parsing of the struct).
14659       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14660         AddAlignmentAttributesForRecord(RD);
14661         AddMsStructLayoutForRecord(RD);
14662       }
14663     }
14664     New->setLexicalDeclContext(CurContext);
14665     return New;
14666   };
14667
14668   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14669   if (Name && SS.isNotEmpty()) {
14670     // We have a nested-name tag ('struct foo::bar').
14671
14672     // Check for invalid 'foo::'.
14673     if (SS.isInvalid()) {
14674       Name = nullptr;
14675       goto CreateNewDecl;
14676     }
14677
14678     // If this is a friend or a reference to a class in a dependent
14679     // context, don't try to make a decl for it.
14680     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14681       DC = computeDeclContext(SS, false);
14682       if (!DC) {
14683         IsDependent = true;
14684         return nullptr;
14685       }
14686     } else {
14687       DC = computeDeclContext(SS, true);
14688       if (!DC) {
14689         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14690           << SS.getRange();
14691         return nullptr;
14692       }
14693     }
14694
14695     if (RequireCompleteDeclContext(SS, DC))
14696       return nullptr;
14697
14698     SearchDC = DC;
14699     // Look-up name inside 'foo::'.
14700     LookupQualifiedName(Previous, DC);
14701
14702     if (Previous.isAmbiguous())
14703       return nullptr;
14704
14705     if (Previous.empty()) {
14706       // Name lookup did not find anything. However, if the
14707       // nested-name-specifier refers to the current instantiation,
14708       // and that current instantiation has any dependent base
14709       // classes, we might find something at instantiation time: treat
14710       // this as a dependent elaborated-type-specifier.
14711       // But this only makes any sense for reference-like lookups.
14712       if (Previous.wasNotFoundInCurrentInstantiation() &&
14713           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14714         IsDependent = true;
14715         return nullptr;
14716       }
14717
14718       // A tag 'foo::bar' must already exist.
14719       Diag(NameLoc, diag::err_not_tag_in_scope)
14720         << Kind << Name << DC << SS.getRange();
14721       Name = nullptr;
14722       Invalid = true;
14723       goto CreateNewDecl;
14724     }
14725   } else if (Name) {
14726     // C++14 [class.mem]p14:
14727     //   If T is the name of a class, then each of the following shall have a
14728     //   name different from T:
14729     //    -- every member of class T that is itself a type
14730     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14731         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14732       return nullptr;
14733
14734     // If this is a named struct, check to see if there was a previous forward
14735     // declaration or definition.
14736     // FIXME: We're looking into outer scopes here, even when we
14737     // shouldn't be. Doing so can result in ambiguities that we
14738     // shouldn't be diagnosing.
14739     LookupName(Previous, S);
14740
14741     // When declaring or defining a tag, ignore ambiguities introduced
14742     // by types using'ed into this scope.
14743     if (Previous.isAmbiguous() &&
14744         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14745       LookupResult::Filter F = Previous.makeFilter();
14746       while (F.hasNext()) {
14747         NamedDecl *ND = F.next();
14748         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14749                 SearchDC->getRedeclContext()))
14750           F.erase();
14751       }
14752       F.done();
14753     }
14754
14755     // C++11 [namespace.memdef]p3:
14756     //   If the name in a friend declaration is neither qualified nor
14757     //   a template-id and the declaration is a function or an
14758     //   elaborated-type-specifier, the lookup to determine whether
14759     //   the entity has been previously declared shall not consider
14760     //   any scopes outside the innermost enclosing namespace.
14761     //
14762     // MSVC doesn't implement the above rule for types, so a friend tag
14763     // declaration may be a redeclaration of a type declared in an enclosing
14764     // scope.  They do implement this rule for friend functions.
14765     //
14766     // Does it matter that this should be by scope instead of by
14767     // semantic context?
14768     if (!Previous.empty() && TUK == TUK_Friend) {
14769       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14770       LookupResult::Filter F = Previous.makeFilter();
14771       bool FriendSawTagOutsideEnclosingNamespace = false;
14772       while (F.hasNext()) {
14773         NamedDecl *ND = F.next();
14774         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14775         if (DC->isFileContext() &&
14776             !EnclosingNS->Encloses(ND->getDeclContext())) {
14777           if (getLangOpts().MSVCCompat)
14778             FriendSawTagOutsideEnclosingNamespace = true;
14779           else
14780             F.erase();
14781         }
14782       }
14783       F.done();
14784
14785       // Diagnose this MSVC extension in the easy case where lookup would have
14786       // unambiguously found something outside the enclosing namespace.
14787       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14788         NamedDecl *ND = Previous.getFoundDecl();
14789         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14790             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14791       }
14792     }
14793
14794     // Note:  there used to be some attempt at recovery here.
14795     if (Previous.isAmbiguous())
14796       return nullptr;
14797
14798     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14799       // FIXME: This makes sure that we ignore the contexts associated
14800       // with C structs, unions, and enums when looking for a matching
14801       // tag declaration or definition. See the similar lookup tweak
14802       // in Sema::LookupName; is there a better way to deal with this?
14803       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14804         SearchDC = SearchDC->getParent();
14805     }
14806   }
14807
14808   if (Previous.isSingleResult() &&
14809       Previous.getFoundDecl()->isTemplateParameter()) {
14810     // Maybe we will complain about the shadowed template parameter.
14811     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14812     // Just pretend that we didn't see the previous declaration.
14813     Previous.clear();
14814   }
14815
14816   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14817       DC->Equals(getStdNamespace())) {
14818     if (Name->isStr("bad_alloc")) {
14819       // This is a declaration of or a reference to "std::bad_alloc".
14820       isStdBadAlloc = true;
14821
14822       // If std::bad_alloc has been implicitly declared (but made invisible to
14823       // name lookup), fill in this implicit declaration as the previous
14824       // declaration, so that the declarations get chained appropriately.
14825       if (Previous.empty() && StdBadAlloc)
14826         Previous.addDecl(getStdBadAlloc());
14827     } else if (Name->isStr("align_val_t")) {
14828       isStdAlignValT = true;
14829       if (Previous.empty() && StdAlignValT)
14830         Previous.addDecl(getStdAlignValT());
14831     }
14832   }
14833
14834   // If we didn't find a previous declaration, and this is a reference
14835   // (or friend reference), move to the correct scope.  In C++, we
14836   // also need to do a redeclaration lookup there, just in case
14837   // there's a shadow friend decl.
14838   if (Name && Previous.empty() &&
14839       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14840     if (Invalid) goto CreateNewDecl;
14841     assert(SS.isEmpty());
14842
14843     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14844       // C++ [basic.scope.pdecl]p5:
14845       //   -- for an elaborated-type-specifier of the form
14846       //
14847       //          class-key identifier
14848       //
14849       //      if the elaborated-type-specifier is used in the
14850       //      decl-specifier-seq or parameter-declaration-clause of a
14851       //      function defined in namespace scope, the identifier is
14852       //      declared as a class-name in the namespace that contains
14853       //      the declaration; otherwise, except as a friend
14854       //      declaration, the identifier is declared in the smallest
14855       //      non-class, non-function-prototype scope that contains the
14856       //      declaration.
14857       //
14858       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14859       // C structs and unions.
14860       //
14861       // It is an error in C++ to declare (rather than define) an enum
14862       // type, including via an elaborated type specifier.  We'll
14863       // diagnose that later; for now, declare the enum in the same
14864       // scope as we would have picked for any other tag type.
14865       //
14866       // GNU C also supports this behavior as part of its incomplete
14867       // enum types extension, while GNU C++ does not.
14868       //
14869       // Find the context where we'll be declaring the tag.
14870       // FIXME: We would like to maintain the current DeclContext as the
14871       // lexical context,
14872       SearchDC = getTagInjectionContext(SearchDC);
14873
14874       // Find the scope where we'll be declaring the tag.
14875       S = getTagInjectionScope(S, getLangOpts());
14876     } else {
14877       assert(TUK == TUK_Friend);
14878       // C++ [namespace.memdef]p3:
14879       //   If a friend declaration in a non-local class first declares a
14880       //   class or function, the friend class or function is a member of
14881       //   the innermost enclosing namespace.
14882       SearchDC = SearchDC->getEnclosingNamespaceContext();
14883     }
14884
14885     // In C++, we need to do a redeclaration lookup to properly
14886     // diagnose some problems.
14887     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14888     // hidden declaration so that we don't get ambiguity errors when using a
14889     // type declared by an elaborated-type-specifier.  In C that is not correct
14890     // and we should instead merge compatible types found by lookup.
14891     if (getLangOpts().CPlusPlus) {
14892       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14893       LookupQualifiedName(Previous, SearchDC);
14894     } else {
14895       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14896       LookupName(Previous, S);
14897     }
14898   }
14899
14900   // If we have a known previous declaration to use, then use it.
14901   if (Previous.empty() && SkipBody && SkipBody->Previous)
14902     Previous.addDecl(SkipBody->Previous);
14903
14904   if (!Previous.empty()) {
14905     NamedDecl *PrevDecl = Previous.getFoundDecl();
14906     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14907
14908     // It's okay to have a tag decl in the same scope as a typedef
14909     // which hides a tag decl in the same scope.  Finding this
14910     // insanity with a redeclaration lookup can only actually happen
14911     // in C++.
14912     //
14913     // This is also okay for elaborated-type-specifiers, which is
14914     // technically forbidden by the current standard but which is
14915     // okay according to the likely resolution of an open issue;
14916     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14917     if (getLangOpts().CPlusPlus) {
14918       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14919         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14920           TagDecl *Tag = TT->getDecl();
14921           if (Tag->getDeclName() == Name &&
14922               Tag->getDeclContext()->getRedeclContext()
14923                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14924             PrevDecl = Tag;
14925             Previous.clear();
14926             Previous.addDecl(Tag);
14927             Previous.resolveKind();
14928           }
14929         }
14930       }
14931     }
14932
14933     // If this is a redeclaration of a using shadow declaration, it must
14934     // declare a tag in the same context. In MSVC mode, we allow a
14935     // redefinition if either context is within the other.
14936     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14937       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14938       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14939           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14940           !(OldTag && isAcceptableTagRedeclContext(
14941                           *this, OldTag->getDeclContext(), SearchDC))) {
14942         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14943         Diag(Shadow->getTargetDecl()->getLocation(),
14944              diag::note_using_decl_target);
14945         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14946             << 0;
14947         // Recover by ignoring the old declaration.
14948         Previous.clear();
14949         goto CreateNewDecl;
14950       }
14951     }
14952
14953     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14954       // If this is a use of a previous tag, or if the tag is already declared
14955       // in the same scope (so that the definition/declaration completes or
14956       // rementions the tag), reuse the decl.
14957       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14958           isDeclInScope(DirectPrevDecl, SearchDC, S,
14959                         SS.isNotEmpty() || isMemberSpecialization)) {
14960         // Make sure that this wasn't declared as an enum and now used as a
14961         // struct or something similar.
14962         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14963                                           TUK == TUK_Definition, KWLoc,
14964                                           Name)) {
14965           bool SafeToContinue
14966             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14967                Kind != TTK_Enum);
14968           if (SafeToContinue)
14969             Diag(KWLoc, diag::err_use_with_wrong_tag)
14970               << Name
14971               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14972                                               PrevTagDecl->getKindName());
14973           else
14974             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14975           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14976
14977           if (SafeToContinue)
14978             Kind = PrevTagDecl->getTagKind();
14979           else {
14980             // Recover by making this an anonymous redefinition.
14981             Name = nullptr;
14982             Previous.clear();
14983             Invalid = true;
14984           }
14985         }
14986
14987         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14988           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14989
14990           // If this is an elaborated-type-specifier for a scoped enumeration,
14991           // the 'class' keyword is not necessary and not permitted.
14992           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14993             if (ScopedEnum)
14994               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14995                 << PrevEnum->isScoped()
14996                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14997             return PrevTagDecl;
14998           }
14999
15000           QualType EnumUnderlyingTy;
15001           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15002             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15003           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15004             EnumUnderlyingTy = QualType(T, 0);
15005
15006           // All conflicts with previous declarations are recovered by
15007           // returning the previous declaration, unless this is a definition,
15008           // in which case we want the caller to bail out.
15009           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15010                                      ScopedEnum, EnumUnderlyingTy,
15011                                      IsFixed, PrevEnum))
15012             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15013         }
15014
15015         // C++11 [class.mem]p1:
15016         //   A member shall not be declared twice in the member-specification,
15017         //   except that a nested class or member class template can be declared
15018         //   and then later defined.
15019         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15020             S->isDeclScope(PrevDecl)) {
15021           Diag(NameLoc, diag::ext_member_redeclared);
15022           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15023         }
15024
15025         if (!Invalid) {
15026           // If this is a use, just return the declaration we found, unless
15027           // we have attributes.
15028           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15029             if (!Attrs.empty()) {
15030               // FIXME: Diagnose these attributes. For now, we create a new
15031               // declaration to hold them.
15032             } else if (TUK == TUK_Reference &&
15033                        (PrevTagDecl->getFriendObjectKind() ==
15034                             Decl::FOK_Undeclared ||
15035                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15036                        SS.isEmpty()) {
15037               // This declaration is a reference to an existing entity, but
15038               // has different visibility from that entity: it either makes
15039               // a friend visible or it makes a type visible in a new module.
15040               // In either case, create a new declaration. We only do this if
15041               // the declaration would have meant the same thing if no prior
15042               // declaration were found, that is, if it was found in the same
15043               // scope where we would have injected a declaration.
15044               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15045                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15046                 return PrevTagDecl;
15047               // This is in the injected scope, create a new declaration in
15048               // that scope.
15049               S = getTagInjectionScope(S, getLangOpts());
15050             } else {
15051               return PrevTagDecl;
15052             }
15053           }
15054
15055           // Diagnose attempts to redefine a tag.
15056           if (TUK == TUK_Definition) {
15057             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15058               // If we're defining a specialization and the previous definition
15059               // is from an implicit instantiation, don't emit an error
15060               // here; we'll catch this in the general case below.
15061               bool IsExplicitSpecializationAfterInstantiation = false;
15062               if (isMemberSpecialization) {
15063                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15064                   IsExplicitSpecializationAfterInstantiation =
15065                     RD->getTemplateSpecializationKind() !=
15066                     TSK_ExplicitSpecialization;
15067                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15068                   IsExplicitSpecializationAfterInstantiation =
15069                     ED->getTemplateSpecializationKind() !=
15070                     TSK_ExplicitSpecialization;
15071               }
15072
15073               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15074               // not keep more that one definition around (merge them). However,
15075               // ensure the decl passes the structural compatibility check in
15076               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15077               NamedDecl *Hidden = nullptr;
15078               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15079                 // There is a definition of this tag, but it is not visible. We
15080                 // explicitly make use of C++'s one definition rule here, and
15081                 // assume that this definition is identical to the hidden one
15082                 // we already have. Make the existing definition visible and
15083                 // use it in place of this one.
15084                 if (!getLangOpts().CPlusPlus) {
15085                   // Postpone making the old definition visible until after we
15086                   // complete parsing the new one and do the structural
15087                   // comparison.
15088                   SkipBody->CheckSameAsPrevious = true;
15089                   SkipBody->New = createTagFromNewDecl();
15090                   SkipBody->Previous = Def;
15091                   return Def;
15092                 } else {
15093                   SkipBody->ShouldSkip = true;
15094                   SkipBody->Previous = Def;
15095                   makeMergedDefinitionVisible(Hidden);
15096                   // Carry on and handle it like a normal definition. We'll
15097                   // skip starting the definitiion later.
15098                 }
15099               } else if (!IsExplicitSpecializationAfterInstantiation) {
15100                 // A redeclaration in function prototype scope in C isn't
15101                 // visible elsewhere, so merely issue a warning.
15102                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15103                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15104                 else
15105                   Diag(NameLoc, diag::err_redefinition) << Name;
15106                 notePreviousDefinition(Def,
15107                                        NameLoc.isValid() ? NameLoc : KWLoc);
15108                 // If this is a redefinition, recover by making this
15109                 // struct be anonymous, which will make any later
15110                 // references get the previous definition.
15111                 Name = nullptr;
15112                 Previous.clear();
15113                 Invalid = true;
15114               }
15115             } else {
15116               // If the type is currently being defined, complain
15117               // about a nested redefinition.
15118               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15119               if (TD->isBeingDefined()) {
15120                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15121                 Diag(PrevTagDecl->getLocation(),
15122                      diag::note_previous_definition);
15123                 Name = nullptr;
15124                 Previous.clear();
15125                 Invalid = true;
15126               }
15127             }
15128
15129             // Okay, this is definition of a previously declared or referenced
15130             // tag. We're going to create a new Decl for it.
15131           }
15132
15133           // Okay, we're going to make a redeclaration.  If this is some kind
15134           // of reference, make sure we build the redeclaration in the same DC
15135           // as the original, and ignore the current access specifier.
15136           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15137             SearchDC = PrevTagDecl->getDeclContext();
15138             AS = AS_none;
15139           }
15140         }
15141         // If we get here we have (another) forward declaration or we
15142         // have a definition.  Just create a new decl.
15143
15144       } else {
15145         // If we get here, this is a definition of a new tag type in a nested
15146         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15147         // new decl/type.  We set PrevDecl to NULL so that the entities
15148         // have distinct types.
15149         Previous.clear();
15150       }
15151       // If we get here, we're going to create a new Decl. If PrevDecl
15152       // is non-NULL, it's a definition of the tag declared by
15153       // PrevDecl. If it's NULL, we have a new definition.
15154
15155     // Otherwise, PrevDecl is not a tag, but was found with tag
15156     // lookup.  This is only actually possible in C++, where a few
15157     // things like templates still live in the tag namespace.
15158     } else {
15159       // Use a better diagnostic if an elaborated-type-specifier
15160       // found the wrong kind of type on the first
15161       // (non-redeclaration) lookup.
15162       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15163           !Previous.isForRedeclaration()) {
15164         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15165         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15166                                                        << Kind;
15167         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15168         Invalid = true;
15169
15170       // Otherwise, only diagnose if the declaration is in scope.
15171       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15172                                 SS.isNotEmpty() || isMemberSpecialization)) {
15173         // do nothing
15174
15175       // Diagnose implicit declarations introduced by elaborated types.
15176       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15177         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15178         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15179         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15180         Invalid = true;
15181
15182       // Otherwise it's a declaration.  Call out a particularly common
15183       // case here.
15184       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15185         unsigned Kind = 0;
15186         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15187         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15188           << Name << Kind << TND->getUnderlyingType();
15189         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15190         Invalid = true;
15191
15192       // Otherwise, diagnose.
15193       } else {
15194         // The tag name clashes with something else in the target scope,
15195         // issue an error and recover by making this tag be anonymous.
15196         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15197         notePreviousDefinition(PrevDecl, NameLoc);
15198         Name = nullptr;
15199         Invalid = true;
15200       }
15201
15202       // The existing declaration isn't relevant to us; we're in a
15203       // new scope, so clear out the previous declaration.
15204       Previous.clear();
15205     }
15206   }
15207
15208 CreateNewDecl:
15209
15210   TagDecl *PrevDecl = nullptr;
15211   if (Previous.isSingleResult())
15212     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15213
15214   // If there is an identifier, use the location of the identifier as the
15215   // location of the decl, otherwise use the location of the struct/union
15216   // keyword.
15217   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15218
15219   // Otherwise, create a new declaration. If there is a previous
15220   // declaration of the same entity, the two will be linked via
15221   // PrevDecl.
15222   TagDecl *New;
15223
15224   if (Kind == TTK_Enum) {
15225     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15226     // enum X { A, B, C } D;    D should chain to X.
15227     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15228                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15229                            ScopedEnumUsesClassTag, IsFixed);
15230
15231     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15232       StdAlignValT = cast<EnumDecl>(New);
15233
15234     // If this is an undefined enum, warn.
15235     if (TUK != TUK_Definition && !Invalid) {
15236       TagDecl *Def;
15237       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15238         // C++0x: 7.2p2: opaque-enum-declaration.
15239         // Conflicts are diagnosed above. Do nothing.
15240       }
15241       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15242         Diag(Loc, diag::ext_forward_ref_enum_def)
15243           << New;
15244         Diag(Def->getLocation(), diag::note_previous_definition);
15245       } else {
15246         unsigned DiagID = diag::ext_forward_ref_enum;
15247         if (getLangOpts().MSVCCompat)
15248           DiagID = diag::ext_ms_forward_ref_enum;
15249         else if (getLangOpts().CPlusPlus)
15250           DiagID = diag::err_forward_ref_enum;
15251         Diag(Loc, DiagID);
15252       }
15253     }
15254
15255     if (EnumUnderlying) {
15256       EnumDecl *ED = cast<EnumDecl>(New);
15257       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15258         ED->setIntegerTypeSourceInfo(TI);
15259       else
15260         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15261       ED->setPromotionType(ED->getIntegerType());
15262       assert(ED->isComplete() && "enum with type should be complete");
15263     }
15264   } else {
15265     // struct/union/class
15266
15267     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15268     // struct X { int A; } D;    D should chain to X.
15269     if (getLangOpts().CPlusPlus) {
15270       // FIXME: Look for a way to use RecordDecl for simple structs.
15271       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15272                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15273
15274       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15275         StdBadAlloc = cast<CXXRecordDecl>(New);
15276     } else
15277       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15278                                cast_or_null<RecordDecl>(PrevDecl));
15279   }
15280
15281   // C++11 [dcl.type]p3:
15282   //   A type-specifier-seq shall not define a class or enumeration [...].
15283   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15284       TUK == TUK_Definition) {
15285     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15286       << Context.getTagDeclType(New);
15287     Invalid = true;
15288   }
15289
15290   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15291       DC->getDeclKind() == Decl::Enum) {
15292     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15293       << Context.getTagDeclType(New);
15294     Invalid = true;
15295   }
15296
15297   // Maybe add qualifier info.
15298   if (SS.isNotEmpty()) {
15299     if (SS.isSet()) {
15300       // If this is either a declaration or a definition, check the
15301       // nested-name-specifier against the current context.
15302       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15303           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15304                                        isMemberSpecialization))
15305         Invalid = true;
15306
15307       New->setQualifierInfo(SS.getWithLocInContext(Context));
15308       if (TemplateParameterLists.size() > 0) {
15309         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15310       }
15311     }
15312     else
15313       Invalid = true;
15314   }
15315
15316   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15317     // Add alignment attributes if necessary; these attributes are checked when
15318     // the ASTContext lays out the structure.
15319     //
15320     // It is important for implementing the correct semantics that this
15321     // happen here (in ActOnTag). The #pragma pack stack is
15322     // maintained as a result of parser callbacks which can occur at
15323     // many points during the parsing of a struct declaration (because
15324     // the #pragma tokens are effectively skipped over during the
15325     // parsing of the struct).
15326     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15327       AddAlignmentAttributesForRecord(RD);
15328       AddMsStructLayoutForRecord(RD);
15329     }
15330   }
15331
15332   if (ModulePrivateLoc.isValid()) {
15333     if (isMemberSpecialization)
15334       Diag(New->getLocation(), diag::err_module_private_specialization)
15335         << 2
15336         << FixItHint::CreateRemoval(ModulePrivateLoc);
15337     // __module_private__ does not apply to local classes. However, we only
15338     // diagnose this as an error when the declaration specifiers are
15339     // freestanding. Here, we just ignore the __module_private__.
15340     else if (!SearchDC->isFunctionOrMethod())
15341       New->setModulePrivate();
15342   }
15343
15344   // If this is a specialization of a member class (of a class template),
15345   // check the specialization.
15346   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15347     Invalid = true;
15348
15349   // If we're declaring or defining a tag in function prototype scope in C,
15350   // note that this type can only be used within the function and add it to
15351   // the list of decls to inject into the function definition scope.
15352   if ((Name || Kind == TTK_Enum) &&
15353       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15354     if (getLangOpts().CPlusPlus) {
15355       // C++ [dcl.fct]p6:
15356       //   Types shall not be defined in return or parameter types.
15357       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15358         Diag(Loc, diag::err_type_defined_in_param_type)
15359             << Name;
15360         Invalid = true;
15361       }
15362     } else if (!PrevDecl) {
15363       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15364     }
15365   }
15366
15367   if (Invalid)
15368     New->setInvalidDecl();
15369
15370   // Set the lexical context. If the tag has a C++ scope specifier, the
15371   // lexical context will be different from the semantic context.
15372   New->setLexicalDeclContext(CurContext);
15373
15374   // Mark this as a friend decl if applicable.
15375   // In Microsoft mode, a friend declaration also acts as a forward
15376   // declaration so we always pass true to setObjectOfFriendDecl to make
15377   // the tag name visible.
15378   if (TUK == TUK_Friend)
15379     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15380
15381   // Set the access specifier.
15382   if (!Invalid && SearchDC->isRecord())
15383     SetMemberAccessSpecifier(New, PrevDecl, AS);
15384
15385   if (PrevDecl)
15386     CheckRedeclarationModuleOwnership(New, PrevDecl);
15387
15388   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15389     New->startDefinition();
15390
15391   ProcessDeclAttributeList(S, New, Attrs);
15392   AddPragmaAttributes(S, New);
15393
15394   // If this has an identifier, add it to the scope stack.
15395   if (TUK == TUK_Friend) {
15396     // We might be replacing an existing declaration in the lookup tables;
15397     // if so, borrow its access specifier.
15398     if (PrevDecl)
15399       New->setAccess(PrevDecl->getAccess());
15400
15401     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15402     DC->makeDeclVisibleInContext(New);
15403     if (Name) // can be null along some error paths
15404       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15405         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15406   } else if (Name) {
15407     S = getNonFieldDeclScope(S);
15408     PushOnScopeChains(New, S, true);
15409   } else {
15410     CurContext->addDecl(New);
15411   }
15412
15413   // If this is the C FILE type, notify the AST context.
15414   if (IdentifierInfo *II = New->getIdentifier())
15415     if (!New->isInvalidDecl() &&
15416         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15417         II->isStr("FILE"))
15418       Context.setFILEDecl(New);
15419
15420   if (PrevDecl)
15421     mergeDeclAttributes(New, PrevDecl);
15422
15423   // If there's a #pragma GCC visibility in scope, set the visibility of this
15424   // record.
15425   AddPushedVisibilityAttribute(New);
15426
15427   if (isMemberSpecialization && !New->isInvalidDecl())
15428     CompleteMemberSpecialization(New, Previous);
15429
15430   OwnedDecl = true;
15431   // In C++, don't return an invalid declaration. We can't recover well from
15432   // the cases where we make the type anonymous.
15433   if (Invalid && getLangOpts().CPlusPlus) {
15434     if (New->isBeingDefined())
15435       if (auto RD = dyn_cast<RecordDecl>(New))
15436         RD->completeDefinition();
15437     return nullptr;
15438   } else if (SkipBody && SkipBody->ShouldSkip) {
15439     return SkipBody->Previous;
15440   } else {
15441     return New;
15442   }
15443 }
15444
15445 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15446   AdjustDeclIfTemplate(TagD);
15447   TagDecl *Tag = cast<TagDecl>(TagD);
15448
15449   // Enter the tag context.
15450   PushDeclContext(S, Tag);
15451
15452   ActOnDocumentableDecl(TagD);
15453
15454   // If there's a #pragma GCC visibility in scope, set the visibility of this
15455   // record.
15456   AddPushedVisibilityAttribute(Tag);
15457 }
15458
15459 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15460                                     SkipBodyInfo &SkipBody) {
15461   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15462     return false;
15463
15464   // Make the previous decl visible.
15465   makeMergedDefinitionVisible(SkipBody.Previous);
15466   return true;
15467 }
15468
15469 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15470   assert(isa<ObjCContainerDecl>(IDecl) &&
15471          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15472   DeclContext *OCD = cast<DeclContext>(IDecl);
15473   assert(getContainingDC(OCD) == CurContext &&
15474       "The next DeclContext should be lexically contained in the current one.");
15475   CurContext = OCD;
15476   return IDecl;
15477 }
15478
15479 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15480                                            SourceLocation FinalLoc,
15481                                            bool IsFinalSpelledSealed,
15482                                            SourceLocation LBraceLoc) {
15483   AdjustDeclIfTemplate(TagD);
15484   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15485
15486   FieldCollector->StartClass();
15487
15488   if (!Record->getIdentifier())
15489     return;
15490
15491   if (FinalLoc.isValid())
15492     Record->addAttr(new (Context)
15493                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15494
15495   // C++ [class]p2:
15496   //   [...] The class-name is also inserted into the scope of the
15497   //   class itself; this is known as the injected-class-name. For
15498   //   purposes of access checking, the injected-class-name is treated
15499   //   as if it were a public member name.
15500   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15501       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15502       Record->getLocation(), Record->getIdentifier(),
15503       /*PrevDecl=*/nullptr,
15504       /*DelayTypeCreation=*/true);
15505   Context.getTypeDeclType(InjectedClassName, Record);
15506   InjectedClassName->setImplicit();
15507   InjectedClassName->setAccess(AS_public);
15508   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15509       InjectedClassName->setDescribedClassTemplate(Template);
15510   PushOnScopeChains(InjectedClassName, S);
15511   assert(InjectedClassName->isInjectedClassName() &&
15512          "Broken injected-class-name");
15513 }
15514
15515 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15516                                     SourceRange BraceRange) {
15517   AdjustDeclIfTemplate(TagD);
15518   TagDecl *Tag = cast<TagDecl>(TagD);
15519   Tag->setBraceRange(BraceRange);
15520
15521   // Make sure we "complete" the definition even it is invalid.
15522   if (Tag->isBeingDefined()) {
15523     assert(Tag->isInvalidDecl() && "We should already have completed it");
15524     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15525       RD->completeDefinition();
15526   }
15527
15528   if (isa<CXXRecordDecl>(Tag)) {
15529     FieldCollector->FinishClass();
15530   }
15531
15532   // Exit this scope of this tag's definition.
15533   PopDeclContext();
15534
15535   if (getCurLexicalContext()->isObjCContainer() &&
15536       Tag->getDeclContext()->isFileContext())
15537     Tag->setTopLevelDeclInObjCContainer();
15538
15539   // Notify the consumer that we've defined a tag.
15540   if (!Tag->isInvalidDecl())
15541     Consumer.HandleTagDeclDefinition(Tag);
15542 }
15543
15544 void Sema::ActOnObjCContainerFinishDefinition() {
15545   // Exit this scope of this interface definition.
15546   PopDeclContext();
15547 }
15548
15549 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15550   assert(DC == CurContext && "Mismatch of container contexts");
15551   OriginalLexicalContext = DC;
15552   ActOnObjCContainerFinishDefinition();
15553 }
15554
15555 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15556   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15557   OriginalLexicalContext = nullptr;
15558 }
15559
15560 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15561   AdjustDeclIfTemplate(TagD);
15562   TagDecl *Tag = cast<TagDecl>(TagD);
15563   Tag->setInvalidDecl();
15564
15565   // Make sure we "complete" the definition even it is invalid.
15566   if (Tag->isBeingDefined()) {
15567     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15568       RD->completeDefinition();
15569   }
15570
15571   // We're undoing ActOnTagStartDefinition here, not
15572   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15573   // the FieldCollector.
15574
15575   PopDeclContext();
15576 }
15577
15578 // Note that FieldName may be null for anonymous bitfields.
15579 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15580                                 IdentifierInfo *FieldName,
15581                                 QualType FieldTy, bool IsMsStruct,
15582                                 Expr *BitWidth, bool *ZeroWidth) {
15583   // Default to true; that shouldn't confuse checks for emptiness
15584   if (ZeroWidth)
15585     *ZeroWidth = true;
15586
15587   // C99 6.7.2.1p4 - verify the field type.
15588   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15589   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15590     // Handle incomplete types with specific error.
15591     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15592       return ExprError();
15593     if (FieldName)
15594       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15595         << FieldName << FieldTy << BitWidth->getSourceRange();
15596     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15597       << FieldTy << BitWidth->getSourceRange();
15598   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15599                                              UPPC_BitFieldWidth))
15600     return ExprError();
15601
15602   // If the bit-width is type- or value-dependent, don't try to check
15603   // it now.
15604   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15605     return BitWidth;
15606
15607   llvm::APSInt Value;
15608   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15609   if (ICE.isInvalid())
15610     return ICE;
15611   BitWidth = ICE.get();
15612
15613   if (Value != 0 && ZeroWidth)
15614     *ZeroWidth = false;
15615
15616   // Zero-width bitfield is ok for anonymous field.
15617   if (Value == 0 && FieldName)
15618     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15619
15620   if (Value.isSigned() && Value.isNegative()) {
15621     if (FieldName)
15622       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15623                << FieldName << Value.toString(10);
15624     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15625       << Value.toString(10);
15626   }
15627
15628   if (!FieldTy->isDependentType()) {
15629     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15630     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15631     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15632
15633     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15634     // ABI.
15635     bool CStdConstraintViolation =
15636         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15637     bool MSBitfieldViolation =
15638         Value.ugt(TypeStorageSize) &&
15639         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15640     if (CStdConstraintViolation || MSBitfieldViolation) {
15641       unsigned DiagWidth =
15642           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15643       if (FieldName)
15644         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15645                << FieldName << (unsigned)Value.getZExtValue()
15646                << !CStdConstraintViolation << DiagWidth;
15647
15648       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15649              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15650              << DiagWidth;
15651     }
15652
15653     // Warn on types where the user might conceivably expect to get all
15654     // specified bits as value bits: that's all integral types other than
15655     // 'bool'.
15656     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15657       if (FieldName)
15658         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15659             << FieldName << (unsigned)Value.getZExtValue()
15660             << (unsigned)TypeWidth;
15661       else
15662         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15663             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15664     }
15665   }
15666
15667   return BitWidth;
15668 }
15669
15670 /// ActOnField - Each field of a C struct/union is passed into this in order
15671 /// to create a FieldDecl object for it.
15672 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15673                        Declarator &D, Expr *BitfieldWidth) {
15674   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15675                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15676                                /*InitStyle=*/ICIS_NoInit, AS_public);
15677   return Res;
15678 }
15679
15680 /// HandleField - Analyze a field of a C struct or a C++ data member.
15681 ///
15682 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15683                              SourceLocation DeclStart,
15684                              Declarator &D, Expr *BitWidth,
15685                              InClassInitStyle InitStyle,
15686                              AccessSpecifier AS) {
15687   if (D.isDecompositionDeclarator()) {
15688     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15689     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15690       << Decomp.getSourceRange();
15691     return nullptr;
15692   }
15693
15694   IdentifierInfo *II = D.getIdentifier();
15695   SourceLocation Loc = DeclStart;
15696   if (II) Loc = D.getIdentifierLoc();
15697
15698   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15699   QualType T = TInfo->getType();
15700   if (getLangOpts().CPlusPlus) {
15701     CheckExtraCXXDefaultArguments(D);
15702
15703     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15704                                         UPPC_DataMemberType)) {
15705       D.setInvalidType();
15706       T = Context.IntTy;
15707       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15708     }
15709   }
15710
15711   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15712
15713   if (D.getDeclSpec().isInlineSpecified())
15714     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15715         << getLangOpts().CPlusPlus17;
15716   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15717     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15718          diag::err_invalid_thread)
15719       << DeclSpec::getSpecifierName(TSCS);
15720
15721   // Check to see if this name was declared as a member previously
15722   NamedDecl *PrevDecl = nullptr;
15723   LookupResult Previous(*this, II, Loc, LookupMemberName,
15724                         ForVisibleRedeclaration);
15725   LookupName(Previous, S);
15726   switch (Previous.getResultKind()) {
15727     case LookupResult::Found:
15728     case LookupResult::FoundUnresolvedValue:
15729       PrevDecl = Previous.getAsSingle<NamedDecl>();
15730       break;
15731
15732     case LookupResult::FoundOverloaded:
15733       PrevDecl = Previous.getRepresentativeDecl();
15734       break;
15735
15736     case LookupResult::NotFound:
15737     case LookupResult::NotFoundInCurrentInstantiation:
15738     case LookupResult::Ambiguous:
15739       break;
15740   }
15741   Previous.suppressDiagnostics();
15742
15743   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15744     // Maybe we will complain about the shadowed template parameter.
15745     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15746     // Just pretend that we didn't see the previous declaration.
15747     PrevDecl = nullptr;
15748   }
15749
15750   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15751     PrevDecl = nullptr;
15752
15753   bool Mutable
15754     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15755   SourceLocation TSSL = D.getBeginLoc();
15756   FieldDecl *NewFD
15757     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15758                      TSSL, AS, PrevDecl, &D);
15759
15760   if (NewFD->isInvalidDecl())
15761     Record->setInvalidDecl();
15762
15763   if (D.getDeclSpec().isModulePrivateSpecified())
15764     NewFD->setModulePrivate();
15765
15766   if (NewFD->isInvalidDecl() && PrevDecl) {
15767     // Don't introduce NewFD into scope; there's already something
15768     // with the same name in the same scope.
15769   } else if (II) {
15770     PushOnScopeChains(NewFD, S);
15771   } else
15772     Record->addDecl(NewFD);
15773
15774   return NewFD;
15775 }
15776
15777 /// Build a new FieldDecl and check its well-formedness.
15778 ///
15779 /// This routine builds a new FieldDecl given the fields name, type,
15780 /// record, etc. \p PrevDecl should refer to any previous declaration
15781 /// with the same name and in the same scope as the field to be
15782 /// created.
15783 ///
15784 /// \returns a new FieldDecl.
15785 ///
15786 /// \todo The Declarator argument is a hack. It will be removed once
15787 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15788                                 TypeSourceInfo *TInfo,
15789                                 RecordDecl *Record, SourceLocation Loc,
15790                                 bool Mutable, Expr *BitWidth,
15791                                 InClassInitStyle InitStyle,
15792                                 SourceLocation TSSL,
15793                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15794                                 Declarator *D) {
15795   IdentifierInfo *II = Name.getAsIdentifierInfo();
15796   bool InvalidDecl = false;
15797   if (D) InvalidDecl = D->isInvalidType();
15798
15799   // If we receive a broken type, recover by assuming 'int' and
15800   // marking this declaration as invalid.
15801   if (T.isNull()) {
15802     InvalidDecl = true;
15803     T = Context.IntTy;
15804   }
15805
15806   QualType EltTy = Context.getBaseElementType(T);
15807   if (!EltTy->isDependentType()) {
15808     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15809       // Fields of incomplete type force their record to be invalid.
15810       Record->setInvalidDecl();
15811       InvalidDecl = true;
15812     } else {
15813       NamedDecl *Def;
15814       EltTy->isIncompleteType(&Def);
15815       if (Def && Def->isInvalidDecl()) {
15816         Record->setInvalidDecl();
15817         InvalidDecl = true;
15818       }
15819     }
15820   }
15821
15822   // TR 18037 does not allow fields to be declared with address space
15823   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15824       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15825     Diag(Loc, diag::err_field_with_address_space);
15826     Record->setInvalidDecl();
15827     InvalidDecl = true;
15828   }
15829
15830   if (LangOpts.OpenCL) {
15831     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15832     // used as structure or union field: image, sampler, event or block types.
15833     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15834         T->isBlockPointerType()) {
15835       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15836       Record->setInvalidDecl();
15837       InvalidDecl = true;
15838     }
15839     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15840     if (BitWidth) {
15841       Diag(Loc, diag::err_opencl_bitfields);
15842       InvalidDecl = true;
15843     }
15844   }
15845
15846   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15847   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15848       T.hasQualifiers()) {
15849     InvalidDecl = true;
15850     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15851   }
15852
15853   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15854   // than a variably modified type.
15855   if (!InvalidDecl && T->isVariablyModifiedType()) {
15856     bool SizeIsNegative;
15857     llvm::APSInt Oversized;
15858
15859     TypeSourceInfo *FixedTInfo =
15860       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15861                                                     SizeIsNegative,
15862                                                     Oversized);
15863     if (FixedTInfo) {
15864       Diag(Loc, diag::warn_illegal_constant_array_size);
15865       TInfo = FixedTInfo;
15866       T = FixedTInfo->getType();
15867     } else {
15868       if (SizeIsNegative)
15869         Diag(Loc, diag::err_typecheck_negative_array_size);
15870       else if (Oversized.getBoolValue())
15871         Diag(Loc, diag::err_array_too_large)
15872           << Oversized.toString(10);
15873       else
15874         Diag(Loc, diag::err_typecheck_field_variable_size);
15875       InvalidDecl = true;
15876     }
15877   }
15878
15879   // Fields can not have abstract class types
15880   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15881                                              diag::err_abstract_type_in_decl,
15882                                              AbstractFieldType))
15883     InvalidDecl = true;
15884
15885   bool ZeroWidth = false;
15886   if (InvalidDecl)
15887     BitWidth = nullptr;
15888   // If this is declared as a bit-field, check the bit-field.
15889   if (BitWidth) {
15890     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15891                               &ZeroWidth).get();
15892     if (!BitWidth) {
15893       InvalidDecl = true;
15894       BitWidth = nullptr;
15895       ZeroWidth = false;
15896     }
15897   }
15898
15899   // Check that 'mutable' is consistent with the type of the declaration.
15900   if (!InvalidDecl && Mutable) {
15901     unsigned DiagID = 0;
15902     if (T->isReferenceType())
15903       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15904                                         : diag::err_mutable_reference;
15905     else if (T.isConstQualified())
15906       DiagID = diag::err_mutable_const;
15907
15908     if (DiagID) {
15909       SourceLocation ErrLoc = Loc;
15910       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15911         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15912       Diag(ErrLoc, DiagID);
15913       if (DiagID != diag::ext_mutable_reference) {
15914         Mutable = false;
15915         InvalidDecl = true;
15916       }
15917     }
15918   }
15919
15920   // C++11 [class.union]p8 (DR1460):
15921   //   At most one variant member of a union may have a
15922   //   brace-or-equal-initializer.
15923   if (InitStyle != ICIS_NoInit)
15924     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15925
15926   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15927                                        BitWidth, Mutable, InitStyle);
15928   if (InvalidDecl)
15929     NewFD->setInvalidDecl();
15930
15931   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15932     Diag(Loc, diag::err_duplicate_member) << II;
15933     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15934     NewFD->setInvalidDecl();
15935   }
15936
15937   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15938     if (Record->isUnion()) {
15939       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15940         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15941         if (RDecl->getDefinition()) {
15942           // C++ [class.union]p1: An object of a class with a non-trivial
15943           // constructor, a non-trivial copy constructor, a non-trivial
15944           // destructor, or a non-trivial copy assignment operator
15945           // cannot be a member of a union, nor can an array of such
15946           // objects.
15947           if (CheckNontrivialField(NewFD))
15948             NewFD->setInvalidDecl();
15949         }
15950       }
15951
15952       // C++ [class.union]p1: If a union contains a member of reference type,
15953       // the program is ill-formed, except when compiling with MSVC extensions
15954       // enabled.
15955       if (EltTy->isReferenceType()) {
15956         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15957                                     diag::ext_union_member_of_reference_type :
15958                                     diag::err_union_member_of_reference_type)
15959           << NewFD->getDeclName() << EltTy;
15960         if (!getLangOpts().MicrosoftExt)
15961           NewFD->setInvalidDecl();
15962       }
15963     }
15964   }
15965
15966   // FIXME: We need to pass in the attributes given an AST
15967   // representation, not a parser representation.
15968   if (D) {
15969     // FIXME: The current scope is almost... but not entirely... correct here.
15970     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15971
15972     if (NewFD->hasAttrs())
15973       CheckAlignasUnderalignment(NewFD);
15974   }
15975
15976   // In auto-retain/release, infer strong retension for fields of
15977   // retainable type.
15978   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15979     NewFD->setInvalidDecl();
15980
15981   if (T.isObjCGCWeak())
15982     Diag(Loc, diag::warn_attribute_weak_on_field);
15983
15984   NewFD->setAccess(AS);
15985   return NewFD;
15986 }
15987
15988 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15989   assert(FD);
15990   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15991
15992   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15993     return false;
15994
15995   QualType EltTy = Context.getBaseElementType(FD->getType());
15996   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15997     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15998     if (RDecl->getDefinition()) {
15999       // We check for copy constructors before constructors
16000       // because otherwise we'll never get complaints about
16001       // copy constructors.
16002
16003       CXXSpecialMember member = CXXInvalid;
16004       // We're required to check for any non-trivial constructors. Since the
16005       // implicit default constructor is suppressed if there are any
16006       // user-declared constructors, we just need to check that there is a
16007       // trivial default constructor and a trivial copy constructor. (We don't
16008       // worry about move constructors here, since this is a C++98 check.)
16009       if (RDecl->hasNonTrivialCopyConstructor())
16010         member = CXXCopyConstructor;
16011       else if (!RDecl->hasTrivialDefaultConstructor())
16012         member = CXXDefaultConstructor;
16013       else if (RDecl->hasNonTrivialCopyAssignment())
16014         member = CXXCopyAssignment;
16015       else if (RDecl->hasNonTrivialDestructor())
16016         member = CXXDestructor;
16017
16018       if (member != CXXInvalid) {
16019         if (!getLangOpts().CPlusPlus11 &&
16020             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16021           // Objective-C++ ARC: it is an error to have a non-trivial field of
16022           // a union. However, system headers in Objective-C programs
16023           // occasionally have Objective-C lifetime objects within unions,
16024           // and rather than cause the program to fail, we make those
16025           // members unavailable.
16026           SourceLocation Loc = FD->getLocation();
16027           if (getSourceManager().isInSystemHeader(Loc)) {
16028             if (!FD->hasAttr<UnavailableAttr>())
16029               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16030                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16031             return false;
16032           }
16033         }
16034
16035         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16036                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16037                diag::err_illegal_union_or_anon_struct_member)
16038           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16039         DiagnoseNontrivial(RDecl, member);
16040         return !getLangOpts().CPlusPlus11;
16041       }
16042     }
16043   }
16044
16045   return false;
16046 }
16047
16048 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16049 ///  AST enum value.
16050 static ObjCIvarDecl::AccessControl
16051 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16052   switch (ivarVisibility) {
16053   default: llvm_unreachable("Unknown visitibility kind");
16054   case tok::objc_private: return ObjCIvarDecl::Private;
16055   case tok::objc_public: return ObjCIvarDecl::Public;
16056   case tok::objc_protected: return ObjCIvarDecl::Protected;
16057   case tok::objc_package: return ObjCIvarDecl::Package;
16058   }
16059 }
16060
16061 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16062 /// in order to create an IvarDecl object for it.
16063 Decl *Sema::ActOnIvar(Scope *S,
16064                                 SourceLocation DeclStart,
16065                                 Declarator &D, Expr *BitfieldWidth,
16066                                 tok::ObjCKeywordKind Visibility) {
16067
16068   IdentifierInfo *II = D.getIdentifier();
16069   Expr *BitWidth = (Expr*)BitfieldWidth;
16070   SourceLocation Loc = DeclStart;
16071   if (II) Loc = D.getIdentifierLoc();
16072
16073   // FIXME: Unnamed fields can be handled in various different ways, for
16074   // example, unnamed unions inject all members into the struct namespace!
16075
16076   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16077   QualType T = TInfo->getType();
16078
16079   if (BitWidth) {
16080     // 6.7.2.1p3, 6.7.2.1p4
16081     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16082     if (!BitWidth)
16083       D.setInvalidType();
16084   } else {
16085     // Not a bitfield.
16086
16087     // validate II.
16088
16089   }
16090   if (T->isReferenceType()) {
16091     Diag(Loc, diag::err_ivar_reference_type);
16092     D.setInvalidType();
16093   }
16094   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16095   // than a variably modified type.
16096   else if (T->isVariablyModifiedType()) {
16097     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16098     D.setInvalidType();
16099   }
16100
16101   // Get the visibility (access control) for this ivar.
16102   ObjCIvarDecl::AccessControl ac =
16103     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16104                                         : ObjCIvarDecl::None;
16105   // Must set ivar's DeclContext to its enclosing interface.
16106   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16107   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16108     return nullptr;
16109   ObjCContainerDecl *EnclosingContext;
16110   if (ObjCImplementationDecl *IMPDecl =
16111       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16112     if (LangOpts.ObjCRuntime.isFragile()) {
16113     // Case of ivar declared in an implementation. Context is that of its class.
16114       EnclosingContext = IMPDecl->getClassInterface();
16115       assert(EnclosingContext && "Implementation has no class interface!");
16116     }
16117     else
16118       EnclosingContext = EnclosingDecl;
16119   } else {
16120     if (ObjCCategoryDecl *CDecl =
16121         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16122       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16123         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16124         return nullptr;
16125       }
16126     }
16127     EnclosingContext = EnclosingDecl;
16128   }
16129
16130   // Construct the decl.
16131   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16132                                              DeclStart, Loc, II, T,
16133                                              TInfo, ac, (Expr *)BitfieldWidth);
16134
16135   if (II) {
16136     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16137                                            ForVisibleRedeclaration);
16138     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16139         && !isa<TagDecl>(PrevDecl)) {
16140       Diag(Loc, diag::err_duplicate_member) << II;
16141       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16142       NewID->setInvalidDecl();
16143     }
16144   }
16145
16146   // Process attributes attached to the ivar.
16147   ProcessDeclAttributes(S, NewID, D);
16148
16149   if (D.isInvalidType())
16150     NewID->setInvalidDecl();
16151
16152   // In ARC, infer 'retaining' for ivars of retainable type.
16153   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16154     NewID->setInvalidDecl();
16155
16156   if (D.getDeclSpec().isModulePrivateSpecified())
16157     NewID->setModulePrivate();
16158
16159   if (II) {
16160     // FIXME: When interfaces are DeclContexts, we'll need to add
16161     // these to the interface.
16162     S->AddDecl(NewID);
16163     IdResolver.AddDecl(NewID);
16164   }
16165
16166   if (LangOpts.ObjCRuntime.isNonFragile() &&
16167       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16168     Diag(Loc, diag::warn_ivars_in_interface);
16169
16170   return NewID;
16171 }
16172
16173 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16174 /// class and class extensions. For every class \@interface and class
16175 /// extension \@interface, if the last ivar is a bitfield of any type,
16176 /// then add an implicit `char :0` ivar to the end of that interface.
16177 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16178                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16179   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16180     return;
16181
16182   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16183   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16184
16185   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16186     return;
16187   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16188   if (!ID) {
16189     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16190       if (!CD->IsClassExtension())
16191         return;
16192     }
16193     // No need to add this to end of @implementation.
16194     else
16195       return;
16196   }
16197   // All conditions are met. Add a new bitfield to the tail end of ivars.
16198   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16199   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16200
16201   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16202                               DeclLoc, DeclLoc, nullptr,
16203                               Context.CharTy,
16204                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16205                                                                DeclLoc),
16206                               ObjCIvarDecl::Private, BW,
16207                               true);
16208   AllIvarDecls.push_back(Ivar);
16209 }
16210
16211 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16212                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16213                        SourceLocation RBrac,
16214                        const ParsedAttributesView &Attrs) {
16215   assert(EnclosingDecl && "missing record or interface decl");
16216
16217   // If this is an Objective-C @implementation or category and we have
16218   // new fields here we should reset the layout of the interface since
16219   // it will now change.
16220   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16221     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16222     switch (DC->getKind()) {
16223     default: break;
16224     case Decl::ObjCCategory:
16225       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16226       break;
16227     case Decl::ObjCImplementation:
16228       Context.
16229         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16230       break;
16231     }
16232   }
16233
16234   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16235   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16236
16237   // Start counting up the number of named members; make sure to include
16238   // members of anonymous structs and unions in the total.
16239   unsigned NumNamedMembers = 0;
16240   if (Record) {
16241     for (const auto *I : Record->decls()) {
16242       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16243         if (IFD->getDeclName())
16244           ++NumNamedMembers;
16245     }
16246   }
16247
16248   // Verify that all the fields are okay.
16249   SmallVector<FieldDecl*, 32> RecFields;
16250
16251   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16252        i != end; ++i) {
16253     FieldDecl *FD = cast<FieldDecl>(*i);
16254
16255     // Get the type for the field.
16256     const Type *FDTy = FD->getType().getTypePtr();
16257
16258     if (!FD->isAnonymousStructOrUnion()) {
16259       // Remember all fields written by the user.
16260       RecFields.push_back(FD);
16261     }
16262
16263     // If the field is already invalid for some reason, don't emit more
16264     // diagnostics about it.
16265     if (FD->isInvalidDecl()) {
16266       EnclosingDecl->setInvalidDecl();
16267       continue;
16268     }
16269
16270     // C99 6.7.2.1p2:
16271     //   A structure or union shall not contain a member with
16272     //   incomplete or function type (hence, a structure shall not
16273     //   contain an instance of itself, but may contain a pointer to
16274     //   an instance of itself), except that the last member of a
16275     //   structure with more than one named member may have incomplete
16276     //   array type; such a structure (and any union containing,
16277     //   possibly recursively, a member that is such a structure)
16278     //   shall not be a member of a structure or an element of an
16279     //   array.
16280     bool IsLastField = (i + 1 == Fields.end());
16281     if (FDTy->isFunctionType()) {
16282       // Field declared as a function.
16283       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16284         << FD->getDeclName();
16285       FD->setInvalidDecl();
16286       EnclosingDecl->setInvalidDecl();
16287       continue;
16288     } else if (FDTy->isIncompleteArrayType() &&
16289                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16290       if (Record) {
16291         // Flexible array member.
16292         // Microsoft and g++ is more permissive regarding flexible array.
16293         // It will accept flexible array in union and also
16294         // as the sole element of a struct/class.
16295         unsigned DiagID = 0;
16296         if (!Record->isUnion() && !IsLastField) {
16297           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16298             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16299           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16300           FD->setInvalidDecl();
16301           EnclosingDecl->setInvalidDecl();
16302           continue;
16303         } else if (Record->isUnion())
16304           DiagID = getLangOpts().MicrosoftExt
16305                        ? diag::ext_flexible_array_union_ms
16306                        : getLangOpts().CPlusPlus
16307                              ? diag::ext_flexible_array_union_gnu
16308                              : diag::err_flexible_array_union;
16309         else if (NumNamedMembers < 1)
16310           DiagID = getLangOpts().MicrosoftExt
16311                        ? diag::ext_flexible_array_empty_aggregate_ms
16312                        : getLangOpts().CPlusPlus
16313                              ? diag::ext_flexible_array_empty_aggregate_gnu
16314                              : diag::err_flexible_array_empty_aggregate;
16315
16316         if (DiagID)
16317           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16318                                           << Record->getTagKind();
16319         // While the layout of types that contain virtual bases is not specified
16320         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16321         // virtual bases after the derived members.  This would make a flexible
16322         // array member declared at the end of an object not adjacent to the end
16323         // of the type.
16324         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16325           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16326               << FD->getDeclName() << Record->getTagKind();
16327         if (!getLangOpts().C99)
16328           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16329             << FD->getDeclName() << Record->getTagKind();
16330
16331         // If the element type has a non-trivial destructor, we would not
16332         // implicitly destroy the elements, so disallow it for now.
16333         //
16334         // FIXME: GCC allows this. We should probably either implicitly delete
16335         // the destructor of the containing class, or just allow this.
16336         QualType BaseElem = Context.getBaseElementType(FD->getType());
16337         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16338           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16339             << FD->getDeclName() << FD->getType();
16340           FD->setInvalidDecl();
16341           EnclosingDecl->setInvalidDecl();
16342           continue;
16343         }
16344         // Okay, we have a legal flexible array member at the end of the struct.
16345         Record->setHasFlexibleArrayMember(true);
16346       } else {
16347         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16348         // unless they are followed by another ivar. That check is done
16349         // elsewhere, after synthesized ivars are known.
16350       }
16351     } else if (!FDTy->isDependentType() &&
16352                RequireCompleteType(FD->getLocation(), FD->getType(),
16353                                    diag::err_field_incomplete)) {
16354       // Incomplete type
16355       FD->setInvalidDecl();
16356       EnclosingDecl->setInvalidDecl();
16357       continue;
16358     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16359       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16360         // A type which contains a flexible array member is considered to be a
16361         // flexible array member.
16362         Record->setHasFlexibleArrayMember(true);
16363         if (!Record->isUnion()) {
16364           // If this is a struct/class and this is not the last element, reject
16365           // it.  Note that GCC supports variable sized arrays in the middle of
16366           // structures.
16367           if (!IsLastField)
16368             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16369               << FD->getDeclName() << FD->getType();
16370           else {
16371             // We support flexible arrays at the end of structs in
16372             // other structs as an extension.
16373             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16374               << FD->getDeclName();
16375           }
16376         }
16377       }
16378       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16379           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16380                                  diag::err_abstract_type_in_decl,
16381                                  AbstractIvarType)) {
16382         // Ivars can not have abstract class types
16383         FD->setInvalidDecl();
16384       }
16385       if (Record && FDTTy->getDecl()->hasObjectMember())
16386         Record->setHasObjectMember(true);
16387       if (Record && FDTTy->getDecl()->hasVolatileMember())
16388         Record->setHasVolatileMember(true);
16389     } else if (FDTy->isObjCObjectType()) {
16390       /// A field cannot be an Objective-c object
16391       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16392         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16393       QualType T = Context.getObjCObjectPointerType(FD->getType());
16394       FD->setType(T);
16395     } else if (getLangOpts().ObjC &&
16396                getLangOpts().getGC() != LangOptions::NonGC &&
16397                Record && !Record->hasObjectMember()) {
16398       if (FD->getType()->isObjCObjectPointerType() ||
16399           FD->getType().isObjCGCStrong())
16400         Record->setHasObjectMember(true);
16401       else if (Context.getAsArrayType(FD->getType())) {
16402         QualType BaseType = Context.getBaseElementType(FD->getType());
16403         if (BaseType->isRecordType() &&
16404             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16405           Record->setHasObjectMember(true);
16406         else if (BaseType->isObjCObjectPointerType() ||
16407                  BaseType.isObjCGCStrong())
16408                Record->setHasObjectMember(true);
16409       }
16410     }
16411
16412     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16413       QualType FT = FD->getType();
16414       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16415         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16416         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16417             Record->isUnion())
16418           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16419       }
16420       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16421       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16422         Record->setNonTrivialToPrimitiveCopy(true);
16423         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16424           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16425       }
16426       if (FT.isDestructedType()) {
16427         Record->setNonTrivialToPrimitiveDestroy(true);
16428         Record->setParamDestroyedInCallee(true);
16429         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16430           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16431       }
16432
16433       if (const auto *RT = FT->getAs<RecordType>()) {
16434         if (RT->getDecl()->getArgPassingRestrictions() ==
16435             RecordDecl::APK_CanNeverPassInRegs)
16436           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16437       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16438         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16439     }
16440
16441     if (Record && FD->getType().isVolatileQualified())
16442       Record->setHasVolatileMember(true);
16443     // Keep track of the number of named members.
16444     if (FD->getIdentifier())
16445       ++NumNamedMembers;
16446   }
16447
16448   // Okay, we successfully defined 'Record'.
16449   if (Record) {
16450     bool Completed = false;
16451     if (CXXRecord) {
16452       if (!CXXRecord->isInvalidDecl()) {
16453         // Set access bits correctly on the directly-declared conversions.
16454         for (CXXRecordDecl::conversion_iterator
16455                I = CXXRecord->conversion_begin(),
16456                E = CXXRecord->conversion_end(); I != E; ++I)
16457           I.setAccess((*I)->getAccess());
16458       }
16459
16460       if (!CXXRecord->isDependentType()) {
16461         // Add any implicitly-declared members to this class.
16462         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16463
16464         if (!CXXRecord->isInvalidDecl()) {
16465           // If we have virtual base classes, we may end up finding multiple
16466           // final overriders for a given virtual function. Check for this
16467           // problem now.
16468           if (CXXRecord->getNumVBases()) {
16469             CXXFinalOverriderMap FinalOverriders;
16470             CXXRecord->getFinalOverriders(FinalOverriders);
16471
16472             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16473                                              MEnd = FinalOverriders.end();
16474                  M != MEnd; ++M) {
16475               for (OverridingMethods::iterator SO = M->second.begin(),
16476                                             SOEnd = M->second.end();
16477                    SO != SOEnd; ++SO) {
16478                 assert(SO->second.size() > 0 &&
16479                        "Virtual function without overriding functions?");
16480                 if (SO->second.size() == 1)
16481                   continue;
16482
16483                 // C++ [class.virtual]p2:
16484                 //   In a derived class, if a virtual member function of a base
16485                 //   class subobject has more than one final overrider the
16486                 //   program is ill-formed.
16487                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16488                   << (const NamedDecl *)M->first << Record;
16489                 Diag(M->first->getLocation(),
16490                      diag::note_overridden_virtual_function);
16491                 for (OverridingMethods::overriding_iterator
16492                           OM = SO->second.begin(),
16493                        OMEnd = SO->second.end();
16494                      OM != OMEnd; ++OM)
16495                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16496                     << (const NamedDecl *)M->first << OM->Method->getParent();
16497
16498                 Record->setInvalidDecl();
16499               }
16500             }
16501             CXXRecord->completeDefinition(&FinalOverriders);
16502             Completed = true;
16503           }
16504         }
16505       }
16506     }
16507
16508     if (!Completed)
16509       Record->completeDefinition();
16510
16511     // Handle attributes before checking the layout.
16512     ProcessDeclAttributeList(S, Record, Attrs);
16513
16514     // We may have deferred checking for a deleted destructor. Check now.
16515     if (CXXRecord) {
16516       auto *Dtor = CXXRecord->getDestructor();
16517       if (Dtor && Dtor->isImplicit() &&
16518           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16519         CXXRecord->setImplicitDestructorIsDeleted();
16520         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16521       }
16522     }
16523
16524     if (Record->hasAttrs()) {
16525       CheckAlignasUnderalignment(Record);
16526
16527       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16528         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16529                                            IA->getRange(), IA->getBestCase(),
16530                                            IA->getSemanticSpelling());
16531     }
16532
16533     // Check if the structure/union declaration is a type that can have zero
16534     // size in C. For C this is a language extension, for C++ it may cause
16535     // compatibility problems.
16536     bool CheckForZeroSize;
16537     if (!getLangOpts().CPlusPlus) {
16538       CheckForZeroSize = true;
16539     } else {
16540       // For C++ filter out types that cannot be referenced in C code.
16541       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16542       CheckForZeroSize =
16543           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16544           !CXXRecord->isDependentType() &&
16545           CXXRecord->isCLike();
16546     }
16547     if (CheckForZeroSize) {
16548       bool ZeroSize = true;
16549       bool IsEmpty = true;
16550       unsigned NonBitFields = 0;
16551       for (RecordDecl::field_iterator I = Record->field_begin(),
16552                                       E = Record->field_end();
16553            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16554         IsEmpty = false;
16555         if (I->isUnnamedBitfield()) {
16556           if (!I->isZeroLengthBitField(Context))
16557             ZeroSize = false;
16558         } else {
16559           ++NonBitFields;
16560           QualType FieldType = I->getType();
16561           if (FieldType->isIncompleteType() ||
16562               !Context.getTypeSizeInChars(FieldType).isZero())
16563             ZeroSize = false;
16564         }
16565       }
16566
16567       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16568       // allowed in C++, but warn if its declaration is inside
16569       // extern "C" block.
16570       if (ZeroSize) {
16571         Diag(RecLoc, getLangOpts().CPlusPlus ?
16572                          diag::warn_zero_size_struct_union_in_extern_c :
16573                          diag::warn_zero_size_struct_union_compat)
16574           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16575       }
16576
16577       // Structs without named members are extension in C (C99 6.7.2.1p7),
16578       // but are accepted by GCC.
16579       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16580         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16581                                diag::ext_no_named_members_in_struct_union)
16582           << Record->isUnion();
16583       }
16584     }
16585   } else {
16586     ObjCIvarDecl **ClsFields =
16587       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16588     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16589       ID->setEndOfDefinitionLoc(RBrac);
16590       // Add ivar's to class's DeclContext.
16591       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16592         ClsFields[i]->setLexicalDeclContext(ID);
16593         ID->addDecl(ClsFields[i]);
16594       }
16595       // Must enforce the rule that ivars in the base classes may not be
16596       // duplicates.
16597       if (ID->getSuperClass())
16598         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16599     } else if (ObjCImplementationDecl *IMPDecl =
16600                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16601       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16602       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16603         // Ivar declared in @implementation never belongs to the implementation.
16604         // Only it is in implementation's lexical context.
16605         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16606       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16607       IMPDecl->setIvarLBraceLoc(LBrac);
16608       IMPDecl->setIvarRBraceLoc(RBrac);
16609     } else if (ObjCCategoryDecl *CDecl =
16610                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16611       // case of ivars in class extension; all other cases have been
16612       // reported as errors elsewhere.
16613       // FIXME. Class extension does not have a LocEnd field.
16614       // CDecl->setLocEnd(RBrac);
16615       // Add ivar's to class extension's DeclContext.
16616       // Diagnose redeclaration of private ivars.
16617       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16618       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16619         if (IDecl) {
16620           if (const ObjCIvarDecl *ClsIvar =
16621               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16622             Diag(ClsFields[i]->getLocation(),
16623                  diag::err_duplicate_ivar_declaration);
16624             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16625             continue;
16626           }
16627           for (const auto *Ext : IDecl->known_extensions()) {
16628             if (const ObjCIvarDecl *ClsExtIvar
16629                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16630               Diag(ClsFields[i]->getLocation(),
16631                    diag::err_duplicate_ivar_declaration);
16632               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16633               continue;
16634             }
16635           }
16636         }
16637         ClsFields[i]->setLexicalDeclContext(CDecl);
16638         CDecl->addDecl(ClsFields[i]);
16639       }
16640       CDecl->setIvarLBraceLoc(LBrac);
16641       CDecl->setIvarRBraceLoc(RBrac);
16642     }
16643   }
16644 }
16645
16646 /// Determine whether the given integral value is representable within
16647 /// the given type T.
16648 static bool isRepresentableIntegerValue(ASTContext &Context,
16649                                         llvm::APSInt &Value,
16650                                         QualType T) {
16651   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16652          "Integral type required!");
16653   unsigned BitWidth = Context.getIntWidth(T);
16654
16655   if (Value.isUnsigned() || Value.isNonNegative()) {
16656     if (T->isSignedIntegerOrEnumerationType())
16657       --BitWidth;
16658     return Value.getActiveBits() <= BitWidth;
16659   }
16660   return Value.getMinSignedBits() <= BitWidth;
16661 }
16662
16663 // Given an integral type, return the next larger integral type
16664 // (or a NULL type of no such type exists).
16665 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16666   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16667   // enum checking below.
16668   assert((T->isIntegralType(Context) ||
16669          T->isEnumeralType()) && "Integral type required!");
16670   const unsigned NumTypes = 4;
16671   QualType SignedIntegralTypes[NumTypes] = {
16672     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16673   };
16674   QualType UnsignedIntegralTypes[NumTypes] = {
16675     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16676     Context.UnsignedLongLongTy
16677   };
16678
16679   unsigned BitWidth = Context.getTypeSize(T);
16680   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16681                                                         : UnsignedIntegralTypes;
16682   for (unsigned I = 0; I != NumTypes; ++I)
16683     if (Context.getTypeSize(Types[I]) > BitWidth)
16684       return Types[I];
16685
16686   return QualType();
16687 }
16688
16689 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16690                                           EnumConstantDecl *LastEnumConst,
16691                                           SourceLocation IdLoc,
16692                                           IdentifierInfo *Id,
16693                                           Expr *Val) {
16694   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16695   llvm::APSInt EnumVal(IntWidth);
16696   QualType EltTy;
16697
16698   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16699     Val = nullptr;
16700
16701   if (Val)
16702     Val = DefaultLvalueConversion(Val).get();
16703
16704   if (Val) {
16705     if (Enum->isDependentType() || Val->isTypeDependent())
16706       EltTy = Context.DependentTy;
16707     else {
16708       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16709           !getLangOpts().MSVCCompat) {
16710         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16711         // constant-expression in the enumerator-definition shall be a converted
16712         // constant expression of the underlying type.
16713         EltTy = Enum->getIntegerType();
16714         ExprResult Converted =
16715           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16716                                            CCEK_Enumerator);
16717         if (Converted.isInvalid())
16718           Val = nullptr;
16719         else
16720           Val = Converted.get();
16721       } else if (!Val->isValueDependent() &&
16722                  !(Val = VerifyIntegerConstantExpression(Val,
16723                                                          &EnumVal).get())) {
16724         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16725       } else {
16726         if (Enum->isComplete()) {
16727           EltTy = Enum->getIntegerType();
16728
16729           // In Obj-C and Microsoft mode, require the enumeration value to be
16730           // representable in the underlying type of the enumeration. In C++11,
16731           // we perform a non-narrowing conversion as part of converted constant
16732           // expression checking.
16733           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16734             if (getLangOpts().MSVCCompat) {
16735               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16736               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16737             } else
16738               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16739           } else
16740             Val = ImpCastExprToType(Val, EltTy,
16741                                     EltTy->isBooleanType() ?
16742                                     CK_IntegralToBoolean : CK_IntegralCast)
16743                     .get();
16744         } else if (getLangOpts().CPlusPlus) {
16745           // C++11 [dcl.enum]p5:
16746           //   If the underlying type is not fixed, the type of each enumerator
16747           //   is the type of its initializing value:
16748           //     - If an initializer is specified for an enumerator, the
16749           //       initializing value has the same type as the expression.
16750           EltTy = Val->getType();
16751         } else {
16752           // C99 6.7.2.2p2:
16753           //   The expression that defines the value of an enumeration constant
16754           //   shall be an integer constant expression that has a value
16755           //   representable as an int.
16756
16757           // Complain if the value is not representable in an int.
16758           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16759             Diag(IdLoc, diag::ext_enum_value_not_int)
16760               << EnumVal.toString(10) << Val->getSourceRange()
16761               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16762           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16763             // Force the type of the expression to 'int'.
16764             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16765           }
16766           EltTy = Val->getType();
16767         }
16768       }
16769     }
16770   }
16771
16772   if (!Val) {
16773     if (Enum->isDependentType())
16774       EltTy = Context.DependentTy;
16775     else if (!LastEnumConst) {
16776       // C++0x [dcl.enum]p5:
16777       //   If the underlying type is not fixed, the type of each enumerator
16778       //   is the type of its initializing value:
16779       //     - If no initializer is specified for the first enumerator, the
16780       //       initializing value has an unspecified integral type.
16781       //
16782       // GCC uses 'int' for its unspecified integral type, as does
16783       // C99 6.7.2.2p3.
16784       if (Enum->isFixed()) {
16785         EltTy = Enum->getIntegerType();
16786       }
16787       else {
16788         EltTy = Context.IntTy;
16789       }
16790     } else {
16791       // Assign the last value + 1.
16792       EnumVal = LastEnumConst->getInitVal();
16793       ++EnumVal;
16794       EltTy = LastEnumConst->getType();
16795
16796       // Check for overflow on increment.
16797       if (EnumVal < LastEnumConst->getInitVal()) {
16798         // C++0x [dcl.enum]p5:
16799         //   If the underlying type is not fixed, the type of each enumerator
16800         //   is the type of its initializing value:
16801         //
16802         //     - Otherwise the type of the initializing value is the same as
16803         //       the type of the initializing value of the preceding enumerator
16804         //       unless the incremented value is not representable in that type,
16805         //       in which case the type is an unspecified integral type
16806         //       sufficient to contain the incremented value. If no such type
16807         //       exists, the program is ill-formed.
16808         QualType T = getNextLargerIntegralType(Context, EltTy);
16809         if (T.isNull() || Enum->isFixed()) {
16810           // There is no integral type larger enough to represent this
16811           // value. Complain, then allow the value to wrap around.
16812           EnumVal = LastEnumConst->getInitVal();
16813           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16814           ++EnumVal;
16815           if (Enum->isFixed())
16816             // When the underlying type is fixed, this is ill-formed.
16817             Diag(IdLoc, diag::err_enumerator_wrapped)
16818               << EnumVal.toString(10)
16819               << EltTy;
16820           else
16821             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16822               << EnumVal.toString(10);
16823         } else {
16824           EltTy = T;
16825         }
16826
16827         // Retrieve the last enumerator's value, extent that type to the
16828         // type that is supposed to be large enough to represent the incremented
16829         // value, then increment.
16830         EnumVal = LastEnumConst->getInitVal();
16831         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16832         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16833         ++EnumVal;
16834
16835         // If we're not in C++, diagnose the overflow of enumerator values,
16836         // which in C99 means that the enumerator value is not representable in
16837         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16838         // permits enumerator values that are representable in some larger
16839         // integral type.
16840         if (!getLangOpts().CPlusPlus && !T.isNull())
16841           Diag(IdLoc, diag::warn_enum_value_overflow);
16842       } else if (!getLangOpts().CPlusPlus &&
16843                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16844         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16845         Diag(IdLoc, diag::ext_enum_value_not_int)
16846           << EnumVal.toString(10) << 1;
16847       }
16848     }
16849   }
16850
16851   if (!EltTy->isDependentType()) {
16852     // Make the enumerator value match the signedness and size of the
16853     // enumerator's type.
16854     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16855     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16856   }
16857
16858   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16859                                   Val, EnumVal);
16860 }
16861
16862 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16863                                                 SourceLocation IILoc) {
16864   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16865       !getLangOpts().CPlusPlus)
16866     return SkipBodyInfo();
16867
16868   // We have an anonymous enum definition. Look up the first enumerator to
16869   // determine if we should merge the definition with an existing one and
16870   // skip the body.
16871   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16872                                          forRedeclarationInCurContext());
16873   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16874   if (!PrevECD)
16875     return SkipBodyInfo();
16876
16877   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16878   NamedDecl *Hidden;
16879   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16880     SkipBodyInfo Skip;
16881     Skip.Previous = Hidden;
16882     return Skip;
16883   }
16884
16885   return SkipBodyInfo();
16886 }
16887
16888 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16889                               SourceLocation IdLoc, IdentifierInfo *Id,
16890                               const ParsedAttributesView &Attrs,
16891                               SourceLocation EqualLoc, Expr *Val) {
16892   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16893   EnumConstantDecl *LastEnumConst =
16894     cast_or_null<EnumConstantDecl>(lastEnumConst);
16895
16896   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16897   // we find one that is.
16898   S = getNonFieldDeclScope(S);
16899
16900   // Verify that there isn't already something declared with this name in this
16901   // scope.
16902   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16903   LookupName(R, S);
16904   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16905
16906   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16907     // Maybe we will complain about the shadowed template parameter.
16908     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16909     // Just pretend that we didn't see the previous declaration.
16910     PrevDecl = nullptr;
16911   }
16912
16913   // C++ [class.mem]p15:
16914   // If T is the name of a class, then each of the following shall have a name
16915   // different from T:
16916   // - every enumerator of every member of class T that is an unscoped
16917   // enumerated type
16918   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16919     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16920                             DeclarationNameInfo(Id, IdLoc));
16921
16922   EnumConstantDecl *New =
16923     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16924   if (!New)
16925     return nullptr;
16926
16927   if (PrevDecl) {
16928     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16929       // Check for other kinds of shadowing not already handled.
16930       CheckShadow(New, PrevDecl, R);
16931     }
16932
16933     // When in C++, we may get a TagDecl with the same name; in this case the
16934     // enum constant will 'hide' the tag.
16935     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16936            "Received TagDecl when not in C++!");
16937     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16938       if (isa<EnumConstantDecl>(PrevDecl))
16939         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16940       else
16941         Diag(IdLoc, diag::err_redefinition) << Id;
16942       notePreviousDefinition(PrevDecl, IdLoc);
16943       return nullptr;
16944     }
16945   }
16946
16947   // Process attributes.
16948   ProcessDeclAttributeList(S, New, Attrs);
16949   AddPragmaAttributes(S, New);
16950
16951   // Register this decl in the current scope stack.
16952   New->setAccess(TheEnumDecl->getAccess());
16953   PushOnScopeChains(New, S);
16954
16955   ActOnDocumentableDecl(New);
16956
16957   return New;
16958 }
16959
16960 // Returns true when the enum initial expression does not trigger the
16961 // duplicate enum warning.  A few common cases are exempted as follows:
16962 // Element2 = Element1
16963 // Element2 = Element1 + 1
16964 // Element2 = Element1 - 1
16965 // Where Element2 and Element1 are from the same enum.
16966 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16967   Expr *InitExpr = ECD->getInitExpr();
16968   if (!InitExpr)
16969     return true;
16970   InitExpr = InitExpr->IgnoreImpCasts();
16971
16972   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16973     if (!BO->isAdditiveOp())
16974       return true;
16975     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16976     if (!IL)
16977       return true;
16978     if (IL->getValue() != 1)
16979       return true;
16980
16981     InitExpr = BO->getLHS();
16982   }
16983
16984   // This checks if the elements are from the same enum.
16985   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16986   if (!DRE)
16987     return true;
16988
16989   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16990   if (!EnumConstant)
16991     return true;
16992
16993   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16994       Enum)
16995     return true;
16996
16997   return false;
16998 }
16999
17000 // Emits a warning when an element is implicitly set a value that
17001 // a previous element has already been set to.
17002 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17003                                         EnumDecl *Enum, QualType EnumType) {
17004   // Avoid anonymous enums
17005   if (!Enum->getIdentifier())
17006     return;
17007
17008   // Only check for small enums.
17009   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17010     return;
17011
17012   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17013     return;
17014
17015   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17016   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17017
17018   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17019   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17020
17021   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17022   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17023     llvm::APSInt Val = D->getInitVal();
17024     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17025   };
17026
17027   DuplicatesVector DupVector;
17028   ValueToVectorMap EnumMap;
17029
17030   // Populate the EnumMap with all values represented by enum constants without
17031   // an initializer.
17032   for (auto *Element : Elements) {
17033     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17034
17035     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17036     // this constant.  Skip this enum since it may be ill-formed.
17037     if (!ECD) {
17038       return;
17039     }
17040
17041     // Constants with initalizers are handled in the next loop.
17042     if (ECD->getInitExpr())
17043       continue;
17044
17045     // Duplicate values are handled in the next loop.
17046     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17047   }
17048
17049   if (EnumMap.size() == 0)
17050     return;
17051
17052   // Create vectors for any values that has duplicates.
17053   for (auto *Element : Elements) {
17054     // The last loop returned if any constant was null.
17055     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17056     if (!ValidDuplicateEnum(ECD, Enum))
17057       continue;
17058
17059     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17060     if (Iter == EnumMap.end())
17061       continue;
17062
17063     DeclOrVector& Entry = Iter->second;
17064     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17065       // Ensure constants are different.
17066       if (D == ECD)
17067         continue;
17068
17069       // Create new vector and push values onto it.
17070       auto Vec = llvm::make_unique<ECDVector>();
17071       Vec->push_back(D);
17072       Vec->push_back(ECD);
17073
17074       // Update entry to point to the duplicates vector.
17075       Entry = Vec.get();
17076
17077       // Store the vector somewhere we can consult later for quick emission of
17078       // diagnostics.
17079       DupVector.emplace_back(std::move(Vec));
17080       continue;
17081     }
17082
17083     ECDVector *Vec = Entry.get<ECDVector*>();
17084     // Make sure constants are not added more than once.
17085     if (*Vec->begin() == ECD)
17086       continue;
17087
17088     Vec->push_back(ECD);
17089   }
17090
17091   // Emit diagnostics.
17092   for (const auto &Vec : DupVector) {
17093     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17094
17095     // Emit warning for one enum constant.
17096     auto *FirstECD = Vec->front();
17097     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17098       << FirstECD << FirstECD->getInitVal().toString(10)
17099       << FirstECD->getSourceRange();
17100
17101     // Emit one note for each of the remaining enum constants with
17102     // the same value.
17103     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17104       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17105         << ECD << ECD->getInitVal().toString(10)
17106         << ECD->getSourceRange();
17107   }
17108 }
17109
17110 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17111                              bool AllowMask) const {
17112   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17113   assert(ED->isCompleteDefinition() && "expected enum definition");
17114
17115   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17116   llvm::APInt &FlagBits = R.first->second;
17117
17118   if (R.second) {
17119     for (auto *E : ED->enumerators()) {
17120       const auto &EVal = E->getInitVal();
17121       // Only single-bit enumerators introduce new flag values.
17122       if (EVal.isPowerOf2())
17123         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17124     }
17125   }
17126
17127   // A value is in a flag enum if either its bits are a subset of the enum's
17128   // flag bits (the first condition) or we are allowing masks and the same is
17129   // true of its complement (the second condition). When masks are allowed, we
17130   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17131   //
17132   // While it's true that any value could be used as a mask, the assumption is
17133   // that a mask will have all of the insignificant bits set. Anything else is
17134   // likely a logic error.
17135   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17136   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17137 }
17138
17139 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17140                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17141                          const ParsedAttributesView &Attrs) {
17142   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17143   QualType EnumType = Context.getTypeDeclType(Enum);
17144
17145   ProcessDeclAttributeList(S, Enum, Attrs);
17146
17147   if (Enum->isDependentType()) {
17148     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17149       EnumConstantDecl *ECD =
17150         cast_or_null<EnumConstantDecl>(Elements[i]);
17151       if (!ECD) continue;
17152
17153       ECD->setType(EnumType);
17154     }
17155
17156     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17157     return;
17158   }
17159
17160   // TODO: If the result value doesn't fit in an int, it must be a long or long
17161   // long value.  ISO C does not support this, but GCC does as an extension,
17162   // emit a warning.
17163   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17164   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17165   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17166
17167   // Verify that all the values are okay, compute the size of the values, and
17168   // reverse the list.
17169   unsigned NumNegativeBits = 0;
17170   unsigned NumPositiveBits = 0;
17171
17172   // Keep track of whether all elements have type int.
17173   bool AllElementsInt = true;
17174
17175   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17176     EnumConstantDecl *ECD =
17177       cast_or_null<EnumConstantDecl>(Elements[i]);
17178     if (!ECD) continue;  // Already issued a diagnostic.
17179
17180     const llvm::APSInt &InitVal = ECD->getInitVal();
17181
17182     // Keep track of the size of positive and negative values.
17183     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17184       NumPositiveBits = std::max(NumPositiveBits,
17185                                  (unsigned)InitVal.getActiveBits());
17186     else
17187       NumNegativeBits = std::max(NumNegativeBits,
17188                                  (unsigned)InitVal.getMinSignedBits());
17189
17190     // Keep track of whether every enum element has type int (very common).
17191     if (AllElementsInt)
17192       AllElementsInt = ECD->getType() == Context.IntTy;
17193   }
17194
17195   // Figure out the type that should be used for this enum.
17196   QualType BestType;
17197   unsigned BestWidth;
17198
17199   // C++0x N3000 [conv.prom]p3:
17200   //   An rvalue of an unscoped enumeration type whose underlying
17201   //   type is not fixed can be converted to an rvalue of the first
17202   //   of the following types that can represent all the values of
17203   //   the enumeration: int, unsigned int, long int, unsigned long
17204   //   int, long long int, or unsigned long long int.
17205   // C99 6.4.4.3p2:
17206   //   An identifier declared as an enumeration constant has type int.
17207   // The C99 rule is modified by a gcc extension
17208   QualType BestPromotionType;
17209
17210   bool Packed = Enum->hasAttr<PackedAttr>();
17211   // -fshort-enums is the equivalent to specifying the packed attribute on all
17212   // enum definitions.
17213   if (LangOpts.ShortEnums)
17214     Packed = true;
17215
17216   // If the enum already has a type because it is fixed or dictated by the
17217   // target, promote that type instead of analyzing the enumerators.
17218   if (Enum->isComplete()) {
17219     BestType = Enum->getIntegerType();
17220     if (BestType->isPromotableIntegerType())
17221       BestPromotionType = Context.getPromotedIntegerType(BestType);
17222     else
17223       BestPromotionType = BestType;
17224
17225     BestWidth = Context.getIntWidth(BestType);
17226   }
17227   else if (NumNegativeBits) {
17228     // If there is a negative value, figure out the smallest integer type (of
17229     // int/long/longlong) that fits.
17230     // If it's packed, check also if it fits a char or a short.
17231     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17232       BestType = Context.SignedCharTy;
17233       BestWidth = CharWidth;
17234     } else if (Packed && NumNegativeBits <= ShortWidth &&
17235                NumPositiveBits < ShortWidth) {
17236       BestType = Context.ShortTy;
17237       BestWidth = ShortWidth;
17238     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17239       BestType = Context.IntTy;
17240       BestWidth = IntWidth;
17241     } else {
17242       BestWidth = Context.getTargetInfo().getLongWidth();
17243
17244       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17245         BestType = Context.LongTy;
17246       } else {
17247         BestWidth = Context.getTargetInfo().getLongLongWidth();
17248
17249         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17250           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17251         BestType = Context.LongLongTy;
17252       }
17253     }
17254     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17255   } else {
17256     // If there is no negative value, figure out the smallest type that fits
17257     // all of the enumerator values.
17258     // If it's packed, check also if it fits a char or a short.
17259     if (Packed && NumPositiveBits <= CharWidth) {
17260       BestType = Context.UnsignedCharTy;
17261       BestPromotionType = Context.IntTy;
17262       BestWidth = CharWidth;
17263     } else if (Packed && NumPositiveBits <= ShortWidth) {
17264       BestType = Context.UnsignedShortTy;
17265       BestPromotionType = Context.IntTy;
17266       BestWidth = ShortWidth;
17267     } else if (NumPositiveBits <= IntWidth) {
17268       BestType = Context.UnsignedIntTy;
17269       BestWidth = IntWidth;
17270       BestPromotionType
17271         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17272                            ? Context.UnsignedIntTy : Context.IntTy;
17273     } else if (NumPositiveBits <=
17274                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17275       BestType = Context.UnsignedLongTy;
17276       BestPromotionType
17277         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17278                            ? Context.UnsignedLongTy : Context.LongTy;
17279     } else {
17280       BestWidth = Context.getTargetInfo().getLongLongWidth();
17281       assert(NumPositiveBits <= BestWidth &&
17282              "How could an initializer get larger than ULL?");
17283       BestType = Context.UnsignedLongLongTy;
17284       BestPromotionType
17285         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17286                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17287     }
17288   }
17289
17290   // Loop over all of the enumerator constants, changing their types to match
17291   // the type of the enum if needed.
17292   for (auto *D : Elements) {
17293     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17294     if (!ECD) continue;  // Already issued a diagnostic.
17295
17296     // Standard C says the enumerators have int type, but we allow, as an
17297     // extension, the enumerators to be larger than int size.  If each
17298     // enumerator value fits in an int, type it as an int, otherwise type it the
17299     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17300     // that X has type 'int', not 'unsigned'.
17301
17302     // Determine whether the value fits into an int.
17303     llvm::APSInt InitVal = ECD->getInitVal();
17304
17305     // If it fits into an integer type, force it.  Otherwise force it to match
17306     // the enum decl type.
17307     QualType NewTy;
17308     unsigned NewWidth;
17309     bool NewSign;
17310     if (!getLangOpts().CPlusPlus &&
17311         !Enum->isFixed() &&
17312         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17313       NewTy = Context.IntTy;
17314       NewWidth = IntWidth;
17315       NewSign = true;
17316     } else if (ECD->getType() == BestType) {
17317       // Already the right type!
17318       if (getLangOpts().CPlusPlus)
17319         // C++ [dcl.enum]p4: Following the closing brace of an
17320         // enum-specifier, each enumerator has the type of its
17321         // enumeration.
17322         ECD->setType(EnumType);
17323       continue;
17324     } else {
17325       NewTy = BestType;
17326       NewWidth = BestWidth;
17327       NewSign = BestType->isSignedIntegerOrEnumerationType();
17328     }
17329
17330     // Adjust the APSInt value.
17331     InitVal = InitVal.extOrTrunc(NewWidth);
17332     InitVal.setIsSigned(NewSign);
17333     ECD->setInitVal(InitVal);
17334
17335     // Adjust the Expr initializer and type.
17336     if (ECD->getInitExpr() &&
17337         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17338       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17339                                                 CK_IntegralCast,
17340                                                 ECD->getInitExpr(),
17341                                                 /*base paths*/ nullptr,
17342                                                 VK_RValue));
17343     if (getLangOpts().CPlusPlus)
17344       // C++ [dcl.enum]p4: Following the closing brace of an
17345       // enum-specifier, each enumerator has the type of its
17346       // enumeration.
17347       ECD->setType(EnumType);
17348     else
17349       ECD->setType(NewTy);
17350   }
17351
17352   Enum->completeDefinition(BestType, BestPromotionType,
17353                            NumPositiveBits, NumNegativeBits);
17354
17355   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17356
17357   if (Enum->isClosedFlag()) {
17358     for (Decl *D : Elements) {
17359       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17360       if (!ECD) continue;  // Already issued a diagnostic.
17361
17362       llvm::APSInt InitVal = ECD->getInitVal();
17363       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17364           !IsValueInFlagEnum(Enum, InitVal, true))
17365         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17366           << ECD << Enum;
17367     }
17368   }
17369
17370   // Now that the enum type is defined, ensure it's not been underaligned.
17371   if (Enum->hasAttrs())
17372     CheckAlignasUnderalignment(Enum);
17373 }
17374
17375 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17376                                   SourceLocation StartLoc,
17377                                   SourceLocation EndLoc) {
17378   StringLiteral *AsmString = cast<StringLiteral>(expr);
17379
17380   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17381                                                    AsmString, StartLoc,
17382                                                    EndLoc);
17383   CurContext->addDecl(New);
17384   return New;
17385 }
17386
17387 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17388                                       IdentifierInfo* AliasName,
17389                                       SourceLocation PragmaLoc,
17390                                       SourceLocation NameLoc,
17391                                       SourceLocation AliasNameLoc) {
17392   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17393                                          LookupOrdinaryName);
17394   AsmLabelAttr *Attr =
17395       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17396
17397   // If a declaration that:
17398   // 1) declares a function or a variable
17399   // 2) has external linkage
17400   // already exists, add a label attribute to it.
17401   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17402     if (isDeclExternC(PrevDecl))
17403       PrevDecl->addAttr(Attr);
17404     else
17405       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17406           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17407   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17408   } else
17409     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17410 }
17411
17412 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17413                              SourceLocation PragmaLoc,
17414                              SourceLocation NameLoc) {
17415   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17416
17417   if (PrevDecl) {
17418     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17419   } else {
17420     (void)WeakUndeclaredIdentifiers.insert(
17421       std::pair<IdentifierInfo*,WeakInfo>
17422         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17423   }
17424 }
17425
17426 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17427                                 IdentifierInfo* AliasName,
17428                                 SourceLocation PragmaLoc,
17429                                 SourceLocation NameLoc,
17430                                 SourceLocation AliasNameLoc) {
17431   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17432                                     LookupOrdinaryName);
17433   WeakInfo W = WeakInfo(Name, NameLoc);
17434
17435   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17436     if (!PrevDecl->hasAttr<AliasAttr>())
17437       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17438         DeclApplyPragmaWeak(TUScope, ND, W);
17439   } else {
17440     (void)WeakUndeclaredIdentifiers.insert(
17441       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17442   }
17443 }
17444
17445 Decl *Sema::getObjCDeclContext() const {
17446   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17447 }