1*67e74705SXin Li //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements semantic analysis for declarations.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
15*67e74705SXin Li #include "TypeLocBuilder.h"
16*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
17*67e74705SXin Li #include "clang/AST/ASTContext.h"
18*67e74705SXin Li #include "clang/AST/ASTLambda.h"
19*67e74705SXin Li #include "clang/AST/CXXInheritance.h"
20*67e74705SXin Li #include "clang/AST/CharUnits.h"
21*67e74705SXin Li #include "clang/AST/CommentDiagnostic.h"
22*67e74705SXin Li #include "clang/AST/DeclCXX.h"
23*67e74705SXin Li #include "clang/AST/DeclObjC.h"
24*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
25*67e74705SXin Li #include "clang/AST/EvaluatedExprVisitor.h"
26*67e74705SXin Li #include "clang/AST/ExprCXX.h"
27*67e74705SXin Li #include "clang/AST/StmtCXX.h"
28*67e74705SXin Li #include "clang/Basic/Builtins.h"
29*67e74705SXin Li #include "clang/Basic/PartialDiagnostic.h"
30*67e74705SXin Li #include "clang/Basic/SourceManager.h"
31*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
32*67e74705SXin Li #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33*67e74705SXin Li #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34*67e74705SXin Li #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35*67e74705SXin Li #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36*67e74705SXin Li #include "clang/Sema/CXXFieldCollector.h"
37*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
38*67e74705SXin Li #include "clang/Sema/DelayedDiagnostic.h"
39*67e74705SXin Li #include "clang/Sema/Initialization.h"
40*67e74705SXin Li #include "clang/Sema/Lookup.h"
41*67e74705SXin Li #include "clang/Sema/ParsedTemplate.h"
42*67e74705SXin Li #include "clang/Sema/Scope.h"
43*67e74705SXin Li #include "clang/Sema/ScopeInfo.h"
44*67e74705SXin Li #include "clang/Sema/Template.h"
45*67e74705SXin Li #include "llvm/ADT/SmallString.h"
46*67e74705SXin Li #include "llvm/ADT/Triple.h"
47*67e74705SXin Li #include <algorithm>
48*67e74705SXin Li #include <cstring>
49*67e74705SXin Li #include <functional>
50*67e74705SXin Li
51*67e74705SXin Li using namespace clang;
52*67e74705SXin Li using namespace sema;
53*67e74705SXin Li
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)54*67e74705SXin Li Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55*67e74705SXin Li if (OwnedType) {
56*67e74705SXin Li Decl *Group[2] = { OwnedType, Ptr };
57*67e74705SXin Li return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58*67e74705SXin Li }
59*67e74705SXin Li
60*67e74705SXin Li return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61*67e74705SXin Li }
62*67e74705SXin Li
63*67e74705SXin Li namespace {
64*67e74705SXin Li
65*67e74705SXin Li class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66*67e74705SXin Li public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false)67*67e74705SXin Li TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68*67e74705SXin Li bool AllowTemplates=false)
69*67e74705SXin Li : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70*67e74705SXin Li AllowClassTemplates(AllowTemplates) {
71*67e74705SXin Li WantExpressionKeywords = false;
72*67e74705SXin Li WantCXXNamedCasts = false;
73*67e74705SXin Li WantRemainingKeywords = false;
74*67e74705SXin Li }
75*67e74705SXin Li
ValidateCandidate(const TypoCorrection & candidate)76*67e74705SXin Li bool ValidateCandidate(const TypoCorrection &candidate) override {
77*67e74705SXin Li if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78*67e74705SXin Li bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79*67e74705SXin Li bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80*67e74705SXin Li return (IsType || AllowedTemplate) &&
81*67e74705SXin Li (AllowInvalidDecl || !ND->isInvalidDecl());
82*67e74705SXin Li }
83*67e74705SXin Li return !WantClassName && candidate.isKeyword();
84*67e74705SXin Li }
85*67e74705SXin Li
86*67e74705SXin Li private:
87*67e74705SXin Li bool AllowInvalidDecl;
88*67e74705SXin Li bool WantClassName;
89*67e74705SXin Li bool AllowClassTemplates;
90*67e74705SXin Li };
91*67e74705SXin Li
92*67e74705SXin Li } // end anonymous namespace
93*67e74705SXin Li
94*67e74705SXin Li /// \brief Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const95*67e74705SXin Li bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96*67e74705SXin Li switch (Kind) {
97*67e74705SXin Li // FIXME: Take into account the current language when deciding whether a
98*67e74705SXin Li // token kind is a valid type specifier
99*67e74705SXin Li case tok::kw_short:
100*67e74705SXin Li case tok::kw_long:
101*67e74705SXin Li case tok::kw___int64:
102*67e74705SXin Li case tok::kw___int128:
103*67e74705SXin Li case tok::kw_signed:
104*67e74705SXin Li case tok::kw_unsigned:
105*67e74705SXin Li case tok::kw_void:
106*67e74705SXin Li case tok::kw_char:
107*67e74705SXin Li case tok::kw_int:
108*67e74705SXin Li case tok::kw_half:
109*67e74705SXin Li case tok::kw_float:
110*67e74705SXin Li case tok::kw_double:
111*67e74705SXin Li case tok::kw___float128:
112*67e74705SXin Li case tok::kw_wchar_t:
113*67e74705SXin Li case tok::kw_bool:
114*67e74705SXin Li case tok::kw___underlying_type:
115*67e74705SXin Li case tok::kw___auto_type:
116*67e74705SXin Li return true;
117*67e74705SXin Li
118*67e74705SXin Li case tok::annot_typename:
119*67e74705SXin Li case tok::kw_char16_t:
120*67e74705SXin Li case tok::kw_char32_t:
121*67e74705SXin Li case tok::kw_typeof:
122*67e74705SXin Li case tok::annot_decltype:
123*67e74705SXin Li case tok::kw_decltype:
124*67e74705SXin Li return getLangOpts().CPlusPlus;
125*67e74705SXin Li
126*67e74705SXin Li default:
127*67e74705SXin Li break;
128*67e74705SXin Li }
129*67e74705SXin Li
130*67e74705SXin Li return false;
131*67e74705SXin Li }
132*67e74705SXin Li
133*67e74705SXin Li namespace {
134*67e74705SXin Li enum class UnqualifiedTypeNameLookupResult {
135*67e74705SXin Li NotFound,
136*67e74705SXin Li FoundNonType,
137*67e74705SXin Li FoundType
138*67e74705SXin Li };
139*67e74705SXin Li } // end anonymous namespace
140*67e74705SXin Li
141*67e74705SXin Li /// \brief Tries to perform unqualified lookup of the type decls in bases for
142*67e74705SXin Li /// dependent class.
143*67e74705SXin Li /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144*67e74705SXin Li /// type decl, \a FoundType if only type decls are found.
145*67e74705SXin Li static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)146*67e74705SXin Li lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147*67e74705SXin Li SourceLocation NameLoc,
148*67e74705SXin Li const CXXRecordDecl *RD) {
149*67e74705SXin Li if (!RD->hasDefinition())
150*67e74705SXin Li return UnqualifiedTypeNameLookupResult::NotFound;
151*67e74705SXin Li // Look for type decls in base classes.
152*67e74705SXin Li UnqualifiedTypeNameLookupResult FoundTypeDecl =
153*67e74705SXin Li UnqualifiedTypeNameLookupResult::NotFound;
154*67e74705SXin Li for (const auto &Base : RD->bases()) {
155*67e74705SXin Li const CXXRecordDecl *BaseRD = nullptr;
156*67e74705SXin Li if (auto *BaseTT = Base.getType()->getAs<TagType>())
157*67e74705SXin Li BaseRD = BaseTT->getAsCXXRecordDecl();
158*67e74705SXin Li else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159*67e74705SXin Li // Look for type decls in dependent base classes that have known primary
160*67e74705SXin Li // templates.
161*67e74705SXin Li if (!TST || !TST->isDependentType())
162*67e74705SXin Li continue;
163*67e74705SXin Li auto *TD = TST->getTemplateName().getAsTemplateDecl();
164*67e74705SXin Li if (!TD)
165*67e74705SXin Li continue;
166*67e74705SXin Li if (auto *BasePrimaryTemplate =
167*67e74705SXin Li dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168*67e74705SXin Li if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169*67e74705SXin Li BaseRD = BasePrimaryTemplate;
170*67e74705SXin Li else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171*67e74705SXin Li if (const ClassTemplatePartialSpecializationDecl *PS =
172*67e74705SXin Li CTD->findPartialSpecialization(Base.getType()))
173*67e74705SXin Li if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174*67e74705SXin Li BaseRD = PS;
175*67e74705SXin Li }
176*67e74705SXin Li }
177*67e74705SXin Li }
178*67e74705SXin Li if (BaseRD) {
179*67e74705SXin Li for (NamedDecl *ND : BaseRD->lookup(&II)) {
180*67e74705SXin Li if (!isa<TypeDecl>(ND))
181*67e74705SXin Li return UnqualifiedTypeNameLookupResult::FoundNonType;
182*67e74705SXin Li FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183*67e74705SXin Li }
184*67e74705SXin Li if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185*67e74705SXin Li switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186*67e74705SXin Li case UnqualifiedTypeNameLookupResult::FoundNonType:
187*67e74705SXin Li return UnqualifiedTypeNameLookupResult::FoundNonType;
188*67e74705SXin Li case UnqualifiedTypeNameLookupResult::FoundType:
189*67e74705SXin Li FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190*67e74705SXin Li break;
191*67e74705SXin Li case UnqualifiedTypeNameLookupResult::NotFound:
192*67e74705SXin Li break;
193*67e74705SXin Li }
194*67e74705SXin Li }
195*67e74705SXin Li }
196*67e74705SXin Li }
197*67e74705SXin Li
198*67e74705SXin Li return FoundTypeDecl;
199*67e74705SXin Li }
200*67e74705SXin Li
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)201*67e74705SXin Li static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202*67e74705SXin Li const IdentifierInfo &II,
203*67e74705SXin Li SourceLocation NameLoc) {
204*67e74705SXin Li // Lookup in the parent class template context, if any.
205*67e74705SXin Li const CXXRecordDecl *RD = nullptr;
206*67e74705SXin Li UnqualifiedTypeNameLookupResult FoundTypeDecl =
207*67e74705SXin Li UnqualifiedTypeNameLookupResult::NotFound;
208*67e74705SXin Li for (DeclContext *DC = S.CurContext;
209*67e74705SXin Li DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210*67e74705SXin Li DC = DC->getParent()) {
211*67e74705SXin Li // Look for type decls in dependent base classes that have known primary
212*67e74705SXin Li // templates.
213*67e74705SXin Li RD = dyn_cast<CXXRecordDecl>(DC);
214*67e74705SXin Li if (RD && RD->getDescribedClassTemplate())
215*67e74705SXin Li FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216*67e74705SXin Li }
217*67e74705SXin Li if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218*67e74705SXin Li return nullptr;
219*67e74705SXin Li
220*67e74705SXin Li // We found some types in dependent base classes. Recover as if the user
221*67e74705SXin Li // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
222*67e74705SXin Li // lookup during template instantiation.
223*67e74705SXin Li S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224*67e74705SXin Li
225*67e74705SXin Li ASTContext &Context = S.Context;
226*67e74705SXin Li auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227*67e74705SXin Li cast<Type>(Context.getRecordType(RD)));
228*67e74705SXin Li QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229*67e74705SXin Li
230*67e74705SXin Li CXXScopeSpec SS;
231*67e74705SXin Li SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232*67e74705SXin Li
233*67e74705SXin Li TypeLocBuilder Builder;
234*67e74705SXin Li DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235*67e74705SXin Li DepTL.setNameLoc(NameLoc);
236*67e74705SXin Li DepTL.setElaboratedKeywordLoc(SourceLocation());
237*67e74705SXin Li DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238*67e74705SXin Li return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239*67e74705SXin Li }
240*67e74705SXin Li
241*67e74705SXin Li /// \brief If the identifier refers to a type name within this scope,
242*67e74705SXin Li /// return the declaration of that type.
243*67e74705SXin Li ///
244*67e74705SXin Li /// This routine performs ordinary name lookup of the identifier II
245*67e74705SXin Li /// within the given scope, with optional C++ scope specifier SS, to
246*67e74705SXin Li /// determine whether the name refers to a type. If so, returns an
247*67e74705SXin Li /// opaque pointer (actually a QualType) corresponding to that
248*67e74705SXin Li /// type. Otherwise, returns NULL.
getTypeName(const IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec * SS,bool isClassName,bool HasTrailingDot,ParsedType ObjectTypePtr,bool IsCtorOrDtorName,bool WantNontrivialTypeSourceInfo,IdentifierInfo ** CorrectedII)249*67e74705SXin Li ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250*67e74705SXin Li Scope *S, CXXScopeSpec *SS,
251*67e74705SXin Li bool isClassName, bool HasTrailingDot,
252*67e74705SXin Li ParsedType ObjectTypePtr,
253*67e74705SXin Li bool IsCtorOrDtorName,
254*67e74705SXin Li bool WantNontrivialTypeSourceInfo,
255*67e74705SXin Li IdentifierInfo **CorrectedII) {
256*67e74705SXin Li // Determine where we will perform name lookup.
257*67e74705SXin Li DeclContext *LookupCtx = nullptr;
258*67e74705SXin Li if (ObjectTypePtr) {
259*67e74705SXin Li QualType ObjectType = ObjectTypePtr.get();
260*67e74705SXin Li if (ObjectType->isRecordType())
261*67e74705SXin Li LookupCtx = computeDeclContext(ObjectType);
262*67e74705SXin Li } else if (SS && SS->isNotEmpty()) {
263*67e74705SXin Li LookupCtx = computeDeclContext(*SS, false);
264*67e74705SXin Li
265*67e74705SXin Li if (!LookupCtx) {
266*67e74705SXin Li if (isDependentScopeSpecifier(*SS)) {
267*67e74705SXin Li // C++ [temp.res]p3:
268*67e74705SXin Li // A qualified-id that refers to a type and in which the
269*67e74705SXin Li // nested-name-specifier depends on a template-parameter (14.6.2)
270*67e74705SXin Li // shall be prefixed by the keyword typename to indicate that the
271*67e74705SXin Li // qualified-id denotes a type, forming an
272*67e74705SXin Li // elaborated-type-specifier (7.1.5.3).
273*67e74705SXin Li //
274*67e74705SXin Li // We therefore do not perform any name lookup if the result would
275*67e74705SXin Li // refer to a member of an unknown specialization.
276*67e74705SXin Li if (!isClassName && !IsCtorOrDtorName)
277*67e74705SXin Li return nullptr;
278*67e74705SXin Li
279*67e74705SXin Li // We know from the grammar that this name refers to a type,
280*67e74705SXin Li // so build a dependent node to describe the type.
281*67e74705SXin Li if (WantNontrivialTypeSourceInfo)
282*67e74705SXin Li return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283*67e74705SXin Li
284*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285*67e74705SXin Li QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286*67e74705SXin Li II, NameLoc);
287*67e74705SXin Li return ParsedType::make(T);
288*67e74705SXin Li }
289*67e74705SXin Li
290*67e74705SXin Li return nullptr;
291*67e74705SXin Li }
292*67e74705SXin Li
293*67e74705SXin Li if (!LookupCtx->isDependentContext() &&
294*67e74705SXin Li RequireCompleteDeclContext(*SS, LookupCtx))
295*67e74705SXin Li return nullptr;
296*67e74705SXin Li }
297*67e74705SXin Li
298*67e74705SXin Li // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299*67e74705SXin Li // lookup for class-names.
300*67e74705SXin Li LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301*67e74705SXin Li LookupOrdinaryName;
302*67e74705SXin Li LookupResult Result(*this, &II, NameLoc, Kind);
303*67e74705SXin Li if (LookupCtx) {
304*67e74705SXin Li // Perform "qualified" name lookup into the declaration context we
305*67e74705SXin Li // computed, which is either the type of the base of a member access
306*67e74705SXin Li // expression or the declaration context associated with a prior
307*67e74705SXin Li // nested-name-specifier.
308*67e74705SXin Li LookupQualifiedName(Result, LookupCtx);
309*67e74705SXin Li
310*67e74705SXin Li if (ObjectTypePtr && Result.empty()) {
311*67e74705SXin Li // C++ [basic.lookup.classref]p3:
312*67e74705SXin Li // If the unqualified-id is ~type-name, the type-name is looked up
313*67e74705SXin Li // in the context of the entire postfix-expression. If the type T of
314*67e74705SXin Li // the object expression is of a class type C, the type-name is also
315*67e74705SXin Li // looked up in the scope of class C. At least one of the lookups shall
316*67e74705SXin Li // find a name that refers to (possibly cv-qualified) T.
317*67e74705SXin Li LookupName(Result, S);
318*67e74705SXin Li }
319*67e74705SXin Li } else {
320*67e74705SXin Li // Perform unqualified name lookup.
321*67e74705SXin Li LookupName(Result, S);
322*67e74705SXin Li
323*67e74705SXin Li // For unqualified lookup in a class template in MSVC mode, look into
324*67e74705SXin Li // dependent base classes where the primary class template is known.
325*67e74705SXin Li if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326*67e74705SXin Li if (ParsedType TypeInBase =
327*67e74705SXin Li recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328*67e74705SXin Li return TypeInBase;
329*67e74705SXin Li }
330*67e74705SXin Li }
331*67e74705SXin Li
332*67e74705SXin Li NamedDecl *IIDecl = nullptr;
333*67e74705SXin Li switch (Result.getResultKind()) {
334*67e74705SXin Li case LookupResult::NotFound:
335*67e74705SXin Li case LookupResult::NotFoundInCurrentInstantiation:
336*67e74705SXin Li if (CorrectedII) {
337*67e74705SXin Li TypoCorrection Correction = CorrectTypo(
338*67e74705SXin Li Result.getLookupNameInfo(), Kind, S, SS,
339*67e74705SXin Li llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340*67e74705SXin Li CTK_ErrorRecovery);
341*67e74705SXin Li IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342*67e74705SXin Li TemplateTy Template;
343*67e74705SXin Li bool MemberOfUnknownSpecialization;
344*67e74705SXin Li UnqualifiedId TemplateName;
345*67e74705SXin Li TemplateName.setIdentifier(NewII, NameLoc);
346*67e74705SXin Li NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347*67e74705SXin Li CXXScopeSpec NewSS, *NewSSPtr = SS;
348*67e74705SXin Li if (SS && NNS) {
349*67e74705SXin Li NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350*67e74705SXin Li NewSSPtr = &NewSS;
351*67e74705SXin Li }
352*67e74705SXin Li if (Correction && (NNS || NewII != &II) &&
353*67e74705SXin Li // Ignore a correction to a template type as the to-be-corrected
354*67e74705SXin Li // identifier is not a template (typo correction for template names
355*67e74705SXin Li // is handled elsewhere).
356*67e74705SXin Li !(getLangOpts().CPlusPlus && NewSSPtr &&
357*67e74705SXin Li isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358*67e74705SXin Li Template, MemberOfUnknownSpecialization))) {
359*67e74705SXin Li ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360*67e74705SXin Li isClassName, HasTrailingDot, ObjectTypePtr,
361*67e74705SXin Li IsCtorOrDtorName,
362*67e74705SXin Li WantNontrivialTypeSourceInfo);
363*67e74705SXin Li if (Ty) {
364*67e74705SXin Li diagnoseTypo(Correction,
365*67e74705SXin Li PDiag(diag::err_unknown_type_or_class_name_suggest)
366*67e74705SXin Li << Result.getLookupName() << isClassName);
367*67e74705SXin Li if (SS && NNS)
368*67e74705SXin Li SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369*67e74705SXin Li *CorrectedII = NewII;
370*67e74705SXin Li return Ty;
371*67e74705SXin Li }
372*67e74705SXin Li }
373*67e74705SXin Li }
374*67e74705SXin Li // If typo correction failed or was not performed, fall through
375*67e74705SXin Li case LookupResult::FoundOverloaded:
376*67e74705SXin Li case LookupResult::FoundUnresolvedValue:
377*67e74705SXin Li Result.suppressDiagnostics();
378*67e74705SXin Li return nullptr;
379*67e74705SXin Li
380*67e74705SXin Li case LookupResult::Ambiguous:
381*67e74705SXin Li // Recover from type-hiding ambiguities by hiding the type. We'll
382*67e74705SXin Li // do the lookup again when looking for an object, and we can
383*67e74705SXin Li // diagnose the error then. If we don't do this, then the error
384*67e74705SXin Li // about hiding the type will be immediately followed by an error
385*67e74705SXin Li // that only makes sense if the identifier was treated like a type.
386*67e74705SXin Li if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387*67e74705SXin Li Result.suppressDiagnostics();
388*67e74705SXin Li return nullptr;
389*67e74705SXin Li }
390*67e74705SXin Li
391*67e74705SXin Li // Look to see if we have a type anywhere in the list of results.
392*67e74705SXin Li for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393*67e74705SXin Li Res != ResEnd; ++Res) {
394*67e74705SXin Li if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395*67e74705SXin Li if (!IIDecl ||
396*67e74705SXin Li (*Res)->getLocation().getRawEncoding() <
397*67e74705SXin Li IIDecl->getLocation().getRawEncoding())
398*67e74705SXin Li IIDecl = *Res;
399*67e74705SXin Li }
400*67e74705SXin Li }
401*67e74705SXin Li
402*67e74705SXin Li if (!IIDecl) {
403*67e74705SXin Li // None of the entities we found is a type, so there is no way
404*67e74705SXin Li // to even assume that the result is a type. In this case, don't
405*67e74705SXin Li // complain about the ambiguity. The parser will either try to
406*67e74705SXin Li // perform this lookup again (e.g., as an object name), which
407*67e74705SXin Li // will produce the ambiguity, or will complain that it expected
408*67e74705SXin Li // a type name.
409*67e74705SXin Li Result.suppressDiagnostics();
410*67e74705SXin Li return nullptr;
411*67e74705SXin Li }
412*67e74705SXin Li
413*67e74705SXin Li // We found a type within the ambiguous lookup; diagnose the
414*67e74705SXin Li // ambiguity and then return that type. This might be the right
415*67e74705SXin Li // answer, or it might not be, but it suppresses any attempt to
416*67e74705SXin Li // perform the name lookup again.
417*67e74705SXin Li break;
418*67e74705SXin Li
419*67e74705SXin Li case LookupResult::Found:
420*67e74705SXin Li IIDecl = Result.getFoundDecl();
421*67e74705SXin Li break;
422*67e74705SXin Li }
423*67e74705SXin Li
424*67e74705SXin Li assert(IIDecl && "Didn't find decl");
425*67e74705SXin Li
426*67e74705SXin Li QualType T;
427*67e74705SXin Li if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428*67e74705SXin Li DiagnoseUseOfDecl(IIDecl, NameLoc);
429*67e74705SXin Li
430*67e74705SXin Li T = Context.getTypeDeclType(TD);
431*67e74705SXin Li MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432*67e74705SXin Li
433*67e74705SXin Li // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434*67e74705SXin Li // constructor or destructor name (in such a case, the scope specifier
435*67e74705SXin Li // will be attached to the enclosing Expr or Decl node).
436*67e74705SXin Li if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437*67e74705SXin Li if (WantNontrivialTypeSourceInfo) {
438*67e74705SXin Li // Construct a type with type-source information.
439*67e74705SXin Li TypeLocBuilder Builder;
440*67e74705SXin Li Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441*67e74705SXin Li
442*67e74705SXin Li T = getElaboratedType(ETK_None, *SS, T);
443*67e74705SXin Li ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444*67e74705SXin Li ElabTL.setElaboratedKeywordLoc(SourceLocation());
445*67e74705SXin Li ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446*67e74705SXin Li return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447*67e74705SXin Li } else {
448*67e74705SXin Li T = getElaboratedType(ETK_None, *SS, T);
449*67e74705SXin Li }
450*67e74705SXin Li }
451*67e74705SXin Li } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452*67e74705SXin Li (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453*67e74705SXin Li if (!HasTrailingDot)
454*67e74705SXin Li T = Context.getObjCInterfaceType(IDecl);
455*67e74705SXin Li }
456*67e74705SXin Li
457*67e74705SXin Li if (T.isNull()) {
458*67e74705SXin Li // If it's not plausibly a type, suppress diagnostics.
459*67e74705SXin Li Result.suppressDiagnostics();
460*67e74705SXin Li return nullptr;
461*67e74705SXin Li }
462*67e74705SXin Li return ParsedType::make(T);
463*67e74705SXin Li }
464*67e74705SXin Li
465*67e74705SXin Li // Builds a fake NNS for the given decl context.
466*67e74705SXin Li static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)467*67e74705SXin Li synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468*67e74705SXin Li for (;; DC = DC->getLookupParent()) {
469*67e74705SXin Li DC = DC->getPrimaryContext();
470*67e74705SXin Li auto *ND = dyn_cast<NamespaceDecl>(DC);
471*67e74705SXin Li if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472*67e74705SXin Li return NestedNameSpecifier::Create(Context, nullptr, ND);
473*67e74705SXin Li else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474*67e74705SXin Li return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475*67e74705SXin Li RD->getTypeForDecl());
476*67e74705SXin Li else if (isa<TranslationUnitDecl>(DC))
477*67e74705SXin Li return NestedNameSpecifier::GlobalSpecifier(Context);
478*67e74705SXin Li }
479*67e74705SXin Li llvm_unreachable("something isn't in TU scope?");
480*67e74705SXin Li }
481*67e74705SXin Li
482*67e74705SXin Li /// Find the parent class with dependent bases of the innermost enclosing method
483*67e74705SXin Li /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484*67e74705SXin Li /// up allowing unqualified dependent type names at class-level, which MSVC
485*67e74705SXin Li /// correctly rejects.
486*67e74705SXin Li static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)487*67e74705SXin Li findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488*67e74705SXin Li for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489*67e74705SXin Li DC = DC->getPrimaryContext();
490*67e74705SXin Li if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491*67e74705SXin Li if (MD->getParent()->hasAnyDependentBases())
492*67e74705SXin Li return MD->getParent();
493*67e74705SXin Li }
494*67e74705SXin Li return nullptr;
495*67e74705SXin Li }
496*67e74705SXin Li
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)497*67e74705SXin Li ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498*67e74705SXin Li SourceLocation NameLoc,
499*67e74705SXin Li bool IsTemplateTypeArg) {
500*67e74705SXin Li assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501*67e74705SXin Li
502*67e74705SXin Li NestedNameSpecifier *NNS = nullptr;
503*67e74705SXin Li if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504*67e74705SXin Li // If we weren't able to parse a default template argument, delay lookup
505*67e74705SXin Li // until instantiation time by making a non-dependent DependentTypeName. We
506*67e74705SXin Li // pretend we saw a NestedNameSpecifier referring to the current scope, and
507*67e74705SXin Li // lookup is retried.
508*67e74705SXin Li // FIXME: This hurts our diagnostic quality, since we get errors like "no
509*67e74705SXin Li // type named 'Foo' in 'current_namespace'" when the user didn't write any
510*67e74705SXin Li // name specifiers.
511*67e74705SXin Li NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512*67e74705SXin Li Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513*67e74705SXin Li } else if (const CXXRecordDecl *RD =
514*67e74705SXin Li findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515*67e74705SXin Li // Build a DependentNameType that will perform lookup into RD at
516*67e74705SXin Li // instantiation time.
517*67e74705SXin Li NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518*67e74705SXin Li RD->getTypeForDecl());
519*67e74705SXin Li
520*67e74705SXin Li // Diagnose that this identifier was undeclared, and retry the lookup during
521*67e74705SXin Li // template instantiation.
522*67e74705SXin Li Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523*67e74705SXin Li << RD;
524*67e74705SXin Li } else {
525*67e74705SXin Li // This is not a situation that we should recover from.
526*67e74705SXin Li return ParsedType();
527*67e74705SXin Li }
528*67e74705SXin Li
529*67e74705SXin Li QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530*67e74705SXin Li
531*67e74705SXin Li // Build type location information. We synthesized the qualifier, so we have
532*67e74705SXin Li // to build a fake NestedNameSpecifierLoc.
533*67e74705SXin Li NestedNameSpecifierLocBuilder NNSLocBuilder;
534*67e74705SXin Li NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536*67e74705SXin Li
537*67e74705SXin Li TypeLocBuilder Builder;
538*67e74705SXin Li DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539*67e74705SXin Li DepTL.setNameLoc(NameLoc);
540*67e74705SXin Li DepTL.setElaboratedKeywordLoc(SourceLocation());
541*67e74705SXin Li DepTL.setQualifierLoc(QualifierLoc);
542*67e74705SXin Li return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543*67e74705SXin Li }
544*67e74705SXin Li
545*67e74705SXin Li /// isTagName() - This method is called *for error recovery purposes only*
546*67e74705SXin Li /// to determine if the specified name is a valid tag name ("struct foo"). If
547*67e74705SXin Li /// so, this returns the TST for the tag corresponding to it (TST_enum,
548*67e74705SXin Li /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
549*67e74705SXin Li /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)550*67e74705SXin Li DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551*67e74705SXin Li // Do a tag name lookup in this scope.
552*67e74705SXin Li LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553*67e74705SXin Li LookupName(R, S, false);
554*67e74705SXin Li R.suppressDiagnostics();
555*67e74705SXin Li if (R.getResultKind() == LookupResult::Found)
556*67e74705SXin Li if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557*67e74705SXin Li switch (TD->getTagKind()) {
558*67e74705SXin Li case TTK_Struct: return DeclSpec::TST_struct;
559*67e74705SXin Li case TTK_Interface: return DeclSpec::TST_interface;
560*67e74705SXin Li case TTK_Union: return DeclSpec::TST_union;
561*67e74705SXin Li case TTK_Class: return DeclSpec::TST_class;
562*67e74705SXin Li case TTK_Enum: return DeclSpec::TST_enum;
563*67e74705SXin Li }
564*67e74705SXin Li }
565*67e74705SXin Li
566*67e74705SXin Li return DeclSpec::TST_unspecified;
567*67e74705SXin Li }
568*67e74705SXin Li
569*67e74705SXin Li /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570*67e74705SXin Li /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571*67e74705SXin Li /// then downgrade the missing typename error to a warning.
572*67e74705SXin Li /// This is needed for MSVC compatibility; Example:
573*67e74705SXin Li /// @code
574*67e74705SXin Li /// template<class T> class A {
575*67e74705SXin Li /// public:
576*67e74705SXin Li /// typedef int TYPE;
577*67e74705SXin Li /// };
578*67e74705SXin Li /// template<class T> class B : public A<T> {
579*67e74705SXin Li /// public:
580*67e74705SXin Li /// A<T>::TYPE a; // no typename required because A<T> is a base class.
581*67e74705SXin Li /// };
582*67e74705SXin Li /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)583*67e74705SXin Li bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584*67e74705SXin Li if (CurContext->isRecord()) {
585*67e74705SXin Li if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586*67e74705SXin Li return true;
587*67e74705SXin Li
588*67e74705SXin Li const Type *Ty = SS->getScopeRep()->getAsType();
589*67e74705SXin Li
590*67e74705SXin Li CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591*67e74705SXin Li for (const auto &Base : RD->bases())
592*67e74705SXin Li if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593*67e74705SXin Li return true;
594*67e74705SXin Li return S->isFunctionPrototypeScope();
595*67e74705SXin Li }
596*67e74705SXin Li return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597*67e74705SXin Li }
598*67e74705SXin Li
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool AllowClassTemplates)599*67e74705SXin Li void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600*67e74705SXin Li SourceLocation IILoc,
601*67e74705SXin Li Scope *S,
602*67e74705SXin Li CXXScopeSpec *SS,
603*67e74705SXin Li ParsedType &SuggestedType,
604*67e74705SXin Li bool AllowClassTemplates) {
605*67e74705SXin Li // We don't have anything to suggest (yet).
606*67e74705SXin Li SuggestedType = nullptr;
607*67e74705SXin Li
608*67e74705SXin Li // There may have been a typo in the name of the type. Look up typo
609*67e74705SXin Li // results, in case we have something that we can suggest.
610*67e74705SXin Li if (TypoCorrection Corrected =
611*67e74705SXin Li CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612*67e74705SXin Li llvm::make_unique<TypeNameValidatorCCC>(
613*67e74705SXin Li false, false, AllowClassTemplates),
614*67e74705SXin Li CTK_ErrorRecovery)) {
615*67e74705SXin Li if (Corrected.isKeyword()) {
616*67e74705SXin Li // We corrected to a keyword.
617*67e74705SXin Li diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618*67e74705SXin Li II = Corrected.getCorrectionAsIdentifierInfo();
619*67e74705SXin Li } else {
620*67e74705SXin Li // We found a similarly-named type or interface; suggest that.
621*67e74705SXin Li if (!SS || !SS->isSet()) {
622*67e74705SXin Li diagnoseTypo(Corrected,
623*67e74705SXin Li PDiag(diag::err_unknown_typename_suggest) << II);
624*67e74705SXin Li } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625*67e74705SXin Li std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626*67e74705SXin Li bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627*67e74705SXin Li II->getName().equals(CorrectedStr);
628*67e74705SXin Li diagnoseTypo(Corrected,
629*67e74705SXin Li PDiag(diag::err_unknown_nested_typename_suggest)
630*67e74705SXin Li << II << DC << DroppedSpecifier << SS->getRange());
631*67e74705SXin Li } else {
632*67e74705SXin Li llvm_unreachable("could not have corrected a typo here");
633*67e74705SXin Li }
634*67e74705SXin Li
635*67e74705SXin Li CXXScopeSpec tmpSS;
636*67e74705SXin Li if (Corrected.getCorrectionSpecifier())
637*67e74705SXin Li tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638*67e74705SXin Li SourceRange(IILoc));
639*67e74705SXin Li SuggestedType =
640*67e74705SXin Li getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641*67e74705SXin Li tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642*67e74705SXin Li /*IsCtorOrDtorName=*/false,
643*67e74705SXin Li /*NonTrivialTypeSourceInfo=*/true);
644*67e74705SXin Li }
645*67e74705SXin Li return;
646*67e74705SXin Li }
647*67e74705SXin Li
648*67e74705SXin Li if (getLangOpts().CPlusPlus) {
649*67e74705SXin Li // See if II is a class template that the user forgot to pass arguments to.
650*67e74705SXin Li UnqualifiedId Name;
651*67e74705SXin Li Name.setIdentifier(II, IILoc);
652*67e74705SXin Li CXXScopeSpec EmptySS;
653*67e74705SXin Li TemplateTy TemplateResult;
654*67e74705SXin Li bool MemberOfUnknownSpecialization;
655*67e74705SXin Li if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656*67e74705SXin Li Name, nullptr, true, TemplateResult,
657*67e74705SXin Li MemberOfUnknownSpecialization) == TNK_Type_template) {
658*67e74705SXin Li TemplateName TplName = TemplateResult.get();
659*67e74705SXin Li Diag(IILoc, diag::err_template_missing_args) << TplName;
660*67e74705SXin Li if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661*67e74705SXin Li Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662*67e74705SXin Li << TplDecl->getTemplateParameters()->getSourceRange();
663*67e74705SXin Li }
664*67e74705SXin Li return;
665*67e74705SXin Li }
666*67e74705SXin Li }
667*67e74705SXin Li
668*67e74705SXin Li // FIXME: Should we move the logic that tries to recover from a missing tag
669*67e74705SXin Li // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670*67e74705SXin Li
671*67e74705SXin Li if (!SS || (!SS->isSet() && !SS->isInvalid()))
672*67e74705SXin Li Diag(IILoc, diag::err_unknown_typename) << II;
673*67e74705SXin Li else if (DeclContext *DC = computeDeclContext(*SS, false))
674*67e74705SXin Li Diag(IILoc, diag::err_typename_nested_not_found)
675*67e74705SXin Li << II << DC << SS->getRange();
676*67e74705SXin Li else if (isDependentScopeSpecifier(*SS)) {
677*67e74705SXin Li unsigned DiagID = diag::err_typename_missing;
678*67e74705SXin Li if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679*67e74705SXin Li DiagID = diag::ext_typename_missing;
680*67e74705SXin Li
681*67e74705SXin Li Diag(SS->getRange().getBegin(), DiagID)
682*67e74705SXin Li << SS->getScopeRep() << II->getName()
683*67e74705SXin Li << SourceRange(SS->getRange().getBegin(), IILoc)
684*67e74705SXin Li << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685*67e74705SXin Li SuggestedType = ActOnTypenameType(S, SourceLocation(),
686*67e74705SXin Li *SS, *II, IILoc).get();
687*67e74705SXin Li } else {
688*67e74705SXin Li assert(SS && SS->isInvalid() &&
689*67e74705SXin Li "Invalid scope specifier has already been diagnosed");
690*67e74705SXin Li }
691*67e74705SXin Li }
692*67e74705SXin Li
693*67e74705SXin Li /// \brief Determine whether the given result set contains either a type name
694*67e74705SXin Li /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)695*67e74705SXin Li static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696*67e74705SXin Li bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697*67e74705SXin Li NextToken.is(tok::less);
698*67e74705SXin Li
699*67e74705SXin Li for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700*67e74705SXin Li if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701*67e74705SXin Li return true;
702*67e74705SXin Li
703*67e74705SXin Li if (CheckTemplate && isa<TemplateDecl>(*I))
704*67e74705SXin Li return true;
705*67e74705SXin Li }
706*67e74705SXin Li
707*67e74705SXin Li return false;
708*67e74705SXin Li }
709*67e74705SXin Li
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)710*67e74705SXin Li static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711*67e74705SXin Li Scope *S, CXXScopeSpec &SS,
712*67e74705SXin Li IdentifierInfo *&Name,
713*67e74705SXin Li SourceLocation NameLoc) {
714*67e74705SXin Li LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715*67e74705SXin Li SemaRef.LookupParsedName(R, S, &SS);
716*67e74705SXin Li if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717*67e74705SXin Li StringRef FixItTagName;
718*67e74705SXin Li switch (Tag->getTagKind()) {
719*67e74705SXin Li case TTK_Class:
720*67e74705SXin Li FixItTagName = "class ";
721*67e74705SXin Li break;
722*67e74705SXin Li
723*67e74705SXin Li case TTK_Enum:
724*67e74705SXin Li FixItTagName = "enum ";
725*67e74705SXin Li break;
726*67e74705SXin Li
727*67e74705SXin Li case TTK_Struct:
728*67e74705SXin Li FixItTagName = "struct ";
729*67e74705SXin Li break;
730*67e74705SXin Li
731*67e74705SXin Li case TTK_Interface:
732*67e74705SXin Li FixItTagName = "__interface ";
733*67e74705SXin Li break;
734*67e74705SXin Li
735*67e74705SXin Li case TTK_Union:
736*67e74705SXin Li FixItTagName = "union ";
737*67e74705SXin Li break;
738*67e74705SXin Li }
739*67e74705SXin Li
740*67e74705SXin Li StringRef TagName = FixItTagName.drop_back();
741*67e74705SXin Li SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742*67e74705SXin Li << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743*67e74705SXin Li << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744*67e74705SXin Li
745*67e74705SXin Li for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746*67e74705SXin Li I != IEnd; ++I)
747*67e74705SXin Li SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748*67e74705SXin Li << Name << TagName;
749*67e74705SXin Li
750*67e74705SXin Li // Replace lookup results with just the tag decl.
751*67e74705SXin Li Result.clear(Sema::LookupTagName);
752*67e74705SXin Li SemaRef.LookupParsedName(Result, S, &SS);
753*67e74705SXin Li return true;
754*67e74705SXin Li }
755*67e74705SXin Li
756*67e74705SXin Li return false;
757*67e74705SXin Li }
758*67e74705SXin Li
759*67e74705SXin Li /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNestedType(Sema & S,CXXScopeSpec & SS,QualType T,SourceLocation NameLoc)760*67e74705SXin Li static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761*67e74705SXin Li QualType T, SourceLocation NameLoc) {
762*67e74705SXin Li ASTContext &Context = S.Context;
763*67e74705SXin Li
764*67e74705SXin Li TypeLocBuilder Builder;
765*67e74705SXin Li Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766*67e74705SXin Li
767*67e74705SXin Li T = S.getElaboratedType(ETK_None, SS, T);
768*67e74705SXin Li ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769*67e74705SXin Li ElabTL.setElaboratedKeywordLoc(SourceLocation());
770*67e74705SXin Li ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771*67e74705SXin Li return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772*67e74705SXin Li }
773*67e74705SXin Li
774*67e74705SXin Li Sema::NameClassification
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC)775*67e74705SXin Li Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776*67e74705SXin Li SourceLocation NameLoc, const Token &NextToken,
777*67e74705SXin Li bool IsAddressOfOperand,
778*67e74705SXin Li std::unique_ptr<CorrectionCandidateCallback> CCC) {
779*67e74705SXin Li DeclarationNameInfo NameInfo(Name, NameLoc);
780*67e74705SXin Li ObjCMethodDecl *CurMethod = getCurMethodDecl();
781*67e74705SXin Li
782*67e74705SXin Li if (NextToken.is(tok::coloncolon)) {
783*67e74705SXin Li BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
784*67e74705SXin Li QualType(), false, SS, nullptr, false);
785*67e74705SXin Li }
786*67e74705SXin Li
787*67e74705SXin Li LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788*67e74705SXin Li LookupParsedName(Result, S, &SS, !CurMethod);
789*67e74705SXin Li
790*67e74705SXin Li // For unqualified lookup in a class template in MSVC mode, look into
791*67e74705SXin Li // dependent base classes where the primary class template is known.
792*67e74705SXin Li if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793*67e74705SXin Li if (ParsedType TypeInBase =
794*67e74705SXin Li recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795*67e74705SXin Li return TypeInBase;
796*67e74705SXin Li }
797*67e74705SXin Li
798*67e74705SXin Li // Perform lookup for Objective-C instance variables (including automatically
799*67e74705SXin Li // synthesized instance variables), if we're in an Objective-C method.
800*67e74705SXin Li // FIXME: This lookup really, really needs to be folded in to the normal
801*67e74705SXin Li // unqualified lookup mechanism.
802*67e74705SXin Li if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803*67e74705SXin Li ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804*67e74705SXin Li if (E.get() || E.isInvalid())
805*67e74705SXin Li return E;
806*67e74705SXin Li }
807*67e74705SXin Li
808*67e74705SXin Li bool SecondTry = false;
809*67e74705SXin Li bool IsFilteredTemplateName = false;
810*67e74705SXin Li
811*67e74705SXin Li Corrected:
812*67e74705SXin Li switch (Result.getResultKind()) {
813*67e74705SXin Li case LookupResult::NotFound:
814*67e74705SXin Li // If an unqualified-id is followed by a '(', then we have a function
815*67e74705SXin Li // call.
816*67e74705SXin Li if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817*67e74705SXin Li // In C++, this is an ADL-only call.
818*67e74705SXin Li // FIXME: Reference?
819*67e74705SXin Li if (getLangOpts().CPlusPlus)
820*67e74705SXin Li return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821*67e74705SXin Li
822*67e74705SXin Li // C90 6.3.2.2:
823*67e74705SXin Li // If the expression that precedes the parenthesized argument list in a
824*67e74705SXin Li // function call consists solely of an identifier, and if no
825*67e74705SXin Li // declaration is visible for this identifier, the identifier is
826*67e74705SXin Li // implicitly declared exactly as if, in the innermost block containing
827*67e74705SXin Li // the function call, the declaration
828*67e74705SXin Li //
829*67e74705SXin Li // extern int identifier ();
830*67e74705SXin Li //
831*67e74705SXin Li // appeared.
832*67e74705SXin Li //
833*67e74705SXin Li // We also allow this in C99 as an extension.
834*67e74705SXin Li if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835*67e74705SXin Li Result.addDecl(D);
836*67e74705SXin Li Result.resolveKind();
837*67e74705SXin Li return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838*67e74705SXin Li }
839*67e74705SXin Li }
840*67e74705SXin Li
841*67e74705SXin Li // In C, we first see whether there is a tag type by the same name, in
842*67e74705SXin Li // which case it's likely that the user just forgot to write "enum",
843*67e74705SXin Li // "struct", or "union".
844*67e74705SXin Li if (!getLangOpts().CPlusPlus && !SecondTry &&
845*67e74705SXin Li isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846*67e74705SXin Li break;
847*67e74705SXin Li }
848*67e74705SXin Li
849*67e74705SXin Li // Perform typo correction to determine if there is another name that is
850*67e74705SXin Li // close to this name.
851*67e74705SXin Li if (!SecondTry && CCC) {
852*67e74705SXin Li SecondTry = true;
853*67e74705SXin Li if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854*67e74705SXin Li Result.getLookupKind(), S,
855*67e74705SXin Li &SS, std::move(CCC),
856*67e74705SXin Li CTK_ErrorRecovery)) {
857*67e74705SXin Li unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858*67e74705SXin Li unsigned QualifiedDiag = diag::err_no_member_suggest;
859*67e74705SXin Li
860*67e74705SXin Li NamedDecl *FirstDecl = Corrected.getFoundDecl();
861*67e74705SXin Li NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862*67e74705SXin Li if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863*67e74705SXin Li UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864*67e74705SXin Li UnqualifiedDiag = diag::err_no_template_suggest;
865*67e74705SXin Li QualifiedDiag = diag::err_no_member_template_suggest;
866*67e74705SXin Li } else if (UnderlyingFirstDecl &&
867*67e74705SXin Li (isa<TypeDecl>(UnderlyingFirstDecl) ||
868*67e74705SXin Li isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869*67e74705SXin Li isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870*67e74705SXin Li UnqualifiedDiag = diag::err_unknown_typename_suggest;
871*67e74705SXin Li QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872*67e74705SXin Li }
873*67e74705SXin Li
874*67e74705SXin Li if (SS.isEmpty()) {
875*67e74705SXin Li diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876*67e74705SXin Li } else {// FIXME: is this even reachable? Test it.
877*67e74705SXin Li std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878*67e74705SXin Li bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879*67e74705SXin Li Name->getName().equals(CorrectedStr);
880*67e74705SXin Li diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881*67e74705SXin Li << Name << computeDeclContext(SS, false)
882*67e74705SXin Li << DroppedSpecifier << SS.getRange());
883*67e74705SXin Li }
884*67e74705SXin Li
885*67e74705SXin Li // Update the name, so that the caller has the new name.
886*67e74705SXin Li Name = Corrected.getCorrectionAsIdentifierInfo();
887*67e74705SXin Li
888*67e74705SXin Li // Typo correction corrected to a keyword.
889*67e74705SXin Li if (Corrected.isKeyword())
890*67e74705SXin Li return Name;
891*67e74705SXin Li
892*67e74705SXin Li // Also update the LookupResult...
893*67e74705SXin Li // FIXME: This should probably go away at some point
894*67e74705SXin Li Result.clear();
895*67e74705SXin Li Result.setLookupName(Corrected.getCorrection());
896*67e74705SXin Li if (FirstDecl)
897*67e74705SXin Li Result.addDecl(FirstDecl);
898*67e74705SXin Li
899*67e74705SXin Li // If we found an Objective-C instance variable, let
900*67e74705SXin Li // LookupInObjCMethod build the appropriate expression to
901*67e74705SXin Li // reference the ivar.
902*67e74705SXin Li // FIXME: This is a gross hack.
903*67e74705SXin Li if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904*67e74705SXin Li Result.clear();
905*67e74705SXin Li ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906*67e74705SXin Li return E;
907*67e74705SXin Li }
908*67e74705SXin Li
909*67e74705SXin Li goto Corrected;
910*67e74705SXin Li }
911*67e74705SXin Li }
912*67e74705SXin Li
913*67e74705SXin Li // We failed to correct; just fall through and let the parser deal with it.
914*67e74705SXin Li Result.suppressDiagnostics();
915*67e74705SXin Li return NameClassification::Unknown();
916*67e74705SXin Li
917*67e74705SXin Li case LookupResult::NotFoundInCurrentInstantiation: {
918*67e74705SXin Li // We performed name lookup into the current instantiation, and there were
919*67e74705SXin Li // dependent bases, so we treat this result the same way as any other
920*67e74705SXin Li // dependent nested-name-specifier.
921*67e74705SXin Li
922*67e74705SXin Li // C++ [temp.res]p2:
923*67e74705SXin Li // A name used in a template declaration or definition and that is
924*67e74705SXin Li // dependent on a template-parameter is assumed not to name a type
925*67e74705SXin Li // unless the applicable name lookup finds a type name or the name is
926*67e74705SXin Li // qualified by the keyword typename.
927*67e74705SXin Li //
928*67e74705SXin Li // FIXME: If the next token is '<', we might want to ask the parser to
929*67e74705SXin Li // perform some heroics to see if we actually have a
930*67e74705SXin Li // template-argument-list, which would indicate a missing 'template'
931*67e74705SXin Li // keyword here.
932*67e74705SXin Li return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933*67e74705SXin Li NameInfo, IsAddressOfOperand,
934*67e74705SXin Li /*TemplateArgs=*/nullptr);
935*67e74705SXin Li }
936*67e74705SXin Li
937*67e74705SXin Li case LookupResult::Found:
938*67e74705SXin Li case LookupResult::FoundOverloaded:
939*67e74705SXin Li case LookupResult::FoundUnresolvedValue:
940*67e74705SXin Li break;
941*67e74705SXin Li
942*67e74705SXin Li case LookupResult::Ambiguous:
943*67e74705SXin Li if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944*67e74705SXin Li hasAnyAcceptableTemplateNames(Result)) {
945*67e74705SXin Li // C++ [temp.local]p3:
946*67e74705SXin Li // A lookup that finds an injected-class-name (10.2) can result in an
947*67e74705SXin Li // ambiguity in certain cases (for example, if it is found in more than
948*67e74705SXin Li // one base class). If all of the injected-class-names that are found
949*67e74705SXin Li // refer to specializations of the same class template, and if the name
950*67e74705SXin Li // is followed by a template-argument-list, the reference refers to the
951*67e74705SXin Li // class template itself and not a specialization thereof, and is not
952*67e74705SXin Li // ambiguous.
953*67e74705SXin Li //
954*67e74705SXin Li // This filtering can make an ambiguous result into an unambiguous one,
955*67e74705SXin Li // so try again after filtering out template names.
956*67e74705SXin Li FilterAcceptableTemplateNames(Result);
957*67e74705SXin Li if (!Result.isAmbiguous()) {
958*67e74705SXin Li IsFilteredTemplateName = true;
959*67e74705SXin Li break;
960*67e74705SXin Li }
961*67e74705SXin Li }
962*67e74705SXin Li
963*67e74705SXin Li // Diagnose the ambiguity and return an error.
964*67e74705SXin Li return NameClassification::Error();
965*67e74705SXin Li }
966*67e74705SXin Li
967*67e74705SXin Li if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968*67e74705SXin Li (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969*67e74705SXin Li // C++ [temp.names]p3:
970*67e74705SXin Li // After name lookup (3.4) finds that a name is a template-name or that
971*67e74705SXin Li // an operator-function-id or a literal- operator-id refers to a set of
972*67e74705SXin Li // overloaded functions any member of which is a function template if
973*67e74705SXin Li // this is followed by a <, the < is always taken as the delimiter of a
974*67e74705SXin Li // template-argument-list and never as the less-than operator.
975*67e74705SXin Li if (!IsFilteredTemplateName)
976*67e74705SXin Li FilterAcceptableTemplateNames(Result);
977*67e74705SXin Li
978*67e74705SXin Li if (!Result.empty()) {
979*67e74705SXin Li bool IsFunctionTemplate;
980*67e74705SXin Li bool IsVarTemplate;
981*67e74705SXin Li TemplateName Template;
982*67e74705SXin Li if (Result.end() - Result.begin() > 1) {
983*67e74705SXin Li IsFunctionTemplate = true;
984*67e74705SXin Li Template = Context.getOverloadedTemplateName(Result.begin(),
985*67e74705SXin Li Result.end());
986*67e74705SXin Li } else {
987*67e74705SXin Li TemplateDecl *TD
988*67e74705SXin Li = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989*67e74705SXin Li IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990*67e74705SXin Li IsVarTemplate = isa<VarTemplateDecl>(TD);
991*67e74705SXin Li
992*67e74705SXin Li if (SS.isSet() && !SS.isInvalid())
993*67e74705SXin Li Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994*67e74705SXin Li /*TemplateKeyword=*/false,
995*67e74705SXin Li TD);
996*67e74705SXin Li else
997*67e74705SXin Li Template = TemplateName(TD);
998*67e74705SXin Li }
999*67e74705SXin Li
1000*67e74705SXin Li if (IsFunctionTemplate) {
1001*67e74705SXin Li // Function templates always go through overload resolution, at which
1002*67e74705SXin Li // point we'll perform the various checks (e.g., accessibility) we need
1003*67e74705SXin Li // to based on which function we selected.
1004*67e74705SXin Li Result.suppressDiagnostics();
1005*67e74705SXin Li
1006*67e74705SXin Li return NameClassification::FunctionTemplate(Template);
1007*67e74705SXin Li }
1008*67e74705SXin Li
1009*67e74705SXin Li return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010*67e74705SXin Li : NameClassification::TypeTemplate(Template);
1011*67e74705SXin Li }
1012*67e74705SXin Li }
1013*67e74705SXin Li
1014*67e74705SXin Li NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015*67e74705SXin Li if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016*67e74705SXin Li DiagnoseUseOfDecl(Type, NameLoc);
1017*67e74705SXin Li MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018*67e74705SXin Li QualType T = Context.getTypeDeclType(Type);
1019*67e74705SXin Li if (SS.isNotEmpty())
1020*67e74705SXin Li return buildNestedType(*this, SS, T, NameLoc);
1021*67e74705SXin Li return ParsedType::make(T);
1022*67e74705SXin Li }
1023*67e74705SXin Li
1024*67e74705SXin Li ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025*67e74705SXin Li if (!Class) {
1026*67e74705SXin Li // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027*67e74705SXin Li if (ObjCCompatibleAliasDecl *Alias =
1028*67e74705SXin Li dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029*67e74705SXin Li Class = Alias->getClassInterface();
1030*67e74705SXin Li }
1031*67e74705SXin Li
1032*67e74705SXin Li if (Class) {
1033*67e74705SXin Li DiagnoseUseOfDecl(Class, NameLoc);
1034*67e74705SXin Li
1035*67e74705SXin Li if (NextToken.is(tok::period)) {
1036*67e74705SXin Li // Interface. <something> is parsed as a property reference expression.
1037*67e74705SXin Li // Just return "unknown" as a fall-through for now.
1038*67e74705SXin Li Result.suppressDiagnostics();
1039*67e74705SXin Li return NameClassification::Unknown();
1040*67e74705SXin Li }
1041*67e74705SXin Li
1042*67e74705SXin Li QualType T = Context.getObjCInterfaceType(Class);
1043*67e74705SXin Li return ParsedType::make(T);
1044*67e74705SXin Li }
1045*67e74705SXin Li
1046*67e74705SXin Li // We can have a type template here if we're classifying a template argument.
1047*67e74705SXin Li if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048*67e74705SXin Li return NameClassification::TypeTemplate(
1049*67e74705SXin Li TemplateName(cast<TemplateDecl>(FirstDecl)));
1050*67e74705SXin Li
1051*67e74705SXin Li // Check for a tag type hidden by a non-type decl in a few cases where it
1052*67e74705SXin Li // seems likely a type is wanted instead of the non-type that was found.
1053*67e74705SXin Li bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054*67e74705SXin Li if ((NextToken.is(tok::identifier) ||
1055*67e74705SXin Li (NextIsOp &&
1056*67e74705SXin Li FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057*67e74705SXin Li isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058*67e74705SXin Li TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059*67e74705SXin Li DiagnoseUseOfDecl(Type, NameLoc);
1060*67e74705SXin Li QualType T = Context.getTypeDeclType(Type);
1061*67e74705SXin Li if (SS.isNotEmpty())
1062*67e74705SXin Li return buildNestedType(*this, SS, T, NameLoc);
1063*67e74705SXin Li return ParsedType::make(T);
1064*67e74705SXin Li }
1065*67e74705SXin Li
1066*67e74705SXin Li if (FirstDecl->isCXXClassMember())
1067*67e74705SXin Li return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068*67e74705SXin Li nullptr, S);
1069*67e74705SXin Li
1070*67e74705SXin Li bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071*67e74705SXin Li return BuildDeclarationNameExpr(SS, Result, ADL);
1072*67e74705SXin Li }
1073*67e74705SXin Li
1074*67e74705SXin Li // Determines the context to return to after temporarily entering a
1075*67e74705SXin Li // context. This depends in an unnecessarily complicated way on the
1076*67e74705SXin Li // exact ordering of callbacks from the parser.
getContainingDC(DeclContext * DC)1077*67e74705SXin Li DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078*67e74705SXin Li
1079*67e74705SXin Li // Functions defined inline within classes aren't parsed until we've
1080*67e74705SXin Li // finished parsing the top-level class, so the top-level class is
1081*67e74705SXin Li // the context we'll need to return to.
1082*67e74705SXin Li // A Lambda call operator whose parent is a class must not be treated
1083*67e74705SXin Li // as an inline member function. A Lambda can be used legally
1084*67e74705SXin Li // either as an in-class member initializer or a default argument. These
1085*67e74705SXin Li // are parsed once the class has been marked complete and so the containing
1086*67e74705SXin Li // context would be the nested class (when the lambda is defined in one);
1087*67e74705SXin Li // If the class is not complete, then the lambda is being used in an
1088*67e74705SXin Li // ill-formed fashion (such as to specify the width of a bit-field, or
1089*67e74705SXin Li // in an array-bound) - in which case we still want to return the
1090*67e74705SXin Li // lexically containing DC (which could be a nested class).
1091*67e74705SXin Li if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092*67e74705SXin Li DC = DC->getLexicalParent();
1093*67e74705SXin Li
1094*67e74705SXin Li // A function not defined within a class will always return to its
1095*67e74705SXin Li // lexical context.
1096*67e74705SXin Li if (!isa<CXXRecordDecl>(DC))
1097*67e74705SXin Li return DC;
1098*67e74705SXin Li
1099*67e74705SXin Li // A C++ inline method/friend is parsed *after* the topmost class
1100*67e74705SXin Li // it was declared in is fully parsed ("complete"); the topmost
1101*67e74705SXin Li // class is the context we need to return to.
1102*67e74705SXin Li while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103*67e74705SXin Li DC = RD;
1104*67e74705SXin Li
1105*67e74705SXin Li // Return the declaration context of the topmost class the inline method is
1106*67e74705SXin Li // declared in.
1107*67e74705SXin Li return DC;
1108*67e74705SXin Li }
1109*67e74705SXin Li
1110*67e74705SXin Li return DC->getLexicalParent();
1111*67e74705SXin Li }
1112*67e74705SXin Li
PushDeclContext(Scope * S,DeclContext * DC)1113*67e74705SXin Li void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114*67e74705SXin Li assert(getContainingDC(DC) == CurContext &&
1115*67e74705SXin Li "The next DeclContext should be lexically contained in the current one.");
1116*67e74705SXin Li CurContext = DC;
1117*67e74705SXin Li S->setEntity(DC);
1118*67e74705SXin Li }
1119*67e74705SXin Li
PopDeclContext()1120*67e74705SXin Li void Sema::PopDeclContext() {
1121*67e74705SXin Li assert(CurContext && "DeclContext imbalance!");
1122*67e74705SXin Li
1123*67e74705SXin Li CurContext = getContainingDC(CurContext);
1124*67e74705SXin Li assert(CurContext && "Popped translation unit!");
1125*67e74705SXin Li }
1126*67e74705SXin Li
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1127*67e74705SXin Li Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128*67e74705SXin Li Decl *D) {
1129*67e74705SXin Li // Unlike PushDeclContext, the context to which we return is not necessarily
1130*67e74705SXin Li // the containing DC of TD, because the new context will be some pre-existing
1131*67e74705SXin Li // TagDecl definition instead of a fresh one.
1132*67e74705SXin Li auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133*67e74705SXin Li CurContext = cast<TagDecl>(D)->getDefinition();
1134*67e74705SXin Li assert(CurContext && "skipping definition of undefined tag");
1135*67e74705SXin Li // Start lookups from the parent of the current context; we don't want to look
1136*67e74705SXin Li // into the pre-existing complete definition.
1137*67e74705SXin Li S->setEntity(CurContext->getLookupParent());
1138*67e74705SXin Li return Result;
1139*67e74705SXin Li }
1140*67e74705SXin Li
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1141*67e74705SXin Li void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142*67e74705SXin Li CurContext = static_cast<decltype(CurContext)>(Context);
1143*67e74705SXin Li }
1144*67e74705SXin Li
1145*67e74705SXin Li /// EnterDeclaratorContext - Used when we must lookup names in the context
1146*67e74705SXin Li /// of a declarator's nested name specifier.
1147*67e74705SXin Li ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)1148*67e74705SXin Li void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149*67e74705SXin Li // C++0x [basic.lookup.unqual]p13:
1150*67e74705SXin Li // A name used in the definition of a static data member of class
1151*67e74705SXin Li // X (after the qualified-id of the static member) is looked up as
1152*67e74705SXin Li // if the name was used in a member function of X.
1153*67e74705SXin Li // C++0x [basic.lookup.unqual]p14:
1154*67e74705SXin Li // If a variable member of a namespace is defined outside of the
1155*67e74705SXin Li // scope of its namespace then any name used in the definition of
1156*67e74705SXin Li // the variable member (after the declarator-id) is looked up as
1157*67e74705SXin Li // if the definition of the variable member occurred in its
1158*67e74705SXin Li // namespace.
1159*67e74705SXin Li // Both of these imply that we should push a scope whose context
1160*67e74705SXin Li // is the semantic context of the declaration. We can't use
1161*67e74705SXin Li // PushDeclContext here because that context is not necessarily
1162*67e74705SXin Li // lexically contained in the current context. Fortunately,
1163*67e74705SXin Li // the containing scope should have the appropriate information.
1164*67e74705SXin Li
1165*67e74705SXin Li assert(!S->getEntity() && "scope already has entity");
1166*67e74705SXin Li
1167*67e74705SXin Li #ifndef NDEBUG
1168*67e74705SXin Li Scope *Ancestor = S->getParent();
1169*67e74705SXin Li while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170*67e74705SXin Li assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171*67e74705SXin Li #endif
1172*67e74705SXin Li
1173*67e74705SXin Li CurContext = DC;
1174*67e74705SXin Li S->setEntity(DC);
1175*67e74705SXin Li }
1176*67e74705SXin Li
ExitDeclaratorContext(Scope * S)1177*67e74705SXin Li void Sema::ExitDeclaratorContext(Scope *S) {
1178*67e74705SXin Li assert(S->getEntity() == CurContext && "Context imbalance!");
1179*67e74705SXin Li
1180*67e74705SXin Li // Switch back to the lexical context. The safety of this is
1181*67e74705SXin Li // enforced by an assert in EnterDeclaratorContext.
1182*67e74705SXin Li Scope *Ancestor = S->getParent();
1183*67e74705SXin Li while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184*67e74705SXin Li CurContext = Ancestor->getEntity();
1185*67e74705SXin Li
1186*67e74705SXin Li // We don't need to do anything with the scope, which is going to
1187*67e74705SXin Li // disappear.
1188*67e74705SXin Li }
1189*67e74705SXin Li
ActOnReenterFunctionContext(Scope * S,Decl * D)1190*67e74705SXin Li void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191*67e74705SXin Li // We assume that the caller has already called
1192*67e74705SXin Li // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193*67e74705SXin Li FunctionDecl *FD = D->getAsFunction();
1194*67e74705SXin Li if (!FD)
1195*67e74705SXin Li return;
1196*67e74705SXin Li
1197*67e74705SXin Li // Same implementation as PushDeclContext, but enters the context
1198*67e74705SXin Li // from the lexical parent, rather than the top-level class.
1199*67e74705SXin Li assert(CurContext == FD->getLexicalParent() &&
1200*67e74705SXin Li "The next DeclContext should be lexically contained in the current one.");
1201*67e74705SXin Li CurContext = FD;
1202*67e74705SXin Li S->setEntity(CurContext);
1203*67e74705SXin Li
1204*67e74705SXin Li for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205*67e74705SXin Li ParmVarDecl *Param = FD->getParamDecl(P);
1206*67e74705SXin Li // If the parameter has an identifier, then add it to the scope
1207*67e74705SXin Li if (Param->getIdentifier()) {
1208*67e74705SXin Li S->AddDecl(Param);
1209*67e74705SXin Li IdResolver.AddDecl(Param);
1210*67e74705SXin Li }
1211*67e74705SXin Li }
1212*67e74705SXin Li }
1213*67e74705SXin Li
ActOnExitFunctionContext()1214*67e74705SXin Li void Sema::ActOnExitFunctionContext() {
1215*67e74705SXin Li // Same implementation as PopDeclContext, but returns to the lexical parent,
1216*67e74705SXin Li // rather than the top-level class.
1217*67e74705SXin Li assert(CurContext && "DeclContext imbalance!");
1218*67e74705SXin Li CurContext = CurContext->getLexicalParent();
1219*67e74705SXin Li assert(CurContext && "Popped translation unit!");
1220*67e74705SXin Li }
1221*67e74705SXin Li
1222*67e74705SXin Li /// \brief Determine whether we allow overloading of the function
1223*67e74705SXin Li /// PrevDecl with another declaration.
1224*67e74705SXin Li ///
1225*67e74705SXin Li /// This routine determines whether overloading is possible, not
1226*67e74705SXin Li /// whether some new function is actually an overload. It will return
1227*67e74705SXin Li /// true in C++ (where we can always provide overloads) or, as an
1228*67e74705SXin Li /// extension, in C when the previous function is already an
1229*67e74705SXin Li /// overloaded function declaration or has the "overloadable"
1230*67e74705SXin Li /// attribute.
AllowOverloadingOfFunction(LookupResult & Previous,ASTContext & Context)1231*67e74705SXin Li static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232*67e74705SXin Li ASTContext &Context) {
1233*67e74705SXin Li if (Context.getLangOpts().CPlusPlus)
1234*67e74705SXin Li return true;
1235*67e74705SXin Li
1236*67e74705SXin Li if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237*67e74705SXin Li return true;
1238*67e74705SXin Li
1239*67e74705SXin Li return (Previous.getResultKind() == LookupResult::Found
1240*67e74705SXin Li && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241*67e74705SXin Li }
1242*67e74705SXin Li
1243*67e74705SXin Li /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1244*67e74705SXin Li void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245*67e74705SXin Li // Move up the scope chain until we find the nearest enclosing
1246*67e74705SXin Li // non-transparent context. The declaration will be introduced into this
1247*67e74705SXin Li // scope.
1248*67e74705SXin Li while (S->getEntity() && S->getEntity()->isTransparentContext())
1249*67e74705SXin Li S = S->getParent();
1250*67e74705SXin Li
1251*67e74705SXin Li // Add scoped declarations into their context, so that they can be
1252*67e74705SXin Li // found later. Declarations without a context won't be inserted
1253*67e74705SXin Li // into any context.
1254*67e74705SXin Li if (AddToContext)
1255*67e74705SXin Li CurContext->addDecl(D);
1256*67e74705SXin Li
1257*67e74705SXin Li // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258*67e74705SXin Li // are function-local declarations.
1259*67e74705SXin Li if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260*67e74705SXin Li !D->getDeclContext()->getRedeclContext()->Equals(
1261*67e74705SXin Li D->getLexicalDeclContext()->getRedeclContext()) &&
1262*67e74705SXin Li !D->getLexicalDeclContext()->isFunctionOrMethod())
1263*67e74705SXin Li return;
1264*67e74705SXin Li
1265*67e74705SXin Li // Template instantiations should also not be pushed into scope.
1266*67e74705SXin Li if (isa<FunctionDecl>(D) &&
1267*67e74705SXin Li cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268*67e74705SXin Li return;
1269*67e74705SXin Li
1270*67e74705SXin Li // If this replaces anything in the current scope,
1271*67e74705SXin Li IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272*67e74705SXin Li IEnd = IdResolver.end();
1273*67e74705SXin Li for (; I != IEnd; ++I) {
1274*67e74705SXin Li if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275*67e74705SXin Li S->RemoveDecl(*I);
1276*67e74705SXin Li IdResolver.RemoveDecl(*I);
1277*67e74705SXin Li
1278*67e74705SXin Li // Should only need to replace one decl.
1279*67e74705SXin Li break;
1280*67e74705SXin Li }
1281*67e74705SXin Li }
1282*67e74705SXin Li
1283*67e74705SXin Li S->AddDecl(D);
1284*67e74705SXin Li
1285*67e74705SXin Li if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286*67e74705SXin Li // Implicitly-generated labels may end up getting generated in an order that
1287*67e74705SXin Li // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288*67e74705SXin Li // the label at the appropriate place in the identifier chain.
1289*67e74705SXin Li for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290*67e74705SXin Li DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291*67e74705SXin Li if (IDC == CurContext) {
1292*67e74705SXin Li if (!S->isDeclScope(*I))
1293*67e74705SXin Li continue;
1294*67e74705SXin Li } else if (IDC->Encloses(CurContext))
1295*67e74705SXin Li break;
1296*67e74705SXin Li }
1297*67e74705SXin Li
1298*67e74705SXin Li IdResolver.InsertDeclAfter(I, D);
1299*67e74705SXin Li } else {
1300*67e74705SXin Li IdResolver.AddDecl(D);
1301*67e74705SXin Li }
1302*67e74705SXin Li }
1303*67e74705SXin Li
pushExternalDeclIntoScope(NamedDecl * D,DeclarationName Name)1304*67e74705SXin Li void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305*67e74705SXin Li if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306*67e74705SXin Li TUScope->AddDecl(D);
1307*67e74705SXin Li }
1308*67e74705SXin Li
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace)1309*67e74705SXin Li bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310*67e74705SXin Li bool AllowInlineNamespace) {
1311*67e74705SXin Li return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312*67e74705SXin Li }
1313*67e74705SXin Li
getScopeForDeclContext(Scope * S,DeclContext * DC)1314*67e74705SXin Li Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315*67e74705SXin Li DeclContext *TargetDC = DC->getPrimaryContext();
1316*67e74705SXin Li do {
1317*67e74705SXin Li if (DeclContext *ScopeDC = S->getEntity())
1318*67e74705SXin Li if (ScopeDC->getPrimaryContext() == TargetDC)
1319*67e74705SXin Li return S;
1320*67e74705SXin Li } while ((S = S->getParent()));
1321*67e74705SXin Li
1322*67e74705SXin Li return nullptr;
1323*67e74705SXin Li }
1324*67e74705SXin Li
1325*67e74705SXin Li static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326*67e74705SXin Li DeclContext*,
1327*67e74705SXin Li ASTContext&);
1328*67e74705SXin Li
1329*67e74705SXin Li /// Filters out lookup results that don't fall within the given scope
1330*67e74705SXin Li /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1331*67e74705SXin Li void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332*67e74705SXin Li bool ConsiderLinkage,
1333*67e74705SXin Li bool AllowInlineNamespace) {
1334*67e74705SXin Li LookupResult::Filter F = R.makeFilter();
1335*67e74705SXin Li while (F.hasNext()) {
1336*67e74705SXin Li NamedDecl *D = F.next();
1337*67e74705SXin Li
1338*67e74705SXin Li if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339*67e74705SXin Li continue;
1340*67e74705SXin Li
1341*67e74705SXin Li if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342*67e74705SXin Li continue;
1343*67e74705SXin Li
1344*67e74705SXin Li F.erase();
1345*67e74705SXin Li }
1346*67e74705SXin Li
1347*67e74705SXin Li F.done();
1348*67e74705SXin Li }
1349*67e74705SXin Li
isUsingDecl(NamedDecl * D)1350*67e74705SXin Li static bool isUsingDecl(NamedDecl *D) {
1351*67e74705SXin Li return isa<UsingShadowDecl>(D) ||
1352*67e74705SXin Li isa<UnresolvedUsingTypenameDecl>(D) ||
1353*67e74705SXin Li isa<UnresolvedUsingValueDecl>(D);
1354*67e74705SXin Li }
1355*67e74705SXin Li
1356*67e74705SXin Li /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1357*67e74705SXin Li static void RemoveUsingDecls(LookupResult &R) {
1358*67e74705SXin Li LookupResult::Filter F = R.makeFilter();
1359*67e74705SXin Li while (F.hasNext())
1360*67e74705SXin Li if (isUsingDecl(F.next()))
1361*67e74705SXin Li F.erase();
1362*67e74705SXin Li
1363*67e74705SXin Li F.done();
1364*67e74705SXin Li }
1365*67e74705SXin Li
1366*67e74705SXin Li /// \brief Check for this common pattern:
1367*67e74705SXin Li /// @code
1368*67e74705SXin Li /// class S {
1369*67e74705SXin Li /// S(const S&); // DO NOT IMPLEMENT
1370*67e74705SXin Li /// void operator=(const S&); // DO NOT IMPLEMENT
1371*67e74705SXin Li /// };
1372*67e74705SXin Li /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1373*67e74705SXin Li static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374*67e74705SXin Li // FIXME: Should check for private access too but access is set after we get
1375*67e74705SXin Li // the decl here.
1376*67e74705SXin Li if (D->doesThisDeclarationHaveABody())
1377*67e74705SXin Li return false;
1378*67e74705SXin Li
1379*67e74705SXin Li if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380*67e74705SXin Li return CD->isCopyConstructor();
1381*67e74705SXin Li if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382*67e74705SXin Li return Method->isCopyAssignmentOperator();
1383*67e74705SXin Li return false;
1384*67e74705SXin Li }
1385*67e74705SXin Li
1386*67e74705SXin Li // We need this to handle
1387*67e74705SXin Li //
1388*67e74705SXin Li // typedef struct {
1389*67e74705SXin Li // void *foo() { return 0; }
1390*67e74705SXin Li // } A;
1391*67e74705SXin Li //
1392*67e74705SXin Li // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393*67e74705SXin Li // for example. If 'A', foo will have external linkage. If we have '*A',
1394*67e74705SXin Li // foo will have no linkage. Since we can't know until we get to the end
1395*67e74705SXin Li // of the typedef, this function finds out if D might have non-external linkage.
1396*67e74705SXin Li // Callers should verify at the end of the TU if it D has external linkage or
1397*67e74705SXin Li // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1398*67e74705SXin Li bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399*67e74705SXin Li const DeclContext *DC = D->getDeclContext();
1400*67e74705SXin Li while (!DC->isTranslationUnit()) {
1401*67e74705SXin Li if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402*67e74705SXin Li if (!RD->hasNameForLinkage())
1403*67e74705SXin Li return true;
1404*67e74705SXin Li }
1405*67e74705SXin Li DC = DC->getParent();
1406*67e74705SXin Li }
1407*67e74705SXin Li
1408*67e74705SXin Li return !D->isExternallyVisible();
1409*67e74705SXin Li }
1410*67e74705SXin Li
1411*67e74705SXin Li // FIXME: This needs to be refactored; some other isInMainFile users want
1412*67e74705SXin Li // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1413*67e74705SXin Li static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414*67e74705SXin Li if (S.TUKind != TU_Complete)
1415*67e74705SXin Li return false;
1416*67e74705SXin Li return S.SourceMgr.isInMainFile(Loc);
1417*67e74705SXin Li }
1418*67e74705SXin Li
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1419*67e74705SXin Li bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420*67e74705SXin Li assert(D);
1421*67e74705SXin Li
1422*67e74705SXin Li if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423*67e74705SXin Li return false;
1424*67e74705SXin Li
1425*67e74705SXin Li // Ignore all entities declared within templates, and out-of-line definitions
1426*67e74705SXin Li // of members of class templates.
1427*67e74705SXin Li if (D->getDeclContext()->isDependentContext() ||
1428*67e74705SXin Li D->getLexicalDeclContext()->isDependentContext())
1429*67e74705SXin Li return false;
1430*67e74705SXin Li
1431*67e74705SXin Li if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432*67e74705SXin Li if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433*67e74705SXin Li return false;
1434*67e74705SXin Li
1435*67e74705SXin Li if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436*67e74705SXin Li if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437*67e74705SXin Li return false;
1438*67e74705SXin Li } else {
1439*67e74705SXin Li // 'static inline' functions are defined in headers; don't warn.
1440*67e74705SXin Li if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441*67e74705SXin Li return false;
1442*67e74705SXin Li }
1443*67e74705SXin Li
1444*67e74705SXin Li if (FD->doesThisDeclarationHaveABody() &&
1445*67e74705SXin Li Context.DeclMustBeEmitted(FD))
1446*67e74705SXin Li return false;
1447*67e74705SXin Li } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448*67e74705SXin Li // Constants and utility variables are defined in headers with internal
1449*67e74705SXin Li // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1450*67e74705SXin Li // like "inline".)
1451*67e74705SXin Li if (!isMainFileLoc(*this, VD->getLocation()))
1452*67e74705SXin Li return false;
1453*67e74705SXin Li
1454*67e74705SXin Li if (Context.DeclMustBeEmitted(VD))
1455*67e74705SXin Li return false;
1456*67e74705SXin Li
1457*67e74705SXin Li if (VD->isStaticDataMember() &&
1458*67e74705SXin Li VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459*67e74705SXin Li return false;
1460*67e74705SXin Li
1461*67e74705SXin Li if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1462*67e74705SXin Li return false;
1463*67e74705SXin Li } else {
1464*67e74705SXin Li return false;
1465*67e74705SXin Li }
1466*67e74705SXin Li
1467*67e74705SXin Li // Only warn for unused decls internal to the translation unit.
1468*67e74705SXin Li // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469*67e74705SXin Li // for inline functions defined in the main source file, for instance.
1470*67e74705SXin Li return mightHaveNonExternalLinkage(D);
1471*67e74705SXin Li }
1472*67e74705SXin Li
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1473*67e74705SXin Li void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1474*67e74705SXin Li if (!D)
1475*67e74705SXin Li return;
1476*67e74705SXin Li
1477*67e74705SXin Li if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478*67e74705SXin Li const FunctionDecl *First = FD->getFirstDecl();
1479*67e74705SXin Li if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480*67e74705SXin Li return; // First should already be in the vector.
1481*67e74705SXin Li }
1482*67e74705SXin Li
1483*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484*67e74705SXin Li const VarDecl *First = VD->getFirstDecl();
1485*67e74705SXin Li if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486*67e74705SXin Li return; // First should already be in the vector.
1487*67e74705SXin Li }
1488*67e74705SXin Li
1489*67e74705SXin Li if (ShouldWarnIfUnusedFileScopedDecl(D))
1490*67e74705SXin Li UnusedFileScopedDecls.push_back(D);
1491*67e74705SXin Li }
1492*67e74705SXin Li
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1493*67e74705SXin Li static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494*67e74705SXin Li if (D->isInvalidDecl())
1495*67e74705SXin Li return false;
1496*67e74705SXin Li
1497*67e74705SXin Li if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498*67e74705SXin Li D->hasAttr<ObjCPreciseLifetimeAttr>())
1499*67e74705SXin Li return false;
1500*67e74705SXin Li
1501*67e74705SXin Li if (isa<LabelDecl>(D))
1502*67e74705SXin Li return true;
1503*67e74705SXin Li
1504*67e74705SXin Li // Except for labels, we only care about unused decls that are local to
1505*67e74705SXin Li // functions.
1506*67e74705SXin Li bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507*67e74705SXin Li if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508*67e74705SXin Li // For dependent types, the diagnostic is deferred.
1509*67e74705SXin Li WithinFunction =
1510*67e74705SXin Li WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511*67e74705SXin Li if (!WithinFunction)
1512*67e74705SXin Li return false;
1513*67e74705SXin Li
1514*67e74705SXin Li if (isa<TypedefNameDecl>(D))
1515*67e74705SXin Li return true;
1516*67e74705SXin Li
1517*67e74705SXin Li // White-list anything that isn't a local variable.
1518*67e74705SXin Li if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1519*67e74705SXin Li return false;
1520*67e74705SXin Li
1521*67e74705SXin Li // Types of valid local variables should be complete, so this should succeed.
1522*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523*67e74705SXin Li
1524*67e74705SXin Li // White-list anything with an __attribute__((unused)) type.
1525*67e74705SXin Li QualType Ty = VD->getType();
1526*67e74705SXin Li
1527*67e74705SXin Li // Only look at the outermost level of typedef.
1528*67e74705SXin Li if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529*67e74705SXin Li if (TT->getDecl()->hasAttr<UnusedAttr>())
1530*67e74705SXin Li return false;
1531*67e74705SXin Li }
1532*67e74705SXin Li
1533*67e74705SXin Li // If we failed to complete the type for some reason, or if the type is
1534*67e74705SXin Li // dependent, don't diagnose the variable.
1535*67e74705SXin Li if (Ty->isIncompleteType() || Ty->isDependentType())
1536*67e74705SXin Li return false;
1537*67e74705SXin Li
1538*67e74705SXin Li if (const TagType *TT = Ty->getAs<TagType>()) {
1539*67e74705SXin Li const TagDecl *Tag = TT->getDecl();
1540*67e74705SXin Li if (Tag->hasAttr<UnusedAttr>())
1541*67e74705SXin Li return false;
1542*67e74705SXin Li
1543*67e74705SXin Li if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1544*67e74705SXin Li if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1545*67e74705SXin Li return false;
1546*67e74705SXin Li
1547*67e74705SXin Li if (const Expr *Init = VD->getInit()) {
1548*67e74705SXin Li if (const ExprWithCleanups *Cleanups =
1549*67e74705SXin Li dyn_cast<ExprWithCleanups>(Init))
1550*67e74705SXin Li Init = Cleanups->getSubExpr();
1551*67e74705SXin Li const CXXConstructExpr *Construct =
1552*67e74705SXin Li dyn_cast<CXXConstructExpr>(Init);
1553*67e74705SXin Li if (Construct && !Construct->isElidable()) {
1554*67e74705SXin Li CXXConstructorDecl *CD = Construct->getConstructor();
1555*67e74705SXin Li if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1556*67e74705SXin Li return false;
1557*67e74705SXin Li }
1558*67e74705SXin Li }
1559*67e74705SXin Li }
1560*67e74705SXin Li }
1561*67e74705SXin Li
1562*67e74705SXin Li // TODO: __attribute__((unused)) templates?
1563*67e74705SXin Li }
1564*67e74705SXin Li
1565*67e74705SXin Li return true;
1566*67e74705SXin Li }
1567*67e74705SXin Li
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)1568*67e74705SXin Li static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1569*67e74705SXin Li FixItHint &Hint) {
1570*67e74705SXin Li if (isa<LabelDecl>(D)) {
1571*67e74705SXin Li SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1572*67e74705SXin Li tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1573*67e74705SXin Li if (AfterColon.isInvalid())
1574*67e74705SXin Li return;
1575*67e74705SXin Li Hint = FixItHint::CreateRemoval(CharSourceRange::
1576*67e74705SXin Li getCharRange(D->getLocStart(), AfterColon));
1577*67e74705SXin Li }
1578*67e74705SXin Li }
1579*67e74705SXin Li
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)1580*67e74705SXin Li void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1581*67e74705SXin Li if (D->getTypeForDecl()->isDependentType())
1582*67e74705SXin Li return;
1583*67e74705SXin Li
1584*67e74705SXin Li for (auto *TmpD : D->decls()) {
1585*67e74705SXin Li if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1586*67e74705SXin Li DiagnoseUnusedDecl(T);
1587*67e74705SXin Li else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1588*67e74705SXin Li DiagnoseUnusedNestedTypedefs(R);
1589*67e74705SXin Li }
1590*67e74705SXin Li }
1591*67e74705SXin Li
1592*67e74705SXin Li /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1593*67e74705SXin Li /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D)1594*67e74705SXin Li void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1595*67e74705SXin Li if (!ShouldDiagnoseUnusedDecl(D))
1596*67e74705SXin Li return;
1597*67e74705SXin Li
1598*67e74705SXin Li if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1599*67e74705SXin Li // typedefs can be referenced later on, so the diagnostics are emitted
1600*67e74705SXin Li // at end-of-translation-unit.
1601*67e74705SXin Li UnusedLocalTypedefNameCandidates.insert(TD);
1602*67e74705SXin Li return;
1603*67e74705SXin Li }
1604*67e74705SXin Li
1605*67e74705SXin Li FixItHint Hint;
1606*67e74705SXin Li GenerateFixForUnusedDecl(D, Context, Hint);
1607*67e74705SXin Li
1608*67e74705SXin Li unsigned DiagID;
1609*67e74705SXin Li if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1610*67e74705SXin Li DiagID = diag::warn_unused_exception_param;
1611*67e74705SXin Li else if (isa<LabelDecl>(D))
1612*67e74705SXin Li DiagID = diag::warn_unused_label;
1613*67e74705SXin Li else
1614*67e74705SXin Li DiagID = diag::warn_unused_variable;
1615*67e74705SXin Li
1616*67e74705SXin Li Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1617*67e74705SXin Li }
1618*67e74705SXin Li
CheckPoppedLabel(LabelDecl * L,Sema & S)1619*67e74705SXin Li static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1620*67e74705SXin Li // Verify that we have no forward references left. If so, there was a goto
1621*67e74705SXin Li // or address of a label taken, but no definition of it. Label fwd
1622*67e74705SXin Li // definitions are indicated with a null substmt which is also not a resolved
1623*67e74705SXin Li // MS inline assembly label name.
1624*67e74705SXin Li bool Diagnose = false;
1625*67e74705SXin Li if (L->isMSAsmLabel())
1626*67e74705SXin Li Diagnose = !L->isResolvedMSAsmLabel();
1627*67e74705SXin Li else
1628*67e74705SXin Li Diagnose = L->getStmt() == nullptr;
1629*67e74705SXin Li if (Diagnose)
1630*67e74705SXin Li S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1631*67e74705SXin Li }
1632*67e74705SXin Li
ActOnPopScope(SourceLocation Loc,Scope * S)1633*67e74705SXin Li void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1634*67e74705SXin Li S->mergeNRVOIntoParent();
1635*67e74705SXin Li
1636*67e74705SXin Li if (S->decl_empty()) return;
1637*67e74705SXin Li assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1638*67e74705SXin Li "Scope shouldn't contain decls!");
1639*67e74705SXin Li
1640*67e74705SXin Li for (auto *TmpD : S->decls()) {
1641*67e74705SXin Li assert(TmpD && "This decl didn't get pushed??");
1642*67e74705SXin Li
1643*67e74705SXin Li assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1644*67e74705SXin Li NamedDecl *D = cast<NamedDecl>(TmpD);
1645*67e74705SXin Li
1646*67e74705SXin Li if (!D->getDeclName()) continue;
1647*67e74705SXin Li
1648*67e74705SXin Li // Diagnose unused variables in this scope.
1649*67e74705SXin Li if (!S->hasUnrecoverableErrorOccurred()) {
1650*67e74705SXin Li DiagnoseUnusedDecl(D);
1651*67e74705SXin Li if (const auto *RD = dyn_cast<RecordDecl>(D))
1652*67e74705SXin Li DiagnoseUnusedNestedTypedefs(RD);
1653*67e74705SXin Li }
1654*67e74705SXin Li
1655*67e74705SXin Li // If this was a forward reference to a label, verify it was defined.
1656*67e74705SXin Li if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1657*67e74705SXin Li CheckPoppedLabel(LD, *this);
1658*67e74705SXin Li
1659*67e74705SXin Li // Remove this name from our lexical scope, and warn on it if we haven't
1660*67e74705SXin Li // already.
1661*67e74705SXin Li IdResolver.RemoveDecl(D);
1662*67e74705SXin Li auto ShadowI = ShadowingDecls.find(D);
1663*67e74705SXin Li if (ShadowI != ShadowingDecls.end()) {
1664*67e74705SXin Li if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1665*67e74705SXin Li Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1666*67e74705SXin Li << D << FD << FD->getParent();
1667*67e74705SXin Li Diag(FD->getLocation(), diag::note_previous_declaration);
1668*67e74705SXin Li }
1669*67e74705SXin Li ShadowingDecls.erase(ShadowI);
1670*67e74705SXin Li }
1671*67e74705SXin Li }
1672*67e74705SXin Li }
1673*67e74705SXin Li
1674*67e74705SXin Li /// \brief Look for an Objective-C class in the translation unit.
1675*67e74705SXin Li ///
1676*67e74705SXin Li /// \param Id The name of the Objective-C class we're looking for. If
1677*67e74705SXin Li /// typo-correction fixes this name, the Id will be updated
1678*67e74705SXin Li /// to the fixed name.
1679*67e74705SXin Li ///
1680*67e74705SXin Li /// \param IdLoc The location of the name in the translation unit.
1681*67e74705SXin Li ///
1682*67e74705SXin Li /// \param DoTypoCorrection If true, this routine will attempt typo correction
1683*67e74705SXin Li /// if there is no class with the given name.
1684*67e74705SXin Li ///
1685*67e74705SXin Li /// \returns The declaration of the named Objective-C class, or NULL if the
1686*67e74705SXin Li /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)1687*67e74705SXin Li ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1688*67e74705SXin Li SourceLocation IdLoc,
1689*67e74705SXin Li bool DoTypoCorrection) {
1690*67e74705SXin Li // The third "scope" argument is 0 since we aren't enabling lazy built-in
1691*67e74705SXin Li // creation from this context.
1692*67e74705SXin Li NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1693*67e74705SXin Li
1694*67e74705SXin Li if (!IDecl && DoTypoCorrection) {
1695*67e74705SXin Li // Perform typo correction at the given location, but only if we
1696*67e74705SXin Li // find an Objective-C class name.
1697*67e74705SXin Li if (TypoCorrection C = CorrectTypo(
1698*67e74705SXin Li DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1699*67e74705SXin Li llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1700*67e74705SXin Li CTK_ErrorRecovery)) {
1701*67e74705SXin Li diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1702*67e74705SXin Li IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1703*67e74705SXin Li Id = IDecl->getIdentifier();
1704*67e74705SXin Li }
1705*67e74705SXin Li }
1706*67e74705SXin Li ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1707*67e74705SXin Li // This routine must always return a class definition, if any.
1708*67e74705SXin Li if (Def && Def->getDefinition())
1709*67e74705SXin Li Def = Def->getDefinition();
1710*67e74705SXin Li return Def;
1711*67e74705SXin Li }
1712*67e74705SXin Li
1713*67e74705SXin Li /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1714*67e74705SXin Li /// from S, where a non-field would be declared. This routine copes
1715*67e74705SXin Li /// with the difference between C and C++ scoping rules in structs and
1716*67e74705SXin Li /// unions. For example, the following code is well-formed in C but
1717*67e74705SXin Li /// ill-formed in C++:
1718*67e74705SXin Li /// @code
1719*67e74705SXin Li /// struct S6 {
1720*67e74705SXin Li /// enum { BAR } e;
1721*67e74705SXin Li /// };
1722*67e74705SXin Li ///
1723*67e74705SXin Li /// void test_S6() {
1724*67e74705SXin Li /// struct S6 a;
1725*67e74705SXin Li /// a.e = BAR;
1726*67e74705SXin Li /// }
1727*67e74705SXin Li /// @endcode
1728*67e74705SXin Li /// For the declaration of BAR, this routine will return a different
1729*67e74705SXin Li /// scope. The scope S will be the scope of the unnamed enumeration
1730*67e74705SXin Li /// within S6. In C++, this routine will return the scope associated
1731*67e74705SXin Li /// with S6, because the enumeration's scope is a transparent
1732*67e74705SXin Li /// context but structures can contain non-field names. In C, this
1733*67e74705SXin Li /// routine will return the translation unit scope, since the
1734*67e74705SXin Li /// enumeration's scope is a transparent context and structures cannot
1735*67e74705SXin Li /// contain non-field names.
getNonFieldDeclScope(Scope * S)1736*67e74705SXin Li Scope *Sema::getNonFieldDeclScope(Scope *S) {
1737*67e74705SXin Li while (((S->getFlags() & Scope::DeclScope) == 0) ||
1738*67e74705SXin Li (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1739*67e74705SXin Li (S->isClassScope() && !getLangOpts().CPlusPlus))
1740*67e74705SXin Li S = S->getParent();
1741*67e74705SXin Li return S;
1742*67e74705SXin Li }
1743*67e74705SXin Li
1744*67e74705SXin Li /// \brief Looks up the declaration of "struct objc_super" and
1745*67e74705SXin Li /// saves it for later use in building builtin declaration of
1746*67e74705SXin Li /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1747*67e74705SXin Li /// pre-existing declaration exists no action takes place.
LookupPredefedObjCSuperType(Sema & ThisSema,Scope * S,IdentifierInfo * II)1748*67e74705SXin Li static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1749*67e74705SXin Li IdentifierInfo *II) {
1750*67e74705SXin Li if (!II->isStr("objc_msgSendSuper"))
1751*67e74705SXin Li return;
1752*67e74705SXin Li ASTContext &Context = ThisSema.Context;
1753*67e74705SXin Li
1754*67e74705SXin Li LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1755*67e74705SXin Li SourceLocation(), Sema::LookupTagName);
1756*67e74705SXin Li ThisSema.LookupName(Result, S);
1757*67e74705SXin Li if (Result.getResultKind() == LookupResult::Found)
1758*67e74705SXin Li if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1759*67e74705SXin Li Context.setObjCSuperType(Context.getTagDeclType(TD));
1760*67e74705SXin Li }
1761*67e74705SXin Li
getHeaderName(ASTContext::GetBuiltinTypeError Error)1762*67e74705SXin Li static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1763*67e74705SXin Li switch (Error) {
1764*67e74705SXin Li case ASTContext::GE_None:
1765*67e74705SXin Li return "";
1766*67e74705SXin Li case ASTContext::GE_Missing_stdio:
1767*67e74705SXin Li return "stdio.h";
1768*67e74705SXin Li case ASTContext::GE_Missing_setjmp:
1769*67e74705SXin Li return "setjmp.h";
1770*67e74705SXin Li case ASTContext::GE_Missing_ucontext:
1771*67e74705SXin Li return "ucontext.h";
1772*67e74705SXin Li }
1773*67e74705SXin Li llvm_unreachable("unhandled error kind");
1774*67e74705SXin Li }
1775*67e74705SXin Li
1776*67e74705SXin Li /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1777*67e74705SXin Li /// file scope. lazily create a decl for it. ForRedeclaration is true
1778*67e74705SXin Li /// if we're creating this built-in in anticipation of redeclaring the
1779*67e74705SXin Li /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)1780*67e74705SXin Li NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1781*67e74705SXin Li Scope *S, bool ForRedeclaration,
1782*67e74705SXin Li SourceLocation Loc) {
1783*67e74705SXin Li LookupPredefedObjCSuperType(*this, S, II);
1784*67e74705SXin Li
1785*67e74705SXin Li ASTContext::GetBuiltinTypeError Error;
1786*67e74705SXin Li QualType R = Context.GetBuiltinType(ID, Error);
1787*67e74705SXin Li if (Error) {
1788*67e74705SXin Li if (ForRedeclaration)
1789*67e74705SXin Li Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1790*67e74705SXin Li << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1791*67e74705SXin Li return nullptr;
1792*67e74705SXin Li }
1793*67e74705SXin Li
1794*67e74705SXin Li if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1795*67e74705SXin Li Diag(Loc, diag::ext_implicit_lib_function_decl)
1796*67e74705SXin Li << Context.BuiltinInfo.getName(ID) << R;
1797*67e74705SXin Li if (Context.BuiltinInfo.getHeaderName(ID) &&
1798*67e74705SXin Li !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1799*67e74705SXin Li Diag(Loc, diag::note_include_header_or_declare)
1800*67e74705SXin Li << Context.BuiltinInfo.getHeaderName(ID)
1801*67e74705SXin Li << Context.BuiltinInfo.getName(ID);
1802*67e74705SXin Li }
1803*67e74705SXin Li
1804*67e74705SXin Li if (R.isNull())
1805*67e74705SXin Li return nullptr;
1806*67e74705SXin Li
1807*67e74705SXin Li DeclContext *Parent = Context.getTranslationUnitDecl();
1808*67e74705SXin Li if (getLangOpts().CPlusPlus) {
1809*67e74705SXin Li LinkageSpecDecl *CLinkageDecl =
1810*67e74705SXin Li LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1811*67e74705SXin Li LinkageSpecDecl::lang_c, false);
1812*67e74705SXin Li CLinkageDecl->setImplicit();
1813*67e74705SXin Li Parent->addDecl(CLinkageDecl);
1814*67e74705SXin Li Parent = CLinkageDecl;
1815*67e74705SXin Li }
1816*67e74705SXin Li
1817*67e74705SXin Li FunctionDecl *New = FunctionDecl::Create(Context,
1818*67e74705SXin Li Parent,
1819*67e74705SXin Li Loc, Loc, II, R, /*TInfo=*/nullptr,
1820*67e74705SXin Li SC_Extern,
1821*67e74705SXin Li false,
1822*67e74705SXin Li R->isFunctionProtoType());
1823*67e74705SXin Li New->setImplicit();
1824*67e74705SXin Li
1825*67e74705SXin Li // Create Decl objects for each parameter, adding them to the
1826*67e74705SXin Li // FunctionDecl.
1827*67e74705SXin Li if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1828*67e74705SXin Li SmallVector<ParmVarDecl*, 16> Params;
1829*67e74705SXin Li for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1830*67e74705SXin Li ParmVarDecl *parm =
1831*67e74705SXin Li ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1832*67e74705SXin Li nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1833*67e74705SXin Li SC_None, nullptr);
1834*67e74705SXin Li parm->setScopeInfo(0, i);
1835*67e74705SXin Li Params.push_back(parm);
1836*67e74705SXin Li }
1837*67e74705SXin Li New->setParams(Params);
1838*67e74705SXin Li }
1839*67e74705SXin Li
1840*67e74705SXin Li AddKnownFunctionAttributes(New);
1841*67e74705SXin Li RegisterLocallyScopedExternCDecl(New, S);
1842*67e74705SXin Li
1843*67e74705SXin Li // TUScope is the translation-unit scope to insert this function into.
1844*67e74705SXin Li // FIXME: This is hideous. We need to teach PushOnScopeChains to
1845*67e74705SXin Li // relate Scopes to DeclContexts, and probably eliminate CurContext
1846*67e74705SXin Li // entirely, but we're not there yet.
1847*67e74705SXin Li DeclContext *SavedContext = CurContext;
1848*67e74705SXin Li CurContext = Parent;
1849*67e74705SXin Li PushOnScopeChains(New, TUScope);
1850*67e74705SXin Li CurContext = SavedContext;
1851*67e74705SXin Li return New;
1852*67e74705SXin Li }
1853*67e74705SXin Li
1854*67e74705SXin Li /// Typedef declarations don't have linkage, but they still denote the same
1855*67e74705SXin Li /// entity if their types are the same.
1856*67e74705SXin Li /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1857*67e74705SXin Li /// isSameEntity.
filterNonConflictingPreviousTypedefDecls(Sema & S,TypedefNameDecl * Decl,LookupResult & Previous)1858*67e74705SXin Li static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1859*67e74705SXin Li TypedefNameDecl *Decl,
1860*67e74705SXin Li LookupResult &Previous) {
1861*67e74705SXin Li // This is only interesting when modules are enabled.
1862*67e74705SXin Li if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1863*67e74705SXin Li return;
1864*67e74705SXin Li
1865*67e74705SXin Li // Empty sets are uninteresting.
1866*67e74705SXin Li if (Previous.empty())
1867*67e74705SXin Li return;
1868*67e74705SXin Li
1869*67e74705SXin Li LookupResult::Filter Filter = Previous.makeFilter();
1870*67e74705SXin Li while (Filter.hasNext()) {
1871*67e74705SXin Li NamedDecl *Old = Filter.next();
1872*67e74705SXin Li
1873*67e74705SXin Li // Non-hidden declarations are never ignored.
1874*67e74705SXin Li if (S.isVisible(Old))
1875*67e74705SXin Li continue;
1876*67e74705SXin Li
1877*67e74705SXin Li // Declarations of the same entity are not ignored, even if they have
1878*67e74705SXin Li // different linkages.
1879*67e74705SXin Li if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1880*67e74705SXin Li if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1881*67e74705SXin Li Decl->getUnderlyingType()))
1882*67e74705SXin Li continue;
1883*67e74705SXin Li
1884*67e74705SXin Li // If both declarations give a tag declaration a typedef name for linkage
1885*67e74705SXin Li // purposes, then they declare the same entity.
1886*67e74705SXin Li if (S.getLangOpts().CPlusPlus &&
1887*67e74705SXin Li OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1888*67e74705SXin Li Decl->getAnonDeclWithTypedefName())
1889*67e74705SXin Li continue;
1890*67e74705SXin Li }
1891*67e74705SXin Li
1892*67e74705SXin Li Filter.erase();
1893*67e74705SXin Li }
1894*67e74705SXin Li
1895*67e74705SXin Li Filter.done();
1896*67e74705SXin Li }
1897*67e74705SXin Li
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)1898*67e74705SXin Li bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1899*67e74705SXin Li QualType OldType;
1900*67e74705SXin Li if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1901*67e74705SXin Li OldType = OldTypedef->getUnderlyingType();
1902*67e74705SXin Li else
1903*67e74705SXin Li OldType = Context.getTypeDeclType(Old);
1904*67e74705SXin Li QualType NewType = New->getUnderlyingType();
1905*67e74705SXin Li
1906*67e74705SXin Li if (NewType->isVariablyModifiedType()) {
1907*67e74705SXin Li // Must not redefine a typedef with a variably-modified type.
1908*67e74705SXin Li int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1909*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1910*67e74705SXin Li << Kind << NewType;
1911*67e74705SXin Li if (Old->getLocation().isValid())
1912*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
1913*67e74705SXin Li New->setInvalidDecl();
1914*67e74705SXin Li return true;
1915*67e74705SXin Li }
1916*67e74705SXin Li
1917*67e74705SXin Li if (OldType != NewType &&
1918*67e74705SXin Li !OldType->isDependentType() &&
1919*67e74705SXin Li !NewType->isDependentType() &&
1920*67e74705SXin Li !Context.hasSameType(OldType, NewType)) {
1921*67e74705SXin Li int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1922*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1923*67e74705SXin Li << Kind << NewType << OldType;
1924*67e74705SXin Li if (Old->getLocation().isValid())
1925*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
1926*67e74705SXin Li New->setInvalidDecl();
1927*67e74705SXin Li return true;
1928*67e74705SXin Li }
1929*67e74705SXin Li return false;
1930*67e74705SXin Li }
1931*67e74705SXin Li
1932*67e74705SXin Li /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1933*67e74705SXin Li /// same name and scope as a previous declaration 'Old'. Figure out
1934*67e74705SXin Li /// how to resolve this situation, merging decls or emitting
1935*67e74705SXin Li /// diagnostics as appropriate. If there was an error, set New to be invalid.
1936*67e74705SXin Li ///
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)1937*67e74705SXin Li void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1938*67e74705SXin Li LookupResult &OldDecls) {
1939*67e74705SXin Li // If the new decl is known invalid already, don't bother doing any
1940*67e74705SXin Li // merging checks.
1941*67e74705SXin Li if (New->isInvalidDecl()) return;
1942*67e74705SXin Li
1943*67e74705SXin Li // Allow multiple definitions for ObjC built-in typedefs.
1944*67e74705SXin Li // FIXME: Verify the underlying types are equivalent!
1945*67e74705SXin Li if (getLangOpts().ObjC1) {
1946*67e74705SXin Li const IdentifierInfo *TypeID = New->getIdentifier();
1947*67e74705SXin Li switch (TypeID->getLength()) {
1948*67e74705SXin Li default: break;
1949*67e74705SXin Li case 2:
1950*67e74705SXin Li {
1951*67e74705SXin Li if (!TypeID->isStr("id"))
1952*67e74705SXin Li break;
1953*67e74705SXin Li QualType T = New->getUnderlyingType();
1954*67e74705SXin Li if (!T->isPointerType())
1955*67e74705SXin Li break;
1956*67e74705SXin Li if (!T->isVoidPointerType()) {
1957*67e74705SXin Li QualType PT = T->getAs<PointerType>()->getPointeeType();
1958*67e74705SXin Li if (!PT->isStructureType())
1959*67e74705SXin Li break;
1960*67e74705SXin Li }
1961*67e74705SXin Li Context.setObjCIdRedefinitionType(T);
1962*67e74705SXin Li // Install the built-in type for 'id', ignoring the current definition.
1963*67e74705SXin Li New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1964*67e74705SXin Li return;
1965*67e74705SXin Li }
1966*67e74705SXin Li case 5:
1967*67e74705SXin Li if (!TypeID->isStr("Class"))
1968*67e74705SXin Li break;
1969*67e74705SXin Li Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1970*67e74705SXin Li // Install the built-in type for 'Class', ignoring the current definition.
1971*67e74705SXin Li New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1972*67e74705SXin Li return;
1973*67e74705SXin Li case 3:
1974*67e74705SXin Li if (!TypeID->isStr("SEL"))
1975*67e74705SXin Li break;
1976*67e74705SXin Li Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1977*67e74705SXin Li // Install the built-in type for 'SEL', ignoring the current definition.
1978*67e74705SXin Li New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1979*67e74705SXin Li return;
1980*67e74705SXin Li }
1981*67e74705SXin Li // Fall through - the typedef name was not a builtin type.
1982*67e74705SXin Li }
1983*67e74705SXin Li
1984*67e74705SXin Li // Verify the old decl was also a type.
1985*67e74705SXin Li TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1986*67e74705SXin Li if (!Old) {
1987*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition_different_kind)
1988*67e74705SXin Li << New->getDeclName();
1989*67e74705SXin Li
1990*67e74705SXin Li NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1991*67e74705SXin Li if (OldD->getLocation().isValid())
1992*67e74705SXin Li Diag(OldD->getLocation(), diag::note_previous_definition);
1993*67e74705SXin Li
1994*67e74705SXin Li return New->setInvalidDecl();
1995*67e74705SXin Li }
1996*67e74705SXin Li
1997*67e74705SXin Li // If the old declaration is invalid, just give up here.
1998*67e74705SXin Li if (Old->isInvalidDecl())
1999*67e74705SXin Li return New->setInvalidDecl();
2000*67e74705SXin Li
2001*67e74705SXin Li if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2002*67e74705SXin Li auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2003*67e74705SXin Li auto *NewTag = New->getAnonDeclWithTypedefName();
2004*67e74705SXin Li NamedDecl *Hidden = nullptr;
2005*67e74705SXin Li if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2006*67e74705SXin Li OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2007*67e74705SXin Li !hasVisibleDefinition(OldTag, &Hidden)) {
2008*67e74705SXin Li // There is a definition of this tag, but it is not visible. Use it
2009*67e74705SXin Li // instead of our tag.
2010*67e74705SXin Li New->setTypeForDecl(OldTD->getTypeForDecl());
2011*67e74705SXin Li if (OldTD->isModed())
2012*67e74705SXin Li New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2013*67e74705SXin Li OldTD->getUnderlyingType());
2014*67e74705SXin Li else
2015*67e74705SXin Li New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2016*67e74705SXin Li
2017*67e74705SXin Li // Make the old tag definition visible.
2018*67e74705SXin Li makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2019*67e74705SXin Li
2020*67e74705SXin Li // If this was an unscoped enumeration, yank all of its enumerators
2021*67e74705SXin Li // out of the scope.
2022*67e74705SXin Li if (isa<EnumDecl>(NewTag)) {
2023*67e74705SXin Li Scope *EnumScope = getNonFieldDeclScope(S);
2024*67e74705SXin Li for (auto *D : NewTag->decls()) {
2025*67e74705SXin Li auto *ED = cast<EnumConstantDecl>(D);
2026*67e74705SXin Li assert(EnumScope->isDeclScope(ED));
2027*67e74705SXin Li EnumScope->RemoveDecl(ED);
2028*67e74705SXin Li IdResolver.RemoveDecl(ED);
2029*67e74705SXin Li ED->getLexicalDeclContext()->removeDecl(ED);
2030*67e74705SXin Li }
2031*67e74705SXin Li }
2032*67e74705SXin Li }
2033*67e74705SXin Li }
2034*67e74705SXin Li
2035*67e74705SXin Li // If the typedef types are not identical, reject them in all languages and
2036*67e74705SXin Li // with any extensions enabled.
2037*67e74705SXin Li if (isIncompatibleTypedef(Old, New))
2038*67e74705SXin Li return;
2039*67e74705SXin Li
2040*67e74705SXin Li // The types match. Link up the redeclaration chain and merge attributes if
2041*67e74705SXin Li // the old declaration was a typedef.
2042*67e74705SXin Li if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2043*67e74705SXin Li New->setPreviousDecl(Typedef);
2044*67e74705SXin Li mergeDeclAttributes(New, Old);
2045*67e74705SXin Li }
2046*67e74705SXin Li
2047*67e74705SXin Li if (getLangOpts().MicrosoftExt)
2048*67e74705SXin Li return;
2049*67e74705SXin Li
2050*67e74705SXin Li if (getLangOpts().CPlusPlus) {
2051*67e74705SXin Li // C++ [dcl.typedef]p2:
2052*67e74705SXin Li // In a given non-class scope, a typedef specifier can be used to
2053*67e74705SXin Li // redefine the name of any type declared in that scope to refer
2054*67e74705SXin Li // to the type to which it already refers.
2055*67e74705SXin Li if (!isa<CXXRecordDecl>(CurContext))
2056*67e74705SXin Li return;
2057*67e74705SXin Li
2058*67e74705SXin Li // C++0x [dcl.typedef]p4:
2059*67e74705SXin Li // In a given class scope, a typedef specifier can be used to redefine
2060*67e74705SXin Li // any class-name declared in that scope that is not also a typedef-name
2061*67e74705SXin Li // to refer to the type to which it already refers.
2062*67e74705SXin Li //
2063*67e74705SXin Li // This wording came in via DR424, which was a correction to the
2064*67e74705SXin Li // wording in DR56, which accidentally banned code like:
2065*67e74705SXin Li //
2066*67e74705SXin Li // struct S {
2067*67e74705SXin Li // typedef struct A { } A;
2068*67e74705SXin Li // };
2069*67e74705SXin Li //
2070*67e74705SXin Li // in the C++03 standard. We implement the C++0x semantics, which
2071*67e74705SXin Li // allow the above but disallow
2072*67e74705SXin Li //
2073*67e74705SXin Li // struct S {
2074*67e74705SXin Li // typedef int I;
2075*67e74705SXin Li // typedef int I;
2076*67e74705SXin Li // };
2077*67e74705SXin Li //
2078*67e74705SXin Li // since that was the intent of DR56.
2079*67e74705SXin Li if (!isa<TypedefNameDecl>(Old))
2080*67e74705SXin Li return;
2081*67e74705SXin Li
2082*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition)
2083*67e74705SXin Li << New->getDeclName();
2084*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
2085*67e74705SXin Li return New->setInvalidDecl();
2086*67e74705SXin Li }
2087*67e74705SXin Li
2088*67e74705SXin Li // Modules always permit redefinition of typedefs, as does C11.
2089*67e74705SXin Li if (getLangOpts().Modules || getLangOpts().C11)
2090*67e74705SXin Li return;
2091*67e74705SXin Li
2092*67e74705SXin Li // If we have a redefinition of a typedef in C, emit a warning. This warning
2093*67e74705SXin Li // is normally mapped to an error, but can be controlled with
2094*67e74705SXin Li // -Wtypedef-redefinition. If either the original or the redefinition is
2095*67e74705SXin Li // in a system header, don't emit this for compatibility with GCC.
2096*67e74705SXin Li if (getDiagnostics().getSuppressSystemWarnings() &&
2097*67e74705SXin Li (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2098*67e74705SXin Li Context.getSourceManager().isInSystemHeader(New->getLocation())))
2099*67e74705SXin Li return;
2100*67e74705SXin Li
2101*67e74705SXin Li Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2102*67e74705SXin Li << New->getDeclName();
2103*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
2104*67e74705SXin Li }
2105*67e74705SXin Li
2106*67e74705SXin Li /// DeclhasAttr - returns true if decl Declaration already has the target
2107*67e74705SXin Li /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2108*67e74705SXin Li static bool DeclHasAttr(const Decl *D, const Attr *A) {
2109*67e74705SXin Li const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2110*67e74705SXin Li const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2111*67e74705SXin Li for (const auto *i : D->attrs())
2112*67e74705SXin Li if (i->getKind() == A->getKind()) {
2113*67e74705SXin Li if (Ann) {
2114*67e74705SXin Li if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2115*67e74705SXin Li return true;
2116*67e74705SXin Li continue;
2117*67e74705SXin Li }
2118*67e74705SXin Li // FIXME: Don't hardcode this check
2119*67e74705SXin Li if (OA && isa<OwnershipAttr>(i))
2120*67e74705SXin Li return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2121*67e74705SXin Li return true;
2122*67e74705SXin Li }
2123*67e74705SXin Li
2124*67e74705SXin Li return false;
2125*67e74705SXin Li }
2126*67e74705SXin Li
isAttributeTargetADefinition(Decl * D)2127*67e74705SXin Li static bool isAttributeTargetADefinition(Decl *D) {
2128*67e74705SXin Li if (VarDecl *VD = dyn_cast<VarDecl>(D))
2129*67e74705SXin Li return VD->isThisDeclarationADefinition();
2130*67e74705SXin Li if (TagDecl *TD = dyn_cast<TagDecl>(D))
2131*67e74705SXin Li return TD->isCompleteDefinition() || TD->isBeingDefined();
2132*67e74705SXin Li return true;
2133*67e74705SXin Li }
2134*67e74705SXin Li
2135*67e74705SXin Li /// Merge alignment attributes from \p Old to \p New, taking into account the
2136*67e74705SXin Li /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2137*67e74705SXin Li ///
2138*67e74705SXin Li /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2139*67e74705SXin Li static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2140*67e74705SXin Li // Look for alignas attributes on Old, and pick out whichever attribute
2141*67e74705SXin Li // specifies the strictest alignment requirement.
2142*67e74705SXin Li AlignedAttr *OldAlignasAttr = nullptr;
2143*67e74705SXin Li AlignedAttr *OldStrictestAlignAttr = nullptr;
2144*67e74705SXin Li unsigned OldAlign = 0;
2145*67e74705SXin Li for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2146*67e74705SXin Li // FIXME: We have no way of representing inherited dependent alignments
2147*67e74705SXin Li // in a case like:
2148*67e74705SXin Li // template<int A, int B> struct alignas(A) X;
2149*67e74705SXin Li // template<int A, int B> struct alignas(B) X {};
2150*67e74705SXin Li // For now, we just ignore any alignas attributes which are not on the
2151*67e74705SXin Li // definition in such a case.
2152*67e74705SXin Li if (I->isAlignmentDependent())
2153*67e74705SXin Li return false;
2154*67e74705SXin Li
2155*67e74705SXin Li if (I->isAlignas())
2156*67e74705SXin Li OldAlignasAttr = I;
2157*67e74705SXin Li
2158*67e74705SXin Li unsigned Align = I->getAlignment(S.Context);
2159*67e74705SXin Li if (Align > OldAlign) {
2160*67e74705SXin Li OldAlign = Align;
2161*67e74705SXin Li OldStrictestAlignAttr = I;
2162*67e74705SXin Li }
2163*67e74705SXin Li }
2164*67e74705SXin Li
2165*67e74705SXin Li // Look for alignas attributes on New.
2166*67e74705SXin Li AlignedAttr *NewAlignasAttr = nullptr;
2167*67e74705SXin Li unsigned NewAlign = 0;
2168*67e74705SXin Li for (auto *I : New->specific_attrs<AlignedAttr>()) {
2169*67e74705SXin Li if (I->isAlignmentDependent())
2170*67e74705SXin Li return false;
2171*67e74705SXin Li
2172*67e74705SXin Li if (I->isAlignas())
2173*67e74705SXin Li NewAlignasAttr = I;
2174*67e74705SXin Li
2175*67e74705SXin Li unsigned Align = I->getAlignment(S.Context);
2176*67e74705SXin Li if (Align > NewAlign)
2177*67e74705SXin Li NewAlign = Align;
2178*67e74705SXin Li }
2179*67e74705SXin Li
2180*67e74705SXin Li if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2181*67e74705SXin Li // Both declarations have 'alignas' attributes. We require them to match.
2182*67e74705SXin Li // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2183*67e74705SXin Li // fall short. (If two declarations both have alignas, they must both match
2184*67e74705SXin Li // every definition, and so must match each other if there is a definition.)
2185*67e74705SXin Li
2186*67e74705SXin Li // If either declaration only contains 'alignas(0)' specifiers, then it
2187*67e74705SXin Li // specifies the natural alignment for the type.
2188*67e74705SXin Li if (OldAlign == 0 || NewAlign == 0) {
2189*67e74705SXin Li QualType Ty;
2190*67e74705SXin Li if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2191*67e74705SXin Li Ty = VD->getType();
2192*67e74705SXin Li else
2193*67e74705SXin Li Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2194*67e74705SXin Li
2195*67e74705SXin Li if (OldAlign == 0)
2196*67e74705SXin Li OldAlign = S.Context.getTypeAlign(Ty);
2197*67e74705SXin Li if (NewAlign == 0)
2198*67e74705SXin Li NewAlign = S.Context.getTypeAlign(Ty);
2199*67e74705SXin Li }
2200*67e74705SXin Li
2201*67e74705SXin Li if (OldAlign != NewAlign) {
2202*67e74705SXin Li S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2203*67e74705SXin Li << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2204*67e74705SXin Li << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2205*67e74705SXin Li S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2206*67e74705SXin Li }
2207*67e74705SXin Li }
2208*67e74705SXin Li
2209*67e74705SXin Li if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2210*67e74705SXin Li // C++11 [dcl.align]p6:
2211*67e74705SXin Li // if any declaration of an entity has an alignment-specifier,
2212*67e74705SXin Li // every defining declaration of that entity shall specify an
2213*67e74705SXin Li // equivalent alignment.
2214*67e74705SXin Li // C11 6.7.5/7:
2215*67e74705SXin Li // If the definition of an object does not have an alignment
2216*67e74705SXin Li // specifier, any other declaration of that object shall also
2217*67e74705SXin Li // have no alignment specifier.
2218*67e74705SXin Li S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2219*67e74705SXin Li << OldAlignasAttr;
2220*67e74705SXin Li S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2221*67e74705SXin Li << OldAlignasAttr;
2222*67e74705SXin Li }
2223*67e74705SXin Li
2224*67e74705SXin Li bool AnyAdded = false;
2225*67e74705SXin Li
2226*67e74705SXin Li // Ensure we have an attribute representing the strictest alignment.
2227*67e74705SXin Li if (OldAlign > NewAlign) {
2228*67e74705SXin Li AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2229*67e74705SXin Li Clone->setInherited(true);
2230*67e74705SXin Li New->addAttr(Clone);
2231*67e74705SXin Li AnyAdded = true;
2232*67e74705SXin Li }
2233*67e74705SXin Li
2234*67e74705SXin Li // Ensure we have an alignas attribute if the old declaration had one.
2235*67e74705SXin Li if (OldAlignasAttr && !NewAlignasAttr &&
2236*67e74705SXin Li !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2237*67e74705SXin Li AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2238*67e74705SXin Li Clone->setInherited(true);
2239*67e74705SXin Li New->addAttr(Clone);
2240*67e74705SXin Li AnyAdded = true;
2241*67e74705SXin Li }
2242*67e74705SXin Li
2243*67e74705SXin Li return AnyAdded;
2244*67e74705SXin Li }
2245*67e74705SXin Li
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2246*67e74705SXin Li static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2247*67e74705SXin Li const InheritableAttr *Attr,
2248*67e74705SXin Li Sema::AvailabilityMergeKind AMK) {
2249*67e74705SXin Li InheritableAttr *NewAttr = nullptr;
2250*67e74705SXin Li unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2251*67e74705SXin Li if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2252*67e74705SXin Li NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2253*67e74705SXin Li AA->isImplicit(), AA->getIntroduced(),
2254*67e74705SXin Li AA->getDeprecated(),
2255*67e74705SXin Li AA->getObsoleted(), AA->getUnavailable(),
2256*67e74705SXin Li AA->getMessage(), AA->getStrict(),
2257*67e74705SXin Li AA->getReplacement(), AMK,
2258*67e74705SXin Li AttrSpellingListIndex);
2259*67e74705SXin Li else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2260*67e74705SXin Li NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2261*67e74705SXin Li AttrSpellingListIndex);
2262*67e74705SXin Li else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2263*67e74705SXin Li NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2264*67e74705SXin Li AttrSpellingListIndex);
2265*67e74705SXin Li else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2266*67e74705SXin Li NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2267*67e74705SXin Li AttrSpellingListIndex);
2268*67e74705SXin Li else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2269*67e74705SXin Li NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2270*67e74705SXin Li AttrSpellingListIndex);
2271*67e74705SXin Li else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2272*67e74705SXin Li NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2273*67e74705SXin Li FA->getFormatIdx(), FA->getFirstArg(),
2274*67e74705SXin Li AttrSpellingListIndex);
2275*67e74705SXin Li else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2276*67e74705SXin Li NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2277*67e74705SXin Li AttrSpellingListIndex);
2278*67e74705SXin Li else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2279*67e74705SXin Li NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2280*67e74705SXin Li AttrSpellingListIndex,
2281*67e74705SXin Li IA->getSemanticSpelling());
2282*67e74705SXin Li else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2283*67e74705SXin Li NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2284*67e74705SXin Li &S.Context.Idents.get(AA->getSpelling()),
2285*67e74705SXin Li AttrSpellingListIndex);
2286*67e74705SXin Li else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2287*67e74705SXin Li NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2288*67e74705SXin Li else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2289*67e74705SXin Li NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2290*67e74705SXin Li else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2291*67e74705SXin Li NewAttr = S.mergeInternalLinkageAttr(
2292*67e74705SXin Li D, InternalLinkageA->getRange(),
2293*67e74705SXin Li &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2294*67e74705SXin Li AttrSpellingListIndex);
2295*67e74705SXin Li else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2296*67e74705SXin Li NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2297*67e74705SXin Li &S.Context.Idents.get(CommonA->getSpelling()),
2298*67e74705SXin Li AttrSpellingListIndex);
2299*67e74705SXin Li else if (isa<AlignedAttr>(Attr))
2300*67e74705SXin Li // AlignedAttrs are handled separately, because we need to handle all
2301*67e74705SXin Li // such attributes on a declaration at the same time.
2302*67e74705SXin Li NewAttr = nullptr;
2303*67e74705SXin Li else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2304*67e74705SXin Li (AMK == Sema::AMK_Override ||
2305*67e74705SXin Li AMK == Sema::AMK_ProtocolImplementation))
2306*67e74705SXin Li NewAttr = nullptr;
2307*67e74705SXin Li else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2308*67e74705SXin Li NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2309*67e74705SXin Li
2310*67e74705SXin Li if (NewAttr) {
2311*67e74705SXin Li NewAttr->setInherited(true);
2312*67e74705SXin Li D->addAttr(NewAttr);
2313*67e74705SXin Li if (isa<MSInheritanceAttr>(NewAttr))
2314*67e74705SXin Li S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2315*67e74705SXin Li return true;
2316*67e74705SXin Li }
2317*67e74705SXin Li
2318*67e74705SXin Li return false;
2319*67e74705SXin Li }
2320*67e74705SXin Li
getDefinition(const Decl * D)2321*67e74705SXin Li static const Decl *getDefinition(const Decl *D) {
2322*67e74705SXin Li if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2323*67e74705SXin Li return TD->getDefinition();
2324*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2325*67e74705SXin Li const VarDecl *Def = VD->getDefinition();
2326*67e74705SXin Li if (Def)
2327*67e74705SXin Li return Def;
2328*67e74705SXin Li return VD->getActingDefinition();
2329*67e74705SXin Li }
2330*67e74705SXin Li if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2331*67e74705SXin Li return FD->getDefinition();
2332*67e74705SXin Li return nullptr;
2333*67e74705SXin Li }
2334*67e74705SXin Li
hasAttribute(const Decl * D,attr::Kind Kind)2335*67e74705SXin Li static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2336*67e74705SXin Li for (const auto *Attribute : D->attrs())
2337*67e74705SXin Li if (Attribute->getKind() == Kind)
2338*67e74705SXin Li return true;
2339*67e74705SXin Li return false;
2340*67e74705SXin Li }
2341*67e74705SXin Li
2342*67e74705SXin Li /// checkNewAttributesAfterDef - If we already have a definition, check that
2343*67e74705SXin Li /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2344*67e74705SXin Li static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2345*67e74705SXin Li if (!New->hasAttrs())
2346*67e74705SXin Li return;
2347*67e74705SXin Li
2348*67e74705SXin Li const Decl *Def = getDefinition(Old);
2349*67e74705SXin Li if (!Def || Def == New)
2350*67e74705SXin Li return;
2351*67e74705SXin Li
2352*67e74705SXin Li AttrVec &NewAttributes = New->getAttrs();
2353*67e74705SXin Li for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2354*67e74705SXin Li const Attr *NewAttribute = NewAttributes[I];
2355*67e74705SXin Li
2356*67e74705SXin Li if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2357*67e74705SXin Li if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2358*67e74705SXin Li Sema::SkipBodyInfo SkipBody;
2359*67e74705SXin Li S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2360*67e74705SXin Li
2361*67e74705SXin Li // If we're skipping this definition, drop the "alias" attribute.
2362*67e74705SXin Li if (SkipBody.ShouldSkip) {
2363*67e74705SXin Li NewAttributes.erase(NewAttributes.begin() + I);
2364*67e74705SXin Li --E;
2365*67e74705SXin Li continue;
2366*67e74705SXin Li }
2367*67e74705SXin Li } else {
2368*67e74705SXin Li VarDecl *VD = cast<VarDecl>(New);
2369*67e74705SXin Li unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2370*67e74705SXin Li VarDecl::TentativeDefinition
2371*67e74705SXin Li ? diag::err_alias_after_tentative
2372*67e74705SXin Li : diag::err_redefinition;
2373*67e74705SXin Li S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2374*67e74705SXin Li S.Diag(Def->getLocation(), diag::note_previous_definition);
2375*67e74705SXin Li VD->setInvalidDecl();
2376*67e74705SXin Li }
2377*67e74705SXin Li ++I;
2378*67e74705SXin Li continue;
2379*67e74705SXin Li }
2380*67e74705SXin Li
2381*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2382*67e74705SXin Li // Tentative definitions are only interesting for the alias check above.
2383*67e74705SXin Li if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2384*67e74705SXin Li ++I;
2385*67e74705SXin Li continue;
2386*67e74705SXin Li }
2387*67e74705SXin Li }
2388*67e74705SXin Li
2389*67e74705SXin Li if (hasAttribute(Def, NewAttribute->getKind())) {
2390*67e74705SXin Li ++I;
2391*67e74705SXin Li continue; // regular attr merging will take care of validating this.
2392*67e74705SXin Li }
2393*67e74705SXin Li
2394*67e74705SXin Li if (isa<C11NoReturnAttr>(NewAttribute)) {
2395*67e74705SXin Li // C's _Noreturn is allowed to be added to a function after it is defined.
2396*67e74705SXin Li ++I;
2397*67e74705SXin Li continue;
2398*67e74705SXin Li } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2399*67e74705SXin Li if (AA->isAlignas()) {
2400*67e74705SXin Li // C++11 [dcl.align]p6:
2401*67e74705SXin Li // if any declaration of an entity has an alignment-specifier,
2402*67e74705SXin Li // every defining declaration of that entity shall specify an
2403*67e74705SXin Li // equivalent alignment.
2404*67e74705SXin Li // C11 6.7.5/7:
2405*67e74705SXin Li // If the definition of an object does not have an alignment
2406*67e74705SXin Li // specifier, any other declaration of that object shall also
2407*67e74705SXin Li // have no alignment specifier.
2408*67e74705SXin Li S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2409*67e74705SXin Li << AA;
2410*67e74705SXin Li S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2411*67e74705SXin Li << AA;
2412*67e74705SXin Li NewAttributes.erase(NewAttributes.begin() + I);
2413*67e74705SXin Li --E;
2414*67e74705SXin Li continue;
2415*67e74705SXin Li }
2416*67e74705SXin Li }
2417*67e74705SXin Li
2418*67e74705SXin Li S.Diag(NewAttribute->getLocation(),
2419*67e74705SXin Li diag::warn_attribute_precede_definition);
2420*67e74705SXin Li S.Diag(Def->getLocation(), diag::note_previous_definition);
2421*67e74705SXin Li NewAttributes.erase(NewAttributes.begin() + I);
2422*67e74705SXin Li --E;
2423*67e74705SXin Li }
2424*67e74705SXin Li }
2425*67e74705SXin Li
2426*67e74705SXin Li /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)2427*67e74705SXin Li void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2428*67e74705SXin Li AvailabilityMergeKind AMK) {
2429*67e74705SXin Li if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2430*67e74705SXin Li UsedAttr *NewAttr = OldAttr->clone(Context);
2431*67e74705SXin Li NewAttr->setInherited(true);
2432*67e74705SXin Li New->addAttr(NewAttr);
2433*67e74705SXin Li }
2434*67e74705SXin Li
2435*67e74705SXin Li if (!Old->hasAttrs() && !New->hasAttrs())
2436*67e74705SXin Li return;
2437*67e74705SXin Li
2438*67e74705SXin Li // Attributes declared post-definition are currently ignored.
2439*67e74705SXin Li checkNewAttributesAfterDef(*this, New, Old);
2440*67e74705SXin Li
2441*67e74705SXin Li if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2442*67e74705SXin Li if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2443*67e74705SXin Li if (OldA->getLabel() != NewA->getLabel()) {
2444*67e74705SXin Li // This redeclaration changes __asm__ label.
2445*67e74705SXin Li Diag(New->getLocation(), diag::err_different_asm_label);
2446*67e74705SXin Li Diag(OldA->getLocation(), diag::note_previous_declaration);
2447*67e74705SXin Li }
2448*67e74705SXin Li } else if (Old->isUsed()) {
2449*67e74705SXin Li // This redeclaration adds an __asm__ label to a declaration that has
2450*67e74705SXin Li // already been ODR-used.
2451*67e74705SXin Li Diag(New->getLocation(), diag::err_late_asm_label_name)
2452*67e74705SXin Li << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2453*67e74705SXin Li }
2454*67e74705SXin Li }
2455*67e74705SXin Li
2456*67e74705SXin Li // Re-declaration cannot add abi_tag's.
2457*67e74705SXin Li if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2458*67e74705SXin Li if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2459*67e74705SXin Li for (const auto &NewTag : NewAbiTagAttr->tags()) {
2460*67e74705SXin Li if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2461*67e74705SXin Li NewTag) == OldAbiTagAttr->tags_end()) {
2462*67e74705SXin Li Diag(NewAbiTagAttr->getLocation(),
2463*67e74705SXin Li diag::err_new_abi_tag_on_redeclaration)
2464*67e74705SXin Li << NewTag;
2465*67e74705SXin Li Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2466*67e74705SXin Li }
2467*67e74705SXin Li }
2468*67e74705SXin Li } else {
2469*67e74705SXin Li Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2470*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_declaration);
2471*67e74705SXin Li }
2472*67e74705SXin Li }
2473*67e74705SXin Li
2474*67e74705SXin Li if (!Old->hasAttrs())
2475*67e74705SXin Li return;
2476*67e74705SXin Li
2477*67e74705SXin Li bool foundAny = New->hasAttrs();
2478*67e74705SXin Li
2479*67e74705SXin Li // Ensure that any moving of objects within the allocated map is done before
2480*67e74705SXin Li // we process them.
2481*67e74705SXin Li if (!foundAny) New->setAttrs(AttrVec());
2482*67e74705SXin Li
2483*67e74705SXin Li for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2484*67e74705SXin Li // Ignore deprecated/unavailable/availability attributes if requested.
2485*67e74705SXin Li AvailabilityMergeKind LocalAMK = AMK_None;
2486*67e74705SXin Li if (isa<DeprecatedAttr>(I) ||
2487*67e74705SXin Li isa<UnavailableAttr>(I) ||
2488*67e74705SXin Li isa<AvailabilityAttr>(I)) {
2489*67e74705SXin Li switch (AMK) {
2490*67e74705SXin Li case AMK_None:
2491*67e74705SXin Li continue;
2492*67e74705SXin Li
2493*67e74705SXin Li case AMK_Redeclaration:
2494*67e74705SXin Li case AMK_Override:
2495*67e74705SXin Li case AMK_ProtocolImplementation:
2496*67e74705SXin Li LocalAMK = AMK;
2497*67e74705SXin Li break;
2498*67e74705SXin Li }
2499*67e74705SXin Li }
2500*67e74705SXin Li
2501*67e74705SXin Li // Already handled.
2502*67e74705SXin Li if (isa<UsedAttr>(I))
2503*67e74705SXin Li continue;
2504*67e74705SXin Li
2505*67e74705SXin Li if (mergeDeclAttribute(*this, New, I, LocalAMK))
2506*67e74705SXin Li foundAny = true;
2507*67e74705SXin Li }
2508*67e74705SXin Li
2509*67e74705SXin Li if (mergeAlignedAttrs(*this, New, Old))
2510*67e74705SXin Li foundAny = true;
2511*67e74705SXin Li
2512*67e74705SXin Li if (!foundAny) New->dropAttrs();
2513*67e74705SXin Li }
2514*67e74705SXin Li
2515*67e74705SXin Li /// mergeParamDeclAttributes - Copy attributes from the old parameter
2516*67e74705SXin Li /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)2517*67e74705SXin Li static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2518*67e74705SXin Li const ParmVarDecl *oldDecl,
2519*67e74705SXin Li Sema &S) {
2520*67e74705SXin Li // C++11 [dcl.attr.depend]p2:
2521*67e74705SXin Li // The first declaration of a function shall specify the
2522*67e74705SXin Li // carries_dependency attribute for its declarator-id if any declaration
2523*67e74705SXin Li // of the function specifies the carries_dependency attribute.
2524*67e74705SXin Li const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2525*67e74705SXin Li if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2526*67e74705SXin Li S.Diag(CDA->getLocation(),
2527*67e74705SXin Li diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2528*67e74705SXin Li // Find the first declaration of the parameter.
2529*67e74705SXin Li // FIXME: Should we build redeclaration chains for function parameters?
2530*67e74705SXin Li const FunctionDecl *FirstFD =
2531*67e74705SXin Li cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2532*67e74705SXin Li const ParmVarDecl *FirstVD =
2533*67e74705SXin Li FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2534*67e74705SXin Li S.Diag(FirstVD->getLocation(),
2535*67e74705SXin Li diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2536*67e74705SXin Li }
2537*67e74705SXin Li
2538*67e74705SXin Li if (!oldDecl->hasAttrs())
2539*67e74705SXin Li return;
2540*67e74705SXin Li
2541*67e74705SXin Li bool foundAny = newDecl->hasAttrs();
2542*67e74705SXin Li
2543*67e74705SXin Li // Ensure that any moving of objects within the allocated map is
2544*67e74705SXin Li // done before we process them.
2545*67e74705SXin Li if (!foundAny) newDecl->setAttrs(AttrVec());
2546*67e74705SXin Li
2547*67e74705SXin Li for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2548*67e74705SXin Li if (!DeclHasAttr(newDecl, I)) {
2549*67e74705SXin Li InheritableAttr *newAttr =
2550*67e74705SXin Li cast<InheritableParamAttr>(I->clone(S.Context));
2551*67e74705SXin Li newAttr->setInherited(true);
2552*67e74705SXin Li newDecl->addAttr(newAttr);
2553*67e74705SXin Li foundAny = true;
2554*67e74705SXin Li }
2555*67e74705SXin Li }
2556*67e74705SXin Li
2557*67e74705SXin Li if (!foundAny) newDecl->dropAttrs();
2558*67e74705SXin Li }
2559*67e74705SXin Li
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)2560*67e74705SXin Li static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2561*67e74705SXin Li const ParmVarDecl *OldParam,
2562*67e74705SXin Li Sema &S) {
2563*67e74705SXin Li if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2564*67e74705SXin Li if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2565*67e74705SXin Li if (*Oldnullability != *Newnullability) {
2566*67e74705SXin Li S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2567*67e74705SXin Li << DiagNullabilityKind(
2568*67e74705SXin Li *Newnullability,
2569*67e74705SXin Li ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2570*67e74705SXin Li != 0))
2571*67e74705SXin Li << DiagNullabilityKind(
2572*67e74705SXin Li *Oldnullability,
2573*67e74705SXin Li ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2574*67e74705SXin Li != 0));
2575*67e74705SXin Li S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2576*67e74705SXin Li }
2577*67e74705SXin Li } else {
2578*67e74705SXin Li QualType NewT = NewParam->getType();
2579*67e74705SXin Li NewT = S.Context.getAttributedType(
2580*67e74705SXin Li AttributedType::getNullabilityAttrKind(*Oldnullability),
2581*67e74705SXin Li NewT, NewT);
2582*67e74705SXin Li NewParam->setType(NewT);
2583*67e74705SXin Li }
2584*67e74705SXin Li }
2585*67e74705SXin Li }
2586*67e74705SXin Li
2587*67e74705SXin Li namespace {
2588*67e74705SXin Li
2589*67e74705SXin Li /// Used in MergeFunctionDecl to keep track of function parameters in
2590*67e74705SXin Li /// C.
2591*67e74705SXin Li struct GNUCompatibleParamWarning {
2592*67e74705SXin Li ParmVarDecl *OldParm;
2593*67e74705SXin Li ParmVarDecl *NewParm;
2594*67e74705SXin Li QualType PromotedType;
2595*67e74705SXin Li };
2596*67e74705SXin Li
2597*67e74705SXin Li } // end anonymous namespace
2598*67e74705SXin Li
2599*67e74705SXin Li /// getSpecialMember - get the special member enum for a method.
getSpecialMember(const CXXMethodDecl * MD)2600*67e74705SXin Li Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2601*67e74705SXin Li if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2602*67e74705SXin Li if (Ctor->isDefaultConstructor())
2603*67e74705SXin Li return Sema::CXXDefaultConstructor;
2604*67e74705SXin Li
2605*67e74705SXin Li if (Ctor->isCopyConstructor())
2606*67e74705SXin Li return Sema::CXXCopyConstructor;
2607*67e74705SXin Li
2608*67e74705SXin Li if (Ctor->isMoveConstructor())
2609*67e74705SXin Li return Sema::CXXMoveConstructor;
2610*67e74705SXin Li } else if (isa<CXXDestructorDecl>(MD)) {
2611*67e74705SXin Li return Sema::CXXDestructor;
2612*67e74705SXin Li } else if (MD->isCopyAssignmentOperator()) {
2613*67e74705SXin Li return Sema::CXXCopyAssignment;
2614*67e74705SXin Li } else if (MD->isMoveAssignmentOperator()) {
2615*67e74705SXin Li return Sema::CXXMoveAssignment;
2616*67e74705SXin Li }
2617*67e74705SXin Li
2618*67e74705SXin Li return Sema::CXXInvalid;
2619*67e74705SXin Li }
2620*67e74705SXin Li
2621*67e74705SXin Li // Determine whether the previous declaration was a definition, implicit
2622*67e74705SXin Li // declaration, or a declaration.
2623*67e74705SXin Li template <typename T>
2624*67e74705SXin Li static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)2625*67e74705SXin Li getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2626*67e74705SXin Li diag::kind PrevDiag;
2627*67e74705SXin Li SourceLocation OldLocation = Old->getLocation();
2628*67e74705SXin Li if (Old->isThisDeclarationADefinition())
2629*67e74705SXin Li PrevDiag = diag::note_previous_definition;
2630*67e74705SXin Li else if (Old->isImplicit()) {
2631*67e74705SXin Li PrevDiag = diag::note_previous_implicit_declaration;
2632*67e74705SXin Li if (OldLocation.isInvalid())
2633*67e74705SXin Li OldLocation = New->getLocation();
2634*67e74705SXin Li } else
2635*67e74705SXin Li PrevDiag = diag::note_previous_declaration;
2636*67e74705SXin Li return std::make_pair(PrevDiag, OldLocation);
2637*67e74705SXin Li }
2638*67e74705SXin Li
2639*67e74705SXin Li /// canRedefineFunction - checks if a function can be redefined. Currently,
2640*67e74705SXin Li /// only extern inline functions can be redefined, and even then only in
2641*67e74705SXin Li /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)2642*67e74705SXin Li static bool canRedefineFunction(const FunctionDecl *FD,
2643*67e74705SXin Li const LangOptions& LangOpts) {
2644*67e74705SXin Li return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2645*67e74705SXin Li !LangOpts.CPlusPlus &&
2646*67e74705SXin Li FD->isInlineSpecified() &&
2647*67e74705SXin Li FD->getStorageClass() == SC_Extern);
2648*67e74705SXin Li }
2649*67e74705SXin Li
getCallingConvAttributedType(QualType T) const2650*67e74705SXin Li const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2651*67e74705SXin Li const AttributedType *AT = T->getAs<AttributedType>();
2652*67e74705SXin Li while (AT && !AT->isCallingConv())
2653*67e74705SXin Li AT = AT->getModifiedType()->getAs<AttributedType>();
2654*67e74705SXin Li return AT;
2655*67e74705SXin Li }
2656*67e74705SXin Li
2657*67e74705SXin Li template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)2658*67e74705SXin Li static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2659*67e74705SXin Li const DeclContext *DC = Old->getDeclContext();
2660*67e74705SXin Li if (DC->isRecord())
2661*67e74705SXin Li return false;
2662*67e74705SXin Li
2663*67e74705SXin Li LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2664*67e74705SXin Li if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2665*67e74705SXin Li return true;
2666*67e74705SXin Li if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2667*67e74705SXin Li return true;
2668*67e74705SXin Li return false;
2669*67e74705SXin Li }
2670*67e74705SXin Li
isExternC(T * D)2671*67e74705SXin Li template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)2672*67e74705SXin Li static bool isExternC(VarTemplateDecl *) { return false; }
2673*67e74705SXin Li
2674*67e74705SXin Li /// \brief Check whether a redeclaration of an entity introduced by a
2675*67e74705SXin Li /// using-declaration is valid, given that we know it's not an overload
2676*67e74705SXin Li /// (nor a hidden tag declaration).
2677*67e74705SXin Li template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)2678*67e74705SXin Li static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2679*67e74705SXin Li ExpectedDecl *New) {
2680*67e74705SXin Li // C++11 [basic.scope.declarative]p4:
2681*67e74705SXin Li // Given a set of declarations in a single declarative region, each of
2682*67e74705SXin Li // which specifies the same unqualified name,
2683*67e74705SXin Li // -- they shall all refer to the same entity, or all refer to functions
2684*67e74705SXin Li // and function templates; or
2685*67e74705SXin Li // -- exactly one declaration shall declare a class name or enumeration
2686*67e74705SXin Li // name that is not a typedef name and the other declarations shall all
2687*67e74705SXin Li // refer to the same variable or enumerator, or all refer to functions
2688*67e74705SXin Li // and function templates; in this case the class name or enumeration
2689*67e74705SXin Li // name is hidden (3.3.10).
2690*67e74705SXin Li
2691*67e74705SXin Li // C++11 [namespace.udecl]p14:
2692*67e74705SXin Li // If a function declaration in namespace scope or block scope has the
2693*67e74705SXin Li // same name and the same parameter-type-list as a function introduced
2694*67e74705SXin Li // by a using-declaration, and the declarations do not declare the same
2695*67e74705SXin Li // function, the program is ill-formed.
2696*67e74705SXin Li
2697*67e74705SXin Li auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2698*67e74705SXin Li if (Old &&
2699*67e74705SXin Li !Old->getDeclContext()->getRedeclContext()->Equals(
2700*67e74705SXin Li New->getDeclContext()->getRedeclContext()) &&
2701*67e74705SXin Li !(isExternC(Old) && isExternC(New)))
2702*67e74705SXin Li Old = nullptr;
2703*67e74705SXin Li
2704*67e74705SXin Li if (!Old) {
2705*67e74705SXin Li S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2706*67e74705SXin Li S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2707*67e74705SXin Li S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2708*67e74705SXin Li return true;
2709*67e74705SXin Li }
2710*67e74705SXin Li return false;
2711*67e74705SXin Li }
2712*67e74705SXin Li
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)2713*67e74705SXin Li static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2714*67e74705SXin Li const FunctionDecl *B) {
2715*67e74705SXin Li assert(A->getNumParams() == B->getNumParams());
2716*67e74705SXin Li
2717*67e74705SXin Li auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2718*67e74705SXin Li const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2719*67e74705SXin Li const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2720*67e74705SXin Li if (AttrA == AttrB)
2721*67e74705SXin Li return true;
2722*67e74705SXin Li return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2723*67e74705SXin Li };
2724*67e74705SXin Li
2725*67e74705SXin Li return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2726*67e74705SXin Li }
2727*67e74705SXin Li
2728*67e74705SXin Li /// MergeFunctionDecl - We just parsed a function 'New' from
2729*67e74705SXin Li /// declarator D which has the same name and scope as a previous
2730*67e74705SXin Li /// declaration 'Old'. Figure out how to resolve this situation,
2731*67e74705SXin Li /// merging decls or emitting diagnostics as appropriate.
2732*67e74705SXin Li ///
2733*67e74705SXin Li /// In C++, New and Old must be declarations that are not
2734*67e74705SXin Li /// overloaded. Use IsOverload to determine whether New and Old are
2735*67e74705SXin Li /// overloaded, and to select the Old declaration that New should be
2736*67e74705SXin Li /// merged with.
2737*67e74705SXin Li ///
2738*67e74705SXin Li /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld)2739*67e74705SXin Li bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2740*67e74705SXin Li Scope *S, bool MergeTypeWithOld) {
2741*67e74705SXin Li // Verify the old decl was also a function.
2742*67e74705SXin Li FunctionDecl *Old = OldD->getAsFunction();
2743*67e74705SXin Li if (!Old) {
2744*67e74705SXin Li if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2745*67e74705SXin Li if (New->getFriendObjectKind()) {
2746*67e74705SXin Li Diag(New->getLocation(), diag::err_using_decl_friend);
2747*67e74705SXin Li Diag(Shadow->getTargetDecl()->getLocation(),
2748*67e74705SXin Li diag::note_using_decl_target);
2749*67e74705SXin Li Diag(Shadow->getUsingDecl()->getLocation(),
2750*67e74705SXin Li diag::note_using_decl) << 0;
2751*67e74705SXin Li return true;
2752*67e74705SXin Li }
2753*67e74705SXin Li
2754*67e74705SXin Li // Check whether the two declarations might declare the same function.
2755*67e74705SXin Li if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2756*67e74705SXin Li return true;
2757*67e74705SXin Li OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2758*67e74705SXin Li } else {
2759*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition_different_kind)
2760*67e74705SXin Li << New->getDeclName();
2761*67e74705SXin Li Diag(OldD->getLocation(), diag::note_previous_definition);
2762*67e74705SXin Li return true;
2763*67e74705SXin Li }
2764*67e74705SXin Li }
2765*67e74705SXin Li
2766*67e74705SXin Li // If the old declaration is invalid, just give up here.
2767*67e74705SXin Li if (Old->isInvalidDecl())
2768*67e74705SXin Li return true;
2769*67e74705SXin Li
2770*67e74705SXin Li diag::kind PrevDiag;
2771*67e74705SXin Li SourceLocation OldLocation;
2772*67e74705SXin Li std::tie(PrevDiag, OldLocation) =
2773*67e74705SXin Li getNoteDiagForInvalidRedeclaration(Old, New);
2774*67e74705SXin Li
2775*67e74705SXin Li // Don't complain about this if we're in GNU89 mode and the old function
2776*67e74705SXin Li // is an extern inline function.
2777*67e74705SXin Li // Don't complain about specializations. They are not supposed to have
2778*67e74705SXin Li // storage classes.
2779*67e74705SXin Li if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2780*67e74705SXin Li New->getStorageClass() == SC_Static &&
2781*67e74705SXin Li Old->hasExternalFormalLinkage() &&
2782*67e74705SXin Li !New->getTemplateSpecializationInfo() &&
2783*67e74705SXin Li !canRedefineFunction(Old, getLangOpts())) {
2784*67e74705SXin Li if (getLangOpts().MicrosoftExt) {
2785*67e74705SXin Li Diag(New->getLocation(), diag::ext_static_non_static) << New;
2786*67e74705SXin Li Diag(OldLocation, PrevDiag);
2787*67e74705SXin Li } else {
2788*67e74705SXin Li Diag(New->getLocation(), diag::err_static_non_static) << New;
2789*67e74705SXin Li Diag(OldLocation, PrevDiag);
2790*67e74705SXin Li return true;
2791*67e74705SXin Li }
2792*67e74705SXin Li }
2793*67e74705SXin Li
2794*67e74705SXin Li if (New->hasAttr<InternalLinkageAttr>() &&
2795*67e74705SXin Li !Old->hasAttr<InternalLinkageAttr>()) {
2796*67e74705SXin Li Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2797*67e74705SXin Li << New->getDeclName();
2798*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
2799*67e74705SXin Li New->dropAttr<InternalLinkageAttr>();
2800*67e74705SXin Li }
2801*67e74705SXin Li
2802*67e74705SXin Li // If a function is first declared with a calling convention, but is later
2803*67e74705SXin Li // declared or defined without one, all following decls assume the calling
2804*67e74705SXin Li // convention of the first.
2805*67e74705SXin Li //
2806*67e74705SXin Li // It's OK if a function is first declared without a calling convention,
2807*67e74705SXin Li // but is later declared or defined with the default calling convention.
2808*67e74705SXin Li //
2809*67e74705SXin Li // To test if either decl has an explicit calling convention, we look for
2810*67e74705SXin Li // AttributedType sugar nodes on the type as written. If they are missing or
2811*67e74705SXin Li // were canonicalized away, we assume the calling convention was implicit.
2812*67e74705SXin Li //
2813*67e74705SXin Li // Note also that we DO NOT return at this point, because we still have
2814*67e74705SXin Li // other tests to run.
2815*67e74705SXin Li QualType OldQType = Context.getCanonicalType(Old->getType());
2816*67e74705SXin Li QualType NewQType = Context.getCanonicalType(New->getType());
2817*67e74705SXin Li const FunctionType *OldType = cast<FunctionType>(OldQType);
2818*67e74705SXin Li const FunctionType *NewType = cast<FunctionType>(NewQType);
2819*67e74705SXin Li FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2820*67e74705SXin Li FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2821*67e74705SXin Li bool RequiresAdjustment = false;
2822*67e74705SXin Li
2823*67e74705SXin Li if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2824*67e74705SXin Li FunctionDecl *First = Old->getFirstDecl();
2825*67e74705SXin Li const FunctionType *FT =
2826*67e74705SXin Li First->getType().getCanonicalType()->castAs<FunctionType>();
2827*67e74705SXin Li FunctionType::ExtInfo FI = FT->getExtInfo();
2828*67e74705SXin Li bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2829*67e74705SXin Li if (!NewCCExplicit) {
2830*67e74705SXin Li // Inherit the CC from the previous declaration if it was specified
2831*67e74705SXin Li // there but not here.
2832*67e74705SXin Li NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2833*67e74705SXin Li RequiresAdjustment = true;
2834*67e74705SXin Li } else {
2835*67e74705SXin Li // Calling conventions aren't compatible, so complain.
2836*67e74705SXin Li bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2837*67e74705SXin Li Diag(New->getLocation(), diag::err_cconv_change)
2838*67e74705SXin Li << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2839*67e74705SXin Li << !FirstCCExplicit
2840*67e74705SXin Li << (!FirstCCExplicit ? "" :
2841*67e74705SXin Li FunctionType::getNameForCallConv(FI.getCC()));
2842*67e74705SXin Li
2843*67e74705SXin Li // Put the note on the first decl, since it is the one that matters.
2844*67e74705SXin Li Diag(First->getLocation(), diag::note_previous_declaration);
2845*67e74705SXin Li return true;
2846*67e74705SXin Li }
2847*67e74705SXin Li }
2848*67e74705SXin Li
2849*67e74705SXin Li // FIXME: diagnose the other way around?
2850*67e74705SXin Li if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2851*67e74705SXin Li NewTypeInfo = NewTypeInfo.withNoReturn(true);
2852*67e74705SXin Li RequiresAdjustment = true;
2853*67e74705SXin Li }
2854*67e74705SXin Li
2855*67e74705SXin Li // Merge regparm attribute.
2856*67e74705SXin Li if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2857*67e74705SXin Li OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2858*67e74705SXin Li if (NewTypeInfo.getHasRegParm()) {
2859*67e74705SXin Li Diag(New->getLocation(), diag::err_regparm_mismatch)
2860*67e74705SXin Li << NewType->getRegParmType()
2861*67e74705SXin Li << OldType->getRegParmType();
2862*67e74705SXin Li Diag(OldLocation, diag::note_previous_declaration);
2863*67e74705SXin Li return true;
2864*67e74705SXin Li }
2865*67e74705SXin Li
2866*67e74705SXin Li NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2867*67e74705SXin Li RequiresAdjustment = true;
2868*67e74705SXin Li }
2869*67e74705SXin Li
2870*67e74705SXin Li // Merge ns_returns_retained attribute.
2871*67e74705SXin Li if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2872*67e74705SXin Li if (NewTypeInfo.getProducesResult()) {
2873*67e74705SXin Li Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2874*67e74705SXin Li Diag(OldLocation, diag::note_previous_declaration);
2875*67e74705SXin Li return true;
2876*67e74705SXin Li }
2877*67e74705SXin Li
2878*67e74705SXin Li NewTypeInfo = NewTypeInfo.withProducesResult(true);
2879*67e74705SXin Li RequiresAdjustment = true;
2880*67e74705SXin Li }
2881*67e74705SXin Li
2882*67e74705SXin Li if (RequiresAdjustment) {
2883*67e74705SXin Li const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2884*67e74705SXin Li AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2885*67e74705SXin Li New->setType(QualType(AdjustedType, 0));
2886*67e74705SXin Li NewQType = Context.getCanonicalType(New->getType());
2887*67e74705SXin Li NewType = cast<FunctionType>(NewQType);
2888*67e74705SXin Li }
2889*67e74705SXin Li
2890*67e74705SXin Li // If this redeclaration makes the function inline, we may need to add it to
2891*67e74705SXin Li // UndefinedButUsed.
2892*67e74705SXin Li if (!Old->isInlined() && New->isInlined() &&
2893*67e74705SXin Li !New->hasAttr<GNUInlineAttr>() &&
2894*67e74705SXin Li !getLangOpts().GNUInline &&
2895*67e74705SXin Li Old->isUsed(false) &&
2896*67e74705SXin Li !Old->isDefined() && !New->isThisDeclarationADefinition())
2897*67e74705SXin Li UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2898*67e74705SXin Li SourceLocation()));
2899*67e74705SXin Li
2900*67e74705SXin Li // If this redeclaration makes it newly gnu_inline, we don't want to warn
2901*67e74705SXin Li // about it.
2902*67e74705SXin Li if (New->hasAttr<GNUInlineAttr>() &&
2903*67e74705SXin Li Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2904*67e74705SXin Li UndefinedButUsed.erase(Old->getCanonicalDecl());
2905*67e74705SXin Li }
2906*67e74705SXin Li
2907*67e74705SXin Li // If pass_object_size params don't match up perfectly, this isn't a valid
2908*67e74705SXin Li // redeclaration.
2909*67e74705SXin Li if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2910*67e74705SXin Li !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2911*67e74705SXin Li Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2912*67e74705SXin Li << New->getDeclName();
2913*67e74705SXin Li Diag(OldLocation, PrevDiag) << Old << Old->getType();
2914*67e74705SXin Li return true;
2915*67e74705SXin Li }
2916*67e74705SXin Li
2917*67e74705SXin Li if (getLangOpts().CPlusPlus) {
2918*67e74705SXin Li // (C++98 13.1p2):
2919*67e74705SXin Li // Certain function declarations cannot be overloaded:
2920*67e74705SXin Li // -- Function declarations that differ only in the return type
2921*67e74705SXin Li // cannot be overloaded.
2922*67e74705SXin Li
2923*67e74705SXin Li // Go back to the type source info to compare the declared return types,
2924*67e74705SXin Li // per C++1y [dcl.type.auto]p13:
2925*67e74705SXin Li // Redeclarations or specializations of a function or function template
2926*67e74705SXin Li // with a declared return type that uses a placeholder type shall also
2927*67e74705SXin Li // use that placeholder, not a deduced type.
2928*67e74705SXin Li QualType OldDeclaredReturnType =
2929*67e74705SXin Li (Old->getTypeSourceInfo()
2930*67e74705SXin Li ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2931*67e74705SXin Li : OldType)->getReturnType();
2932*67e74705SXin Li QualType NewDeclaredReturnType =
2933*67e74705SXin Li (New->getTypeSourceInfo()
2934*67e74705SXin Li ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2935*67e74705SXin Li : NewType)->getReturnType();
2936*67e74705SXin Li QualType ResQT;
2937*67e74705SXin Li if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2938*67e74705SXin Li !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2939*67e74705SXin Li New->isLocalExternDecl())) {
2940*67e74705SXin Li if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2941*67e74705SXin Li OldDeclaredReturnType->isObjCObjectPointerType())
2942*67e74705SXin Li ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2943*67e74705SXin Li if (ResQT.isNull()) {
2944*67e74705SXin Li if (New->isCXXClassMember() && New->isOutOfLine())
2945*67e74705SXin Li Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2946*67e74705SXin Li << New << New->getReturnTypeSourceRange();
2947*67e74705SXin Li else
2948*67e74705SXin Li Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2949*67e74705SXin Li << New->getReturnTypeSourceRange();
2950*67e74705SXin Li Diag(OldLocation, PrevDiag) << Old << Old->getType()
2951*67e74705SXin Li << Old->getReturnTypeSourceRange();
2952*67e74705SXin Li return true;
2953*67e74705SXin Li }
2954*67e74705SXin Li else
2955*67e74705SXin Li NewQType = ResQT;
2956*67e74705SXin Li }
2957*67e74705SXin Li
2958*67e74705SXin Li QualType OldReturnType = OldType->getReturnType();
2959*67e74705SXin Li QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2960*67e74705SXin Li if (OldReturnType != NewReturnType) {
2961*67e74705SXin Li // If this function has a deduced return type and has already been
2962*67e74705SXin Li // defined, copy the deduced value from the old declaration.
2963*67e74705SXin Li AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2964*67e74705SXin Li if (OldAT && OldAT->isDeduced()) {
2965*67e74705SXin Li New->setType(
2966*67e74705SXin Li SubstAutoType(New->getType(),
2967*67e74705SXin Li OldAT->isDependentType() ? Context.DependentTy
2968*67e74705SXin Li : OldAT->getDeducedType()));
2969*67e74705SXin Li NewQType = Context.getCanonicalType(
2970*67e74705SXin Li SubstAutoType(NewQType,
2971*67e74705SXin Li OldAT->isDependentType() ? Context.DependentTy
2972*67e74705SXin Li : OldAT->getDeducedType()));
2973*67e74705SXin Li }
2974*67e74705SXin Li }
2975*67e74705SXin Li
2976*67e74705SXin Li const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2977*67e74705SXin Li CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2978*67e74705SXin Li if (OldMethod && NewMethod) {
2979*67e74705SXin Li // Preserve triviality.
2980*67e74705SXin Li NewMethod->setTrivial(OldMethod->isTrivial());
2981*67e74705SXin Li
2982*67e74705SXin Li // MSVC allows explicit template specialization at class scope:
2983*67e74705SXin Li // 2 CXXMethodDecls referring to the same function will be injected.
2984*67e74705SXin Li // We don't want a redeclaration error.
2985*67e74705SXin Li bool IsClassScopeExplicitSpecialization =
2986*67e74705SXin Li OldMethod->isFunctionTemplateSpecialization() &&
2987*67e74705SXin Li NewMethod->isFunctionTemplateSpecialization();
2988*67e74705SXin Li bool isFriend = NewMethod->getFriendObjectKind();
2989*67e74705SXin Li
2990*67e74705SXin Li if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2991*67e74705SXin Li !IsClassScopeExplicitSpecialization) {
2992*67e74705SXin Li // -- Member function declarations with the same name and the
2993*67e74705SXin Li // same parameter types cannot be overloaded if any of them
2994*67e74705SXin Li // is a static member function declaration.
2995*67e74705SXin Li if (OldMethod->isStatic() != NewMethod->isStatic()) {
2996*67e74705SXin Li Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2997*67e74705SXin Li Diag(OldLocation, PrevDiag) << Old << Old->getType();
2998*67e74705SXin Li return true;
2999*67e74705SXin Li }
3000*67e74705SXin Li
3001*67e74705SXin Li // C++ [class.mem]p1:
3002*67e74705SXin Li // [...] A member shall not be declared twice in the
3003*67e74705SXin Li // member-specification, except that a nested class or member
3004*67e74705SXin Li // class template can be declared and then later defined.
3005*67e74705SXin Li if (ActiveTemplateInstantiations.empty()) {
3006*67e74705SXin Li unsigned NewDiag;
3007*67e74705SXin Li if (isa<CXXConstructorDecl>(OldMethod))
3008*67e74705SXin Li NewDiag = diag::err_constructor_redeclared;
3009*67e74705SXin Li else if (isa<CXXDestructorDecl>(NewMethod))
3010*67e74705SXin Li NewDiag = diag::err_destructor_redeclared;
3011*67e74705SXin Li else if (isa<CXXConversionDecl>(NewMethod))
3012*67e74705SXin Li NewDiag = diag::err_conv_function_redeclared;
3013*67e74705SXin Li else
3014*67e74705SXin Li NewDiag = diag::err_member_redeclared;
3015*67e74705SXin Li
3016*67e74705SXin Li Diag(New->getLocation(), NewDiag);
3017*67e74705SXin Li } else {
3018*67e74705SXin Li Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3019*67e74705SXin Li << New << New->getType();
3020*67e74705SXin Li }
3021*67e74705SXin Li Diag(OldLocation, PrevDiag) << Old << Old->getType();
3022*67e74705SXin Li return true;
3023*67e74705SXin Li
3024*67e74705SXin Li // Complain if this is an explicit declaration of a special
3025*67e74705SXin Li // member that was initially declared implicitly.
3026*67e74705SXin Li //
3027*67e74705SXin Li // As an exception, it's okay to befriend such methods in order
3028*67e74705SXin Li // to permit the implicit constructor/destructor/operator calls.
3029*67e74705SXin Li } else if (OldMethod->isImplicit()) {
3030*67e74705SXin Li if (isFriend) {
3031*67e74705SXin Li NewMethod->setImplicit();
3032*67e74705SXin Li } else {
3033*67e74705SXin Li Diag(NewMethod->getLocation(),
3034*67e74705SXin Li diag::err_definition_of_implicitly_declared_member)
3035*67e74705SXin Li << New << getSpecialMember(OldMethod);
3036*67e74705SXin Li return true;
3037*67e74705SXin Li }
3038*67e74705SXin Li } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3039*67e74705SXin Li Diag(NewMethod->getLocation(),
3040*67e74705SXin Li diag::err_definition_of_explicitly_defaulted_member)
3041*67e74705SXin Li << getSpecialMember(OldMethod);
3042*67e74705SXin Li return true;
3043*67e74705SXin Li }
3044*67e74705SXin Li }
3045*67e74705SXin Li
3046*67e74705SXin Li // C++11 [dcl.attr.noreturn]p1:
3047*67e74705SXin Li // The first declaration of a function shall specify the noreturn
3048*67e74705SXin Li // attribute if any declaration of that function specifies the noreturn
3049*67e74705SXin Li // attribute.
3050*67e74705SXin Li const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3051*67e74705SXin Li if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3052*67e74705SXin Li Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3053*67e74705SXin Li Diag(Old->getFirstDecl()->getLocation(),
3054*67e74705SXin Li diag::note_noreturn_missing_first_decl);
3055*67e74705SXin Li }
3056*67e74705SXin Li
3057*67e74705SXin Li // C++11 [dcl.attr.depend]p2:
3058*67e74705SXin Li // The first declaration of a function shall specify the
3059*67e74705SXin Li // carries_dependency attribute for its declarator-id if any declaration
3060*67e74705SXin Li // of the function specifies the carries_dependency attribute.
3061*67e74705SXin Li const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3062*67e74705SXin Li if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3063*67e74705SXin Li Diag(CDA->getLocation(),
3064*67e74705SXin Li diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3065*67e74705SXin Li Diag(Old->getFirstDecl()->getLocation(),
3066*67e74705SXin Li diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3067*67e74705SXin Li }
3068*67e74705SXin Li
3069*67e74705SXin Li // (C++98 8.3.5p3):
3070*67e74705SXin Li // All declarations for a function shall agree exactly in both the
3071*67e74705SXin Li // return type and the parameter-type-list.
3072*67e74705SXin Li // We also want to respect all the extended bits except noreturn.
3073*67e74705SXin Li
3074*67e74705SXin Li // noreturn should now match unless the old type info didn't have it.
3075*67e74705SXin Li QualType OldQTypeForComparison = OldQType;
3076*67e74705SXin Li if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3077*67e74705SXin Li assert(OldQType == QualType(OldType, 0));
3078*67e74705SXin Li const FunctionType *OldTypeForComparison
3079*67e74705SXin Li = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3080*67e74705SXin Li OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3081*67e74705SXin Li assert(OldQTypeForComparison.isCanonical());
3082*67e74705SXin Li }
3083*67e74705SXin Li
3084*67e74705SXin Li if (haveIncompatibleLanguageLinkages(Old, New)) {
3085*67e74705SXin Li // As a special case, retain the language linkage from previous
3086*67e74705SXin Li // declarations of a friend function as an extension.
3087*67e74705SXin Li //
3088*67e74705SXin Li // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3089*67e74705SXin Li // and is useful because there's otherwise no way to specify language
3090*67e74705SXin Li // linkage within class scope.
3091*67e74705SXin Li //
3092*67e74705SXin Li // Check cautiously as the friend object kind isn't yet complete.
3093*67e74705SXin Li if (New->getFriendObjectKind() != Decl::FOK_None) {
3094*67e74705SXin Li Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3095*67e74705SXin Li Diag(OldLocation, PrevDiag);
3096*67e74705SXin Li } else {
3097*67e74705SXin Li Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3098*67e74705SXin Li Diag(OldLocation, PrevDiag);
3099*67e74705SXin Li return true;
3100*67e74705SXin Li }
3101*67e74705SXin Li }
3102*67e74705SXin Li
3103*67e74705SXin Li if (OldQTypeForComparison == NewQType)
3104*67e74705SXin Li return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3105*67e74705SXin Li
3106*67e74705SXin Li if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3107*67e74705SXin Li New->isLocalExternDecl()) {
3108*67e74705SXin Li // It's OK if we couldn't merge types for a local function declaraton
3109*67e74705SXin Li // if either the old or new type is dependent. We'll merge the types
3110*67e74705SXin Li // when we instantiate the function.
3111*67e74705SXin Li return false;
3112*67e74705SXin Li }
3113*67e74705SXin Li
3114*67e74705SXin Li // Fall through for conflicting redeclarations and redefinitions.
3115*67e74705SXin Li }
3116*67e74705SXin Li
3117*67e74705SXin Li // C: Function types need to be compatible, not identical. This handles
3118*67e74705SXin Li // duplicate function decls like "void f(int); void f(enum X);" properly.
3119*67e74705SXin Li if (!getLangOpts().CPlusPlus &&
3120*67e74705SXin Li Context.typesAreCompatible(OldQType, NewQType)) {
3121*67e74705SXin Li const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3122*67e74705SXin Li const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3123*67e74705SXin Li const FunctionProtoType *OldProto = nullptr;
3124*67e74705SXin Li if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3125*67e74705SXin Li (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3126*67e74705SXin Li // The old declaration provided a function prototype, but the
3127*67e74705SXin Li // new declaration does not. Merge in the prototype.
3128*67e74705SXin Li assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3129*67e74705SXin Li SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3130*67e74705SXin Li NewQType =
3131*67e74705SXin Li Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3132*67e74705SXin Li OldProto->getExtProtoInfo());
3133*67e74705SXin Li New->setType(NewQType);
3134*67e74705SXin Li New->setHasInheritedPrototype();
3135*67e74705SXin Li
3136*67e74705SXin Li // Synthesize parameters with the same types.
3137*67e74705SXin Li SmallVector<ParmVarDecl*, 16> Params;
3138*67e74705SXin Li for (const auto &ParamType : OldProto->param_types()) {
3139*67e74705SXin Li ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3140*67e74705SXin Li SourceLocation(), nullptr,
3141*67e74705SXin Li ParamType, /*TInfo=*/nullptr,
3142*67e74705SXin Li SC_None, nullptr);
3143*67e74705SXin Li Param->setScopeInfo(0, Params.size());
3144*67e74705SXin Li Param->setImplicit();
3145*67e74705SXin Li Params.push_back(Param);
3146*67e74705SXin Li }
3147*67e74705SXin Li
3148*67e74705SXin Li New->setParams(Params);
3149*67e74705SXin Li }
3150*67e74705SXin Li
3151*67e74705SXin Li return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3152*67e74705SXin Li }
3153*67e74705SXin Li
3154*67e74705SXin Li // GNU C permits a K&R definition to follow a prototype declaration
3155*67e74705SXin Li // if the declared types of the parameters in the K&R definition
3156*67e74705SXin Li // match the types in the prototype declaration, even when the
3157*67e74705SXin Li // promoted types of the parameters from the K&R definition differ
3158*67e74705SXin Li // from the types in the prototype. GCC then keeps the types from
3159*67e74705SXin Li // the prototype.
3160*67e74705SXin Li //
3161*67e74705SXin Li // If a variadic prototype is followed by a non-variadic K&R definition,
3162*67e74705SXin Li // the K&R definition becomes variadic. This is sort of an edge case, but
3163*67e74705SXin Li // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3164*67e74705SXin Li // C99 6.9.1p8.
3165*67e74705SXin Li if (!getLangOpts().CPlusPlus &&
3166*67e74705SXin Li Old->hasPrototype() && !New->hasPrototype() &&
3167*67e74705SXin Li New->getType()->getAs<FunctionProtoType>() &&
3168*67e74705SXin Li Old->getNumParams() == New->getNumParams()) {
3169*67e74705SXin Li SmallVector<QualType, 16> ArgTypes;
3170*67e74705SXin Li SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3171*67e74705SXin Li const FunctionProtoType *OldProto
3172*67e74705SXin Li = Old->getType()->getAs<FunctionProtoType>();
3173*67e74705SXin Li const FunctionProtoType *NewProto
3174*67e74705SXin Li = New->getType()->getAs<FunctionProtoType>();
3175*67e74705SXin Li
3176*67e74705SXin Li // Determine whether this is the GNU C extension.
3177*67e74705SXin Li QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3178*67e74705SXin Li NewProto->getReturnType());
3179*67e74705SXin Li bool LooseCompatible = !MergedReturn.isNull();
3180*67e74705SXin Li for (unsigned Idx = 0, End = Old->getNumParams();
3181*67e74705SXin Li LooseCompatible && Idx != End; ++Idx) {
3182*67e74705SXin Li ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3183*67e74705SXin Li ParmVarDecl *NewParm = New->getParamDecl(Idx);
3184*67e74705SXin Li if (Context.typesAreCompatible(OldParm->getType(),
3185*67e74705SXin Li NewProto->getParamType(Idx))) {
3186*67e74705SXin Li ArgTypes.push_back(NewParm->getType());
3187*67e74705SXin Li } else if (Context.typesAreCompatible(OldParm->getType(),
3188*67e74705SXin Li NewParm->getType(),
3189*67e74705SXin Li /*CompareUnqualified=*/true)) {
3190*67e74705SXin Li GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3191*67e74705SXin Li NewProto->getParamType(Idx) };
3192*67e74705SXin Li Warnings.push_back(Warn);
3193*67e74705SXin Li ArgTypes.push_back(NewParm->getType());
3194*67e74705SXin Li } else
3195*67e74705SXin Li LooseCompatible = false;
3196*67e74705SXin Li }
3197*67e74705SXin Li
3198*67e74705SXin Li if (LooseCompatible) {
3199*67e74705SXin Li for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3200*67e74705SXin Li Diag(Warnings[Warn].NewParm->getLocation(),
3201*67e74705SXin Li diag::ext_param_promoted_not_compatible_with_prototype)
3202*67e74705SXin Li << Warnings[Warn].PromotedType
3203*67e74705SXin Li << Warnings[Warn].OldParm->getType();
3204*67e74705SXin Li if (Warnings[Warn].OldParm->getLocation().isValid())
3205*67e74705SXin Li Diag(Warnings[Warn].OldParm->getLocation(),
3206*67e74705SXin Li diag::note_previous_declaration);
3207*67e74705SXin Li }
3208*67e74705SXin Li
3209*67e74705SXin Li if (MergeTypeWithOld)
3210*67e74705SXin Li New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3211*67e74705SXin Li OldProto->getExtProtoInfo()));
3212*67e74705SXin Li return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3213*67e74705SXin Li }
3214*67e74705SXin Li
3215*67e74705SXin Li // Fall through to diagnose conflicting types.
3216*67e74705SXin Li }
3217*67e74705SXin Li
3218*67e74705SXin Li // A function that has already been declared has been redeclared or
3219*67e74705SXin Li // defined with a different type; show an appropriate diagnostic.
3220*67e74705SXin Li
3221*67e74705SXin Li // If the previous declaration was an implicitly-generated builtin
3222*67e74705SXin Li // declaration, then at the very least we should use a specialized note.
3223*67e74705SXin Li unsigned BuiltinID;
3224*67e74705SXin Li if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3225*67e74705SXin Li // If it's actually a library-defined builtin function like 'malloc'
3226*67e74705SXin Li // or 'printf', just warn about the incompatible redeclaration.
3227*67e74705SXin Li if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3228*67e74705SXin Li Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3229*67e74705SXin Li Diag(OldLocation, diag::note_previous_builtin_declaration)
3230*67e74705SXin Li << Old << Old->getType();
3231*67e74705SXin Li
3232*67e74705SXin Li // If this is a global redeclaration, just forget hereafter
3233*67e74705SXin Li // about the "builtin-ness" of the function.
3234*67e74705SXin Li //
3235*67e74705SXin Li // Doing this for local extern declarations is problematic. If
3236*67e74705SXin Li // the builtin declaration remains visible, a second invalid
3237*67e74705SXin Li // local declaration will produce a hard error; if it doesn't
3238*67e74705SXin Li // remain visible, a single bogus local redeclaration (which is
3239*67e74705SXin Li // actually only a warning) could break all the downstream code.
3240*67e74705SXin Li if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3241*67e74705SXin Li New->getIdentifier()->revertBuiltin();
3242*67e74705SXin Li
3243*67e74705SXin Li return false;
3244*67e74705SXin Li }
3245*67e74705SXin Li
3246*67e74705SXin Li PrevDiag = diag::note_previous_builtin_declaration;
3247*67e74705SXin Li }
3248*67e74705SXin Li
3249*67e74705SXin Li Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3250*67e74705SXin Li Diag(OldLocation, PrevDiag) << Old << Old->getType();
3251*67e74705SXin Li return true;
3252*67e74705SXin Li }
3253*67e74705SXin Li
3254*67e74705SXin Li /// \brief Completes the merge of two function declarations that are
3255*67e74705SXin Li /// known to be compatible.
3256*67e74705SXin Li ///
3257*67e74705SXin Li /// This routine handles the merging of attributes and other
3258*67e74705SXin Li /// properties of function declarations from the old declaration to
3259*67e74705SXin Li /// the new declaration, once we know that New is in fact a
3260*67e74705SXin Li /// redeclaration of Old.
3261*67e74705SXin Li ///
3262*67e74705SXin Li /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)3263*67e74705SXin Li bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3264*67e74705SXin Li Scope *S, bool MergeTypeWithOld) {
3265*67e74705SXin Li // Merge the attributes
3266*67e74705SXin Li mergeDeclAttributes(New, Old);
3267*67e74705SXin Li
3268*67e74705SXin Li // Merge "pure" flag.
3269*67e74705SXin Li if (Old->isPure())
3270*67e74705SXin Li New->setPure();
3271*67e74705SXin Li
3272*67e74705SXin Li // Merge "used" flag.
3273*67e74705SXin Li if (Old->getMostRecentDecl()->isUsed(false))
3274*67e74705SXin Li New->setIsUsed();
3275*67e74705SXin Li
3276*67e74705SXin Li // Merge attributes from the parameters. These can mismatch with K&R
3277*67e74705SXin Li // declarations.
3278*67e74705SXin Li if (New->getNumParams() == Old->getNumParams())
3279*67e74705SXin Li for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3280*67e74705SXin Li ParmVarDecl *NewParam = New->getParamDecl(i);
3281*67e74705SXin Li ParmVarDecl *OldParam = Old->getParamDecl(i);
3282*67e74705SXin Li mergeParamDeclAttributes(NewParam, OldParam, *this);
3283*67e74705SXin Li mergeParamDeclTypes(NewParam, OldParam, *this);
3284*67e74705SXin Li }
3285*67e74705SXin Li
3286*67e74705SXin Li if (getLangOpts().CPlusPlus)
3287*67e74705SXin Li return MergeCXXFunctionDecl(New, Old, S);
3288*67e74705SXin Li
3289*67e74705SXin Li // Merge the function types so the we get the composite types for the return
3290*67e74705SXin Li // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3291*67e74705SXin Li // was visible.
3292*67e74705SXin Li QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3293*67e74705SXin Li if (!Merged.isNull() && MergeTypeWithOld)
3294*67e74705SXin Li New->setType(Merged);
3295*67e74705SXin Li
3296*67e74705SXin Li return false;
3297*67e74705SXin Li }
3298*67e74705SXin Li
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)3299*67e74705SXin Li void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3300*67e74705SXin Li ObjCMethodDecl *oldMethod) {
3301*67e74705SXin Li // Merge the attributes, including deprecated/unavailable
3302*67e74705SXin Li AvailabilityMergeKind MergeKind =
3303*67e74705SXin Li isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3304*67e74705SXin Li ? AMK_ProtocolImplementation
3305*67e74705SXin Li : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3306*67e74705SXin Li : AMK_Override;
3307*67e74705SXin Li
3308*67e74705SXin Li mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3309*67e74705SXin Li
3310*67e74705SXin Li // Merge attributes from the parameters.
3311*67e74705SXin Li ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3312*67e74705SXin Li oe = oldMethod->param_end();
3313*67e74705SXin Li for (ObjCMethodDecl::param_iterator
3314*67e74705SXin Li ni = newMethod->param_begin(), ne = newMethod->param_end();
3315*67e74705SXin Li ni != ne && oi != oe; ++ni, ++oi)
3316*67e74705SXin Li mergeParamDeclAttributes(*ni, *oi, *this);
3317*67e74705SXin Li
3318*67e74705SXin Li CheckObjCMethodOverride(newMethod, oldMethod);
3319*67e74705SXin Li }
3320*67e74705SXin Li
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)3321*67e74705SXin Li static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3322*67e74705SXin Li assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3323*67e74705SXin Li
3324*67e74705SXin Li S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3325*67e74705SXin Li ? diag::err_redefinition_different_type
3326*67e74705SXin Li : diag::err_redeclaration_different_type)
3327*67e74705SXin Li << New->getDeclName() << New->getType() << Old->getType();
3328*67e74705SXin Li
3329*67e74705SXin Li diag::kind PrevDiag;
3330*67e74705SXin Li SourceLocation OldLocation;
3331*67e74705SXin Li std::tie(PrevDiag, OldLocation)
3332*67e74705SXin Li = getNoteDiagForInvalidRedeclaration(Old, New);
3333*67e74705SXin Li S.Diag(OldLocation, PrevDiag);
3334*67e74705SXin Li New->setInvalidDecl();
3335*67e74705SXin Li }
3336*67e74705SXin Li
3337*67e74705SXin Li /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3338*67e74705SXin Li /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3339*67e74705SXin Li /// emitting diagnostics as appropriate.
3340*67e74705SXin Li ///
3341*67e74705SXin Li /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3342*67e74705SXin Li /// to here in AddInitializerToDecl. We can't check them before the initializer
3343*67e74705SXin Li /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)3344*67e74705SXin Li void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3345*67e74705SXin Li bool MergeTypeWithOld) {
3346*67e74705SXin Li if (New->isInvalidDecl() || Old->isInvalidDecl())
3347*67e74705SXin Li return;
3348*67e74705SXin Li
3349*67e74705SXin Li QualType MergedT;
3350*67e74705SXin Li if (getLangOpts().CPlusPlus) {
3351*67e74705SXin Li if (New->getType()->isUndeducedType()) {
3352*67e74705SXin Li // We don't know what the new type is until the initializer is attached.
3353*67e74705SXin Li return;
3354*67e74705SXin Li } else if (Context.hasSameType(New->getType(), Old->getType())) {
3355*67e74705SXin Li // These could still be something that needs exception specs checked.
3356*67e74705SXin Li return MergeVarDeclExceptionSpecs(New, Old);
3357*67e74705SXin Li }
3358*67e74705SXin Li // C++ [basic.link]p10:
3359*67e74705SXin Li // [...] the types specified by all declarations referring to a given
3360*67e74705SXin Li // object or function shall be identical, except that declarations for an
3361*67e74705SXin Li // array object can specify array types that differ by the presence or
3362*67e74705SXin Li // absence of a major array bound (8.3.4).
3363*67e74705SXin Li else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3364*67e74705SXin Li const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3365*67e74705SXin Li const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3366*67e74705SXin Li
3367*67e74705SXin Li // We are merging a variable declaration New into Old. If it has an array
3368*67e74705SXin Li // bound, and that bound differs from Old's bound, we should diagnose the
3369*67e74705SXin Li // mismatch.
3370*67e74705SXin Li if (!NewArray->isIncompleteArrayType()) {
3371*67e74705SXin Li for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3372*67e74705SXin Li PrevVD = PrevVD->getPreviousDecl()) {
3373*67e74705SXin Li const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3374*67e74705SXin Li if (PrevVDTy->isIncompleteArrayType())
3375*67e74705SXin Li continue;
3376*67e74705SXin Li
3377*67e74705SXin Li if (!Context.hasSameType(NewArray, PrevVDTy))
3378*67e74705SXin Li return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3379*67e74705SXin Li }
3380*67e74705SXin Li }
3381*67e74705SXin Li
3382*67e74705SXin Li if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3383*67e74705SXin Li if (Context.hasSameType(OldArray->getElementType(),
3384*67e74705SXin Li NewArray->getElementType()))
3385*67e74705SXin Li MergedT = New->getType();
3386*67e74705SXin Li }
3387*67e74705SXin Li // FIXME: Check visibility. New is hidden but has a complete type. If New
3388*67e74705SXin Li // has no array bound, it should not inherit one from Old, if Old is not
3389*67e74705SXin Li // visible.
3390*67e74705SXin Li else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3391*67e74705SXin Li if (Context.hasSameType(OldArray->getElementType(),
3392*67e74705SXin Li NewArray->getElementType()))
3393*67e74705SXin Li MergedT = Old->getType();
3394*67e74705SXin Li }
3395*67e74705SXin Li }
3396*67e74705SXin Li else if (New->getType()->isObjCObjectPointerType() &&
3397*67e74705SXin Li Old->getType()->isObjCObjectPointerType()) {
3398*67e74705SXin Li MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3399*67e74705SXin Li Old->getType());
3400*67e74705SXin Li }
3401*67e74705SXin Li } else {
3402*67e74705SXin Li // C 6.2.7p2:
3403*67e74705SXin Li // All declarations that refer to the same object or function shall have
3404*67e74705SXin Li // compatible type.
3405*67e74705SXin Li MergedT = Context.mergeTypes(New->getType(), Old->getType());
3406*67e74705SXin Li }
3407*67e74705SXin Li if (MergedT.isNull()) {
3408*67e74705SXin Li // It's OK if we couldn't merge types if either type is dependent, for a
3409*67e74705SXin Li // block-scope variable. In other cases (static data members of class
3410*67e74705SXin Li // templates, variable templates, ...), we require the types to be
3411*67e74705SXin Li // equivalent.
3412*67e74705SXin Li // FIXME: The C++ standard doesn't say anything about this.
3413*67e74705SXin Li if ((New->getType()->isDependentType() ||
3414*67e74705SXin Li Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3415*67e74705SXin Li // If the old type was dependent, we can't merge with it, so the new type
3416*67e74705SXin Li // becomes dependent for now. We'll reproduce the original type when we
3417*67e74705SXin Li // instantiate the TypeSourceInfo for the variable.
3418*67e74705SXin Li if (!New->getType()->isDependentType() && MergeTypeWithOld)
3419*67e74705SXin Li New->setType(Context.DependentTy);
3420*67e74705SXin Li return;
3421*67e74705SXin Li }
3422*67e74705SXin Li return diagnoseVarDeclTypeMismatch(*this, New, Old);
3423*67e74705SXin Li }
3424*67e74705SXin Li
3425*67e74705SXin Li // Don't actually update the type on the new declaration if the old
3426*67e74705SXin Li // declaration was an extern declaration in a different scope.
3427*67e74705SXin Li if (MergeTypeWithOld)
3428*67e74705SXin Li New->setType(MergedT);
3429*67e74705SXin Li }
3430*67e74705SXin Li
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)3431*67e74705SXin Li static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3432*67e74705SXin Li LookupResult &Previous) {
3433*67e74705SXin Li // C11 6.2.7p4:
3434*67e74705SXin Li // For an identifier with internal or external linkage declared
3435*67e74705SXin Li // in a scope in which a prior declaration of that identifier is
3436*67e74705SXin Li // visible, if the prior declaration specifies internal or
3437*67e74705SXin Li // external linkage, the type of the identifier at the later
3438*67e74705SXin Li // declaration becomes the composite type.
3439*67e74705SXin Li //
3440*67e74705SXin Li // If the variable isn't visible, we do not merge with its type.
3441*67e74705SXin Li if (Previous.isShadowed())
3442*67e74705SXin Li return false;
3443*67e74705SXin Li
3444*67e74705SXin Li if (S.getLangOpts().CPlusPlus) {
3445*67e74705SXin Li // C++11 [dcl.array]p3:
3446*67e74705SXin Li // If there is a preceding declaration of the entity in the same
3447*67e74705SXin Li // scope in which the bound was specified, an omitted array bound
3448*67e74705SXin Li // is taken to be the same as in that earlier declaration.
3449*67e74705SXin Li return NewVD->isPreviousDeclInSameBlockScope() ||
3450*67e74705SXin Li (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3451*67e74705SXin Li !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3452*67e74705SXin Li } else {
3453*67e74705SXin Li // If the old declaration was function-local, don't merge with its
3454*67e74705SXin Li // type unless we're in the same function.
3455*67e74705SXin Li return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3456*67e74705SXin Li OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3457*67e74705SXin Li }
3458*67e74705SXin Li }
3459*67e74705SXin Li
3460*67e74705SXin Li /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3461*67e74705SXin Li /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3462*67e74705SXin Li /// situation, merging decls or emitting diagnostics as appropriate.
3463*67e74705SXin Li ///
3464*67e74705SXin Li /// Tentative definition rules (C99 6.9.2p2) are checked by
3465*67e74705SXin Li /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3466*67e74705SXin Li /// definitions here, since the initializer hasn't been attached.
3467*67e74705SXin Li ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)3468*67e74705SXin Li void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3469*67e74705SXin Li // If the new decl is already invalid, don't do any other checking.
3470*67e74705SXin Li if (New->isInvalidDecl())
3471*67e74705SXin Li return;
3472*67e74705SXin Li
3473*67e74705SXin Li if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3474*67e74705SXin Li return;
3475*67e74705SXin Li
3476*67e74705SXin Li VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3477*67e74705SXin Li
3478*67e74705SXin Li // Verify the old decl was also a variable or variable template.
3479*67e74705SXin Li VarDecl *Old = nullptr;
3480*67e74705SXin Li VarTemplateDecl *OldTemplate = nullptr;
3481*67e74705SXin Li if (Previous.isSingleResult()) {
3482*67e74705SXin Li if (NewTemplate) {
3483*67e74705SXin Li OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3484*67e74705SXin Li Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3485*67e74705SXin Li
3486*67e74705SXin Li if (auto *Shadow =
3487*67e74705SXin Li dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3488*67e74705SXin Li if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3489*67e74705SXin Li return New->setInvalidDecl();
3490*67e74705SXin Li } else {
3491*67e74705SXin Li Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3492*67e74705SXin Li
3493*67e74705SXin Li if (auto *Shadow =
3494*67e74705SXin Li dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3495*67e74705SXin Li if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3496*67e74705SXin Li return New->setInvalidDecl();
3497*67e74705SXin Li }
3498*67e74705SXin Li }
3499*67e74705SXin Li if (!Old) {
3500*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition_different_kind)
3501*67e74705SXin Li << New->getDeclName();
3502*67e74705SXin Li Diag(Previous.getRepresentativeDecl()->getLocation(),
3503*67e74705SXin Li diag::note_previous_definition);
3504*67e74705SXin Li return New->setInvalidDecl();
3505*67e74705SXin Li }
3506*67e74705SXin Li
3507*67e74705SXin Li // Ensure the template parameters are compatible.
3508*67e74705SXin Li if (NewTemplate &&
3509*67e74705SXin Li !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3510*67e74705SXin Li OldTemplate->getTemplateParameters(),
3511*67e74705SXin Li /*Complain=*/true, TPL_TemplateMatch))
3512*67e74705SXin Li return New->setInvalidDecl();
3513*67e74705SXin Li
3514*67e74705SXin Li // C++ [class.mem]p1:
3515*67e74705SXin Li // A member shall not be declared twice in the member-specification [...]
3516*67e74705SXin Li //
3517*67e74705SXin Li // Here, we need only consider static data members.
3518*67e74705SXin Li if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3519*67e74705SXin Li Diag(New->getLocation(), diag::err_duplicate_member)
3520*67e74705SXin Li << New->getIdentifier();
3521*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_declaration);
3522*67e74705SXin Li New->setInvalidDecl();
3523*67e74705SXin Li }
3524*67e74705SXin Li
3525*67e74705SXin Li mergeDeclAttributes(New, Old);
3526*67e74705SXin Li // Warn if an already-declared variable is made a weak_import in a subsequent
3527*67e74705SXin Li // declaration
3528*67e74705SXin Li if (New->hasAttr<WeakImportAttr>() &&
3529*67e74705SXin Li Old->getStorageClass() == SC_None &&
3530*67e74705SXin Li !Old->hasAttr<WeakImportAttr>()) {
3531*67e74705SXin Li Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3532*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
3533*67e74705SXin Li // Remove weak_import attribute on new declaration.
3534*67e74705SXin Li New->dropAttr<WeakImportAttr>();
3535*67e74705SXin Li }
3536*67e74705SXin Li
3537*67e74705SXin Li if (New->hasAttr<InternalLinkageAttr>() &&
3538*67e74705SXin Li !Old->hasAttr<InternalLinkageAttr>()) {
3539*67e74705SXin Li Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3540*67e74705SXin Li << New->getDeclName();
3541*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_definition);
3542*67e74705SXin Li New->dropAttr<InternalLinkageAttr>();
3543*67e74705SXin Li }
3544*67e74705SXin Li
3545*67e74705SXin Li // Merge the types.
3546*67e74705SXin Li VarDecl *MostRecent = Old->getMostRecentDecl();
3547*67e74705SXin Li if (MostRecent != Old) {
3548*67e74705SXin Li MergeVarDeclTypes(New, MostRecent,
3549*67e74705SXin Li mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3550*67e74705SXin Li if (New->isInvalidDecl())
3551*67e74705SXin Li return;
3552*67e74705SXin Li }
3553*67e74705SXin Li
3554*67e74705SXin Li MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3555*67e74705SXin Li if (New->isInvalidDecl())
3556*67e74705SXin Li return;
3557*67e74705SXin Li
3558*67e74705SXin Li diag::kind PrevDiag;
3559*67e74705SXin Li SourceLocation OldLocation;
3560*67e74705SXin Li std::tie(PrevDiag, OldLocation) =
3561*67e74705SXin Li getNoteDiagForInvalidRedeclaration(Old, New);
3562*67e74705SXin Li
3563*67e74705SXin Li // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3564*67e74705SXin Li if (New->getStorageClass() == SC_Static &&
3565*67e74705SXin Li !New->isStaticDataMember() &&
3566*67e74705SXin Li Old->hasExternalFormalLinkage()) {
3567*67e74705SXin Li if (getLangOpts().MicrosoftExt) {
3568*67e74705SXin Li Diag(New->getLocation(), diag::ext_static_non_static)
3569*67e74705SXin Li << New->getDeclName();
3570*67e74705SXin Li Diag(OldLocation, PrevDiag);
3571*67e74705SXin Li } else {
3572*67e74705SXin Li Diag(New->getLocation(), diag::err_static_non_static)
3573*67e74705SXin Li << New->getDeclName();
3574*67e74705SXin Li Diag(OldLocation, PrevDiag);
3575*67e74705SXin Li return New->setInvalidDecl();
3576*67e74705SXin Li }
3577*67e74705SXin Li }
3578*67e74705SXin Li // C99 6.2.2p4:
3579*67e74705SXin Li // For an identifier declared with the storage-class specifier
3580*67e74705SXin Li // extern in a scope in which a prior declaration of that
3581*67e74705SXin Li // identifier is visible,23) if the prior declaration specifies
3582*67e74705SXin Li // internal or external linkage, the linkage of the identifier at
3583*67e74705SXin Li // the later declaration is the same as the linkage specified at
3584*67e74705SXin Li // the prior declaration. If no prior declaration is visible, or
3585*67e74705SXin Li // if the prior declaration specifies no linkage, then the
3586*67e74705SXin Li // identifier has external linkage.
3587*67e74705SXin Li if (New->hasExternalStorage() && Old->hasLinkage())
3588*67e74705SXin Li /* Okay */;
3589*67e74705SXin Li else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3590*67e74705SXin Li !New->isStaticDataMember() &&
3591*67e74705SXin Li Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3592*67e74705SXin Li Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3593*67e74705SXin Li Diag(OldLocation, PrevDiag);
3594*67e74705SXin Li return New->setInvalidDecl();
3595*67e74705SXin Li }
3596*67e74705SXin Li
3597*67e74705SXin Li // Check if extern is followed by non-extern and vice-versa.
3598*67e74705SXin Li if (New->hasExternalStorage() &&
3599*67e74705SXin Li !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3600*67e74705SXin Li Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3601*67e74705SXin Li Diag(OldLocation, PrevDiag);
3602*67e74705SXin Li return New->setInvalidDecl();
3603*67e74705SXin Li }
3604*67e74705SXin Li if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3605*67e74705SXin Li !New->hasExternalStorage()) {
3606*67e74705SXin Li Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3607*67e74705SXin Li Diag(OldLocation, PrevDiag);
3608*67e74705SXin Li return New->setInvalidDecl();
3609*67e74705SXin Li }
3610*67e74705SXin Li
3611*67e74705SXin Li // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3612*67e74705SXin Li
3613*67e74705SXin Li // FIXME: The test for external storage here seems wrong? We still
3614*67e74705SXin Li // need to check for mismatches.
3615*67e74705SXin Li if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3616*67e74705SXin Li // Don't complain about out-of-line definitions of static members.
3617*67e74705SXin Li !(Old->getLexicalDeclContext()->isRecord() &&
3618*67e74705SXin Li !New->getLexicalDeclContext()->isRecord())) {
3619*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3620*67e74705SXin Li Diag(OldLocation, PrevDiag);
3621*67e74705SXin Li return New->setInvalidDecl();
3622*67e74705SXin Li }
3623*67e74705SXin Li
3624*67e74705SXin Li if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3625*67e74705SXin Li if (VarDecl *Def = Old->getDefinition()) {
3626*67e74705SXin Li // C++1z [dcl.fcn.spec]p4:
3627*67e74705SXin Li // If the definition of a variable appears in a translation unit before
3628*67e74705SXin Li // its first declaration as inline, the program is ill-formed.
3629*67e74705SXin Li Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3630*67e74705SXin Li Diag(Def->getLocation(), diag::note_previous_definition);
3631*67e74705SXin Li }
3632*67e74705SXin Li }
3633*67e74705SXin Li
3634*67e74705SXin Li // If this redeclaration makes the function inline, we may need to add it to
3635*67e74705SXin Li // UndefinedButUsed.
3636*67e74705SXin Li if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3637*67e74705SXin Li !Old->getDefinition() && !New->isThisDeclarationADefinition())
3638*67e74705SXin Li UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3639*67e74705SXin Li SourceLocation()));
3640*67e74705SXin Li
3641*67e74705SXin Li if (New->getTLSKind() != Old->getTLSKind()) {
3642*67e74705SXin Li if (!Old->getTLSKind()) {
3643*67e74705SXin Li Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3644*67e74705SXin Li Diag(OldLocation, PrevDiag);
3645*67e74705SXin Li } else if (!New->getTLSKind()) {
3646*67e74705SXin Li Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3647*67e74705SXin Li Diag(OldLocation, PrevDiag);
3648*67e74705SXin Li } else {
3649*67e74705SXin Li // Do not allow redeclaration to change the variable between requiring
3650*67e74705SXin Li // static and dynamic initialization.
3651*67e74705SXin Li // FIXME: GCC allows this, but uses the TLS keyword on the first
3652*67e74705SXin Li // declaration to determine the kind. Do we need to be compatible here?
3653*67e74705SXin Li Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3654*67e74705SXin Li << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3655*67e74705SXin Li Diag(OldLocation, PrevDiag);
3656*67e74705SXin Li }
3657*67e74705SXin Li }
3658*67e74705SXin Li
3659*67e74705SXin Li // C++ doesn't have tentative definitions, so go right ahead and check here.
3660*67e74705SXin Li VarDecl *Def;
3661*67e74705SXin Li if (getLangOpts().CPlusPlus &&
3662*67e74705SXin Li New->isThisDeclarationADefinition() == VarDecl::Definition &&
3663*67e74705SXin Li (Def = Old->getDefinition())) {
3664*67e74705SXin Li NamedDecl *Hidden = nullptr;
3665*67e74705SXin Li if (!hasVisibleDefinition(Def, &Hidden) &&
3666*67e74705SXin Li (New->getFormalLinkage() == InternalLinkage ||
3667*67e74705SXin Li New->getDescribedVarTemplate() ||
3668*67e74705SXin Li New->getNumTemplateParameterLists() ||
3669*67e74705SXin Li New->getDeclContext()->isDependentContext())) {
3670*67e74705SXin Li // The previous definition is hidden, and multiple definitions are
3671*67e74705SXin Li // permitted (in separate TUs). Form another definition of it.
3672*67e74705SXin Li } else if (Old->isStaticDataMember() &&
3673*67e74705SXin Li Old->getCanonicalDecl()->isInline() &&
3674*67e74705SXin Li Old->getCanonicalDecl()->isConstexpr()) {
3675*67e74705SXin Li // This definition won't be a definition any more once it's been merged.
3676*67e74705SXin Li Diag(New->getLocation(),
3677*67e74705SXin Li diag::warn_deprecated_redundant_constexpr_static_def);
3678*67e74705SXin Li } else {
3679*67e74705SXin Li Diag(New->getLocation(), diag::err_redefinition) << New;
3680*67e74705SXin Li Diag(Def->getLocation(), diag::note_previous_definition);
3681*67e74705SXin Li New->setInvalidDecl();
3682*67e74705SXin Li return;
3683*67e74705SXin Li }
3684*67e74705SXin Li }
3685*67e74705SXin Li
3686*67e74705SXin Li if (haveIncompatibleLanguageLinkages(Old, New)) {
3687*67e74705SXin Li Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3688*67e74705SXin Li Diag(OldLocation, PrevDiag);
3689*67e74705SXin Li New->setInvalidDecl();
3690*67e74705SXin Li return;
3691*67e74705SXin Li }
3692*67e74705SXin Li
3693*67e74705SXin Li // Merge "used" flag.
3694*67e74705SXin Li if (Old->getMostRecentDecl()->isUsed(false))
3695*67e74705SXin Li New->setIsUsed();
3696*67e74705SXin Li
3697*67e74705SXin Li // Keep a chain of previous declarations.
3698*67e74705SXin Li New->setPreviousDecl(Old);
3699*67e74705SXin Li if (NewTemplate)
3700*67e74705SXin Li NewTemplate->setPreviousDecl(OldTemplate);
3701*67e74705SXin Li
3702*67e74705SXin Li // Inherit access appropriately.
3703*67e74705SXin Li New->setAccess(Old->getAccess());
3704*67e74705SXin Li if (NewTemplate)
3705*67e74705SXin Li NewTemplate->setAccess(New->getAccess());
3706*67e74705SXin Li
3707*67e74705SXin Li if (Old->isInline())
3708*67e74705SXin Li New->setImplicitlyInline();
3709*67e74705SXin Li }
3710*67e74705SXin Li
3711*67e74705SXin Li /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3712*67e74705SXin Li /// no declarator (e.g. "struct foo;") is parsed.
3713*67e74705SXin Li Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,RecordDecl * & AnonRecord)3714*67e74705SXin Li Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3715*67e74705SXin Li RecordDecl *&AnonRecord) {
3716*67e74705SXin Li return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3717*67e74705SXin Li AnonRecord);
3718*67e74705SXin Li }
3719*67e74705SXin Li
3720*67e74705SXin Li // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3721*67e74705SXin Li // disambiguate entities defined in different scopes.
3722*67e74705SXin Li // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3723*67e74705SXin Li // compatibility.
3724*67e74705SXin Li // We will pick our mangling number depending on which version of MSVC is being
3725*67e74705SXin Li // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)3726*67e74705SXin Li static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3727*67e74705SXin Li return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3728*67e74705SXin Li ? S->getMSCurManglingNumber()
3729*67e74705SXin Li : S->getMSLastManglingNumber();
3730*67e74705SXin Li }
3731*67e74705SXin Li
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)3732*67e74705SXin Li void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3733*67e74705SXin Li if (!Context.getLangOpts().CPlusPlus)
3734*67e74705SXin Li return;
3735*67e74705SXin Li
3736*67e74705SXin Li if (isa<CXXRecordDecl>(Tag->getParent())) {
3737*67e74705SXin Li // If this tag is the direct child of a class, number it if
3738*67e74705SXin Li // it is anonymous.
3739*67e74705SXin Li if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3740*67e74705SXin Li return;
3741*67e74705SXin Li MangleNumberingContext &MCtx =
3742*67e74705SXin Li Context.getManglingNumberContext(Tag->getParent());
3743*67e74705SXin Li Context.setManglingNumber(
3744*67e74705SXin Li Tag, MCtx.getManglingNumber(
3745*67e74705SXin Li Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3746*67e74705SXin Li return;
3747*67e74705SXin Li }
3748*67e74705SXin Li
3749*67e74705SXin Li // If this tag isn't a direct child of a class, number it if it is local.
3750*67e74705SXin Li Decl *ManglingContextDecl;
3751*67e74705SXin Li if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3752*67e74705SXin Li Tag->getDeclContext(), ManglingContextDecl)) {
3753*67e74705SXin Li Context.setManglingNumber(
3754*67e74705SXin Li Tag, MCtx->getManglingNumber(
3755*67e74705SXin Li Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3756*67e74705SXin Li }
3757*67e74705SXin Li }
3758*67e74705SXin Li
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)3759*67e74705SXin Li void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3760*67e74705SXin Li TypedefNameDecl *NewTD) {
3761*67e74705SXin Li if (TagFromDeclSpec->isInvalidDecl())
3762*67e74705SXin Li return;
3763*67e74705SXin Li
3764*67e74705SXin Li // Do nothing if the tag already has a name for linkage purposes.
3765*67e74705SXin Li if (TagFromDeclSpec->hasNameForLinkage())
3766*67e74705SXin Li return;
3767*67e74705SXin Li
3768*67e74705SXin Li // A well-formed anonymous tag must always be a TUK_Definition.
3769*67e74705SXin Li assert(TagFromDeclSpec->isThisDeclarationADefinition());
3770*67e74705SXin Li
3771*67e74705SXin Li // The type must match the tag exactly; no qualifiers allowed.
3772*67e74705SXin Li if (!Context.hasSameType(NewTD->getUnderlyingType(),
3773*67e74705SXin Li Context.getTagDeclType(TagFromDeclSpec))) {
3774*67e74705SXin Li if (getLangOpts().CPlusPlus)
3775*67e74705SXin Li Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3776*67e74705SXin Li return;
3777*67e74705SXin Li }
3778*67e74705SXin Li
3779*67e74705SXin Li // If we've already computed linkage for the anonymous tag, then
3780*67e74705SXin Li // adding a typedef name for the anonymous decl can change that
3781*67e74705SXin Li // linkage, which might be a serious problem. Diagnose this as
3782*67e74705SXin Li // unsupported and ignore the typedef name. TODO: we should
3783*67e74705SXin Li // pursue this as a language defect and establish a formal rule
3784*67e74705SXin Li // for how to handle it.
3785*67e74705SXin Li if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3786*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3787*67e74705SXin Li
3788*67e74705SXin Li SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3789*67e74705SXin Li tagLoc = getLocForEndOfToken(tagLoc);
3790*67e74705SXin Li
3791*67e74705SXin Li llvm::SmallString<40> textToInsert;
3792*67e74705SXin Li textToInsert += ' ';
3793*67e74705SXin Li textToInsert += NewTD->getIdentifier()->getName();
3794*67e74705SXin Li Diag(tagLoc, diag::note_typedef_changes_linkage)
3795*67e74705SXin Li << FixItHint::CreateInsertion(tagLoc, textToInsert);
3796*67e74705SXin Li return;
3797*67e74705SXin Li }
3798*67e74705SXin Li
3799*67e74705SXin Li // Otherwise, set this is the anon-decl typedef for the tag.
3800*67e74705SXin Li TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3801*67e74705SXin Li }
3802*67e74705SXin Li
GetDiagnosticTypeSpecifierID(DeclSpec::TST T)3803*67e74705SXin Li static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3804*67e74705SXin Li switch (T) {
3805*67e74705SXin Li case DeclSpec::TST_class:
3806*67e74705SXin Li return 0;
3807*67e74705SXin Li case DeclSpec::TST_struct:
3808*67e74705SXin Li return 1;
3809*67e74705SXin Li case DeclSpec::TST_interface:
3810*67e74705SXin Li return 2;
3811*67e74705SXin Li case DeclSpec::TST_union:
3812*67e74705SXin Li return 3;
3813*67e74705SXin Li case DeclSpec::TST_enum:
3814*67e74705SXin Li return 4;
3815*67e74705SXin Li default:
3816*67e74705SXin Li llvm_unreachable("unexpected type specifier");
3817*67e74705SXin Li }
3818*67e74705SXin Li }
3819*67e74705SXin Li
3820*67e74705SXin Li /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3821*67e74705SXin Li /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3822*67e74705SXin Li /// parameters to cope with template friend declarations.
3823*67e74705SXin Li Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)3824*67e74705SXin Li Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3825*67e74705SXin Li MultiTemplateParamsArg TemplateParams,
3826*67e74705SXin Li bool IsExplicitInstantiation,
3827*67e74705SXin Li RecordDecl *&AnonRecord) {
3828*67e74705SXin Li Decl *TagD = nullptr;
3829*67e74705SXin Li TagDecl *Tag = nullptr;
3830*67e74705SXin Li if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3831*67e74705SXin Li DS.getTypeSpecType() == DeclSpec::TST_struct ||
3832*67e74705SXin Li DS.getTypeSpecType() == DeclSpec::TST_interface ||
3833*67e74705SXin Li DS.getTypeSpecType() == DeclSpec::TST_union ||
3834*67e74705SXin Li DS.getTypeSpecType() == DeclSpec::TST_enum) {
3835*67e74705SXin Li TagD = DS.getRepAsDecl();
3836*67e74705SXin Li
3837*67e74705SXin Li if (!TagD) // We probably had an error
3838*67e74705SXin Li return nullptr;
3839*67e74705SXin Li
3840*67e74705SXin Li // Note that the above type specs guarantee that the
3841*67e74705SXin Li // type rep is a Decl, whereas in many of the others
3842*67e74705SXin Li // it's a Type.
3843*67e74705SXin Li if (isa<TagDecl>(TagD))
3844*67e74705SXin Li Tag = cast<TagDecl>(TagD);
3845*67e74705SXin Li else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3846*67e74705SXin Li Tag = CTD->getTemplatedDecl();
3847*67e74705SXin Li }
3848*67e74705SXin Li
3849*67e74705SXin Li if (Tag) {
3850*67e74705SXin Li handleTagNumbering(Tag, S);
3851*67e74705SXin Li Tag->setFreeStanding();
3852*67e74705SXin Li if (Tag->isInvalidDecl())
3853*67e74705SXin Li return Tag;
3854*67e74705SXin Li }
3855*67e74705SXin Li
3856*67e74705SXin Li if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3857*67e74705SXin Li // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3858*67e74705SXin Li // or incomplete types shall not be restrict-qualified."
3859*67e74705SXin Li if (TypeQuals & DeclSpec::TQ_restrict)
3860*67e74705SXin Li Diag(DS.getRestrictSpecLoc(),
3861*67e74705SXin Li diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3862*67e74705SXin Li << DS.getSourceRange();
3863*67e74705SXin Li }
3864*67e74705SXin Li
3865*67e74705SXin Li if (DS.isInlineSpecified())
3866*67e74705SXin Li Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3867*67e74705SXin Li << getLangOpts().CPlusPlus1z;
3868*67e74705SXin Li
3869*67e74705SXin Li if (DS.isConstexprSpecified()) {
3870*67e74705SXin Li // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3871*67e74705SXin Li // and definitions of functions and variables.
3872*67e74705SXin Li if (Tag)
3873*67e74705SXin Li Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3874*67e74705SXin Li << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3875*67e74705SXin Li else
3876*67e74705SXin Li Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3877*67e74705SXin Li // Don't emit warnings after this error.
3878*67e74705SXin Li return TagD;
3879*67e74705SXin Li }
3880*67e74705SXin Li
3881*67e74705SXin Li if (DS.isConceptSpecified()) {
3882*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3883*67e74705SXin Li // either a function concept and its definition or a variable concept and
3884*67e74705SXin Li // its initializer.
3885*67e74705SXin Li Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3886*67e74705SXin Li return TagD;
3887*67e74705SXin Li }
3888*67e74705SXin Li
3889*67e74705SXin Li DiagnoseFunctionSpecifiers(DS);
3890*67e74705SXin Li
3891*67e74705SXin Li if (DS.isFriendSpecified()) {
3892*67e74705SXin Li // If we're dealing with a decl but not a TagDecl, assume that
3893*67e74705SXin Li // whatever routines created it handled the friendship aspect.
3894*67e74705SXin Li if (TagD && !Tag)
3895*67e74705SXin Li return nullptr;
3896*67e74705SXin Li return ActOnFriendTypeDecl(S, DS, TemplateParams);
3897*67e74705SXin Li }
3898*67e74705SXin Li
3899*67e74705SXin Li const CXXScopeSpec &SS = DS.getTypeSpecScope();
3900*67e74705SXin Li bool IsExplicitSpecialization =
3901*67e74705SXin Li !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3902*67e74705SXin Li if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3903*67e74705SXin Li !IsExplicitInstantiation && !IsExplicitSpecialization &&
3904*67e74705SXin Li !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3905*67e74705SXin Li // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3906*67e74705SXin Li // nested-name-specifier unless it is an explicit instantiation
3907*67e74705SXin Li // or an explicit specialization.
3908*67e74705SXin Li //
3909*67e74705SXin Li // FIXME: We allow class template partial specializations here too, per the
3910*67e74705SXin Li // obvious intent of DR1819.
3911*67e74705SXin Li //
3912*67e74705SXin Li // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3913*67e74705SXin Li Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3914*67e74705SXin Li << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3915*67e74705SXin Li return nullptr;
3916*67e74705SXin Li }
3917*67e74705SXin Li
3918*67e74705SXin Li // Track whether this decl-specifier declares anything.
3919*67e74705SXin Li bool DeclaresAnything = true;
3920*67e74705SXin Li
3921*67e74705SXin Li // Handle anonymous struct definitions.
3922*67e74705SXin Li if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3923*67e74705SXin Li if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3924*67e74705SXin Li DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3925*67e74705SXin Li if (getLangOpts().CPlusPlus ||
3926*67e74705SXin Li Record->getDeclContext()->isRecord()) {
3927*67e74705SXin Li // If CurContext is a DeclContext that can contain statements,
3928*67e74705SXin Li // RecursiveASTVisitor won't visit the decls that
3929*67e74705SXin Li // BuildAnonymousStructOrUnion() will put into CurContext.
3930*67e74705SXin Li // Also store them here so that they can be part of the
3931*67e74705SXin Li // DeclStmt that gets created in this case.
3932*67e74705SXin Li // FIXME: Also return the IndirectFieldDecls created by
3933*67e74705SXin Li // BuildAnonymousStructOr union, for the same reason?
3934*67e74705SXin Li if (CurContext->isFunctionOrMethod())
3935*67e74705SXin Li AnonRecord = Record;
3936*67e74705SXin Li return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3937*67e74705SXin Li Context.getPrintingPolicy());
3938*67e74705SXin Li }
3939*67e74705SXin Li
3940*67e74705SXin Li DeclaresAnything = false;
3941*67e74705SXin Li }
3942*67e74705SXin Li }
3943*67e74705SXin Li
3944*67e74705SXin Li // C11 6.7.2.1p2:
3945*67e74705SXin Li // A struct-declaration that does not declare an anonymous structure or
3946*67e74705SXin Li // anonymous union shall contain a struct-declarator-list.
3947*67e74705SXin Li //
3948*67e74705SXin Li // This rule also existed in C89 and C99; the grammar for struct-declaration
3949*67e74705SXin Li // did not permit a struct-declaration without a struct-declarator-list.
3950*67e74705SXin Li if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3951*67e74705SXin Li DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3952*67e74705SXin Li // Check for Microsoft C extension: anonymous struct/union member.
3953*67e74705SXin Li // Handle 2 kinds of anonymous struct/union:
3954*67e74705SXin Li // struct STRUCT;
3955*67e74705SXin Li // union UNION;
3956*67e74705SXin Li // and
3957*67e74705SXin Li // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3958*67e74705SXin Li // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3959*67e74705SXin Li if ((Tag && Tag->getDeclName()) ||
3960*67e74705SXin Li DS.getTypeSpecType() == DeclSpec::TST_typename) {
3961*67e74705SXin Li RecordDecl *Record = nullptr;
3962*67e74705SXin Li if (Tag)
3963*67e74705SXin Li Record = dyn_cast<RecordDecl>(Tag);
3964*67e74705SXin Li else if (const RecordType *RT =
3965*67e74705SXin Li DS.getRepAsType().get()->getAsStructureType())
3966*67e74705SXin Li Record = RT->getDecl();
3967*67e74705SXin Li else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3968*67e74705SXin Li Record = UT->getDecl();
3969*67e74705SXin Li
3970*67e74705SXin Li if (Record && getLangOpts().MicrosoftExt) {
3971*67e74705SXin Li Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3972*67e74705SXin Li << Record->isUnion() << DS.getSourceRange();
3973*67e74705SXin Li return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3974*67e74705SXin Li }
3975*67e74705SXin Li
3976*67e74705SXin Li DeclaresAnything = false;
3977*67e74705SXin Li }
3978*67e74705SXin Li }
3979*67e74705SXin Li
3980*67e74705SXin Li // Skip all the checks below if we have a type error.
3981*67e74705SXin Li if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3982*67e74705SXin Li (TagD && TagD->isInvalidDecl()))
3983*67e74705SXin Li return TagD;
3984*67e74705SXin Li
3985*67e74705SXin Li if (getLangOpts().CPlusPlus &&
3986*67e74705SXin Li DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3987*67e74705SXin Li if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3988*67e74705SXin Li if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3989*67e74705SXin Li !Enum->getIdentifier() && !Enum->isInvalidDecl())
3990*67e74705SXin Li DeclaresAnything = false;
3991*67e74705SXin Li
3992*67e74705SXin Li if (!DS.isMissingDeclaratorOk()) {
3993*67e74705SXin Li // Customize diagnostic for a typedef missing a name.
3994*67e74705SXin Li if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3995*67e74705SXin Li Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3996*67e74705SXin Li << DS.getSourceRange();
3997*67e74705SXin Li else
3998*67e74705SXin Li DeclaresAnything = false;
3999*67e74705SXin Li }
4000*67e74705SXin Li
4001*67e74705SXin Li if (DS.isModulePrivateSpecified() &&
4002*67e74705SXin Li Tag && Tag->getDeclContext()->isFunctionOrMethod())
4003*67e74705SXin Li Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4004*67e74705SXin Li << Tag->getTagKind()
4005*67e74705SXin Li << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4006*67e74705SXin Li
4007*67e74705SXin Li ActOnDocumentableDecl(TagD);
4008*67e74705SXin Li
4009*67e74705SXin Li // C 6.7/2:
4010*67e74705SXin Li // A declaration [...] shall declare at least a declarator [...], a tag,
4011*67e74705SXin Li // or the members of an enumeration.
4012*67e74705SXin Li // C++ [dcl.dcl]p3:
4013*67e74705SXin Li // [If there are no declarators], and except for the declaration of an
4014*67e74705SXin Li // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4015*67e74705SXin Li // names into the program, or shall redeclare a name introduced by a
4016*67e74705SXin Li // previous declaration.
4017*67e74705SXin Li if (!DeclaresAnything) {
4018*67e74705SXin Li // In C, we allow this as a (popular) extension / bug. Don't bother
4019*67e74705SXin Li // producing further diagnostics for redundant qualifiers after this.
4020*67e74705SXin Li Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4021*67e74705SXin Li return TagD;
4022*67e74705SXin Li }
4023*67e74705SXin Li
4024*67e74705SXin Li // C++ [dcl.stc]p1:
4025*67e74705SXin Li // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4026*67e74705SXin Li // init-declarator-list of the declaration shall not be empty.
4027*67e74705SXin Li // C++ [dcl.fct.spec]p1:
4028*67e74705SXin Li // If a cv-qualifier appears in a decl-specifier-seq, the
4029*67e74705SXin Li // init-declarator-list of the declaration shall not be empty.
4030*67e74705SXin Li //
4031*67e74705SXin Li // Spurious qualifiers here appear to be valid in C.
4032*67e74705SXin Li unsigned DiagID = diag::warn_standalone_specifier;
4033*67e74705SXin Li if (getLangOpts().CPlusPlus)
4034*67e74705SXin Li DiagID = diag::ext_standalone_specifier;
4035*67e74705SXin Li
4036*67e74705SXin Li // Note that a linkage-specification sets a storage class, but
4037*67e74705SXin Li // 'extern "C" struct foo;' is actually valid and not theoretically
4038*67e74705SXin Li // useless.
4039*67e74705SXin Li if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4040*67e74705SXin Li if (SCS == DeclSpec::SCS_mutable)
4041*67e74705SXin Li // Since mutable is not a viable storage class specifier in C, there is
4042*67e74705SXin Li // no reason to treat it as an extension. Instead, diagnose as an error.
4043*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4044*67e74705SXin Li else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4045*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(), DiagID)
4046*67e74705SXin Li << DeclSpec::getSpecifierName(SCS);
4047*67e74705SXin Li }
4048*67e74705SXin Li
4049*67e74705SXin Li if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4050*67e74705SXin Li Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4051*67e74705SXin Li << DeclSpec::getSpecifierName(TSCS);
4052*67e74705SXin Li if (DS.getTypeQualifiers()) {
4053*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4054*67e74705SXin Li Diag(DS.getConstSpecLoc(), DiagID) << "const";
4055*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4056*67e74705SXin Li Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4057*67e74705SXin Li // Restrict is covered above.
4058*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4059*67e74705SXin Li Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4060*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4061*67e74705SXin Li Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4062*67e74705SXin Li }
4063*67e74705SXin Li
4064*67e74705SXin Li // Warn about ignored type attributes, for example:
4065*67e74705SXin Li // __attribute__((aligned)) struct A;
4066*67e74705SXin Li // Attributes should be placed after tag to apply to type declaration.
4067*67e74705SXin Li if (!DS.getAttributes().empty()) {
4068*67e74705SXin Li DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4069*67e74705SXin Li if (TypeSpecType == DeclSpec::TST_class ||
4070*67e74705SXin Li TypeSpecType == DeclSpec::TST_struct ||
4071*67e74705SXin Li TypeSpecType == DeclSpec::TST_interface ||
4072*67e74705SXin Li TypeSpecType == DeclSpec::TST_union ||
4073*67e74705SXin Li TypeSpecType == DeclSpec::TST_enum) {
4074*67e74705SXin Li for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4075*67e74705SXin Li attrs = attrs->getNext())
4076*67e74705SXin Li Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4077*67e74705SXin Li << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4078*67e74705SXin Li }
4079*67e74705SXin Li }
4080*67e74705SXin Li
4081*67e74705SXin Li return TagD;
4082*67e74705SXin Li }
4083*67e74705SXin Li
4084*67e74705SXin Li /// We are trying to inject an anonymous member into the given scope;
4085*67e74705SXin Li /// check if there's an existing declaration that can't be overloaded.
4086*67e74705SXin Li ///
4087*67e74705SXin Li /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion)4088*67e74705SXin Li static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4089*67e74705SXin Li Scope *S,
4090*67e74705SXin Li DeclContext *Owner,
4091*67e74705SXin Li DeclarationName Name,
4092*67e74705SXin Li SourceLocation NameLoc,
4093*67e74705SXin Li bool IsUnion) {
4094*67e74705SXin Li LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4095*67e74705SXin Li Sema::ForRedeclaration);
4096*67e74705SXin Li if (!SemaRef.LookupName(R, S)) return false;
4097*67e74705SXin Li
4098*67e74705SXin Li // Pick a representative declaration.
4099*67e74705SXin Li NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4100*67e74705SXin Li assert(PrevDecl && "Expected a non-null Decl");
4101*67e74705SXin Li
4102*67e74705SXin Li if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4103*67e74705SXin Li return false;
4104*67e74705SXin Li
4105*67e74705SXin Li SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4106*67e74705SXin Li << IsUnion << Name;
4107*67e74705SXin Li SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4108*67e74705SXin Li
4109*67e74705SXin Li return true;
4110*67e74705SXin Li }
4111*67e74705SXin Li
4112*67e74705SXin Li /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4113*67e74705SXin Li /// anonymous struct or union AnonRecord into the owning context Owner
4114*67e74705SXin Li /// and scope S. This routine will be invoked just after we realize
4115*67e74705SXin Li /// that an unnamed union or struct is actually an anonymous union or
4116*67e74705SXin Li /// struct, e.g.,
4117*67e74705SXin Li ///
4118*67e74705SXin Li /// @code
4119*67e74705SXin Li /// union {
4120*67e74705SXin Li /// int i;
4121*67e74705SXin Li /// float f;
4122*67e74705SXin Li /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4123*67e74705SXin Li /// // f into the surrounding scope.x
4124*67e74705SXin Li /// @endcode
4125*67e74705SXin Li ///
4126*67e74705SXin Li /// This routine is recursive, injecting the names of nested anonymous
4127*67e74705SXin Li /// structs/unions into the owning context and scope as well.
4128*67e74705SXin Li static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVectorImpl<NamedDecl * > & Chaining)4129*67e74705SXin Li InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4130*67e74705SXin Li RecordDecl *AnonRecord, AccessSpecifier AS,
4131*67e74705SXin Li SmallVectorImpl<NamedDecl *> &Chaining) {
4132*67e74705SXin Li bool Invalid = false;
4133*67e74705SXin Li
4134*67e74705SXin Li // Look every FieldDecl and IndirectFieldDecl with a name.
4135*67e74705SXin Li for (auto *D : AnonRecord->decls()) {
4136*67e74705SXin Li if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4137*67e74705SXin Li cast<NamedDecl>(D)->getDeclName()) {
4138*67e74705SXin Li ValueDecl *VD = cast<ValueDecl>(D);
4139*67e74705SXin Li if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4140*67e74705SXin Li VD->getLocation(),
4141*67e74705SXin Li AnonRecord->isUnion())) {
4142*67e74705SXin Li // C++ [class.union]p2:
4143*67e74705SXin Li // The names of the members of an anonymous union shall be
4144*67e74705SXin Li // distinct from the names of any other entity in the
4145*67e74705SXin Li // scope in which the anonymous union is declared.
4146*67e74705SXin Li Invalid = true;
4147*67e74705SXin Li } else {
4148*67e74705SXin Li // C++ [class.union]p2:
4149*67e74705SXin Li // For the purpose of name lookup, after the anonymous union
4150*67e74705SXin Li // definition, the members of the anonymous union are
4151*67e74705SXin Li // considered to have been defined in the scope in which the
4152*67e74705SXin Li // anonymous union is declared.
4153*67e74705SXin Li unsigned OldChainingSize = Chaining.size();
4154*67e74705SXin Li if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4155*67e74705SXin Li Chaining.append(IF->chain_begin(), IF->chain_end());
4156*67e74705SXin Li else
4157*67e74705SXin Li Chaining.push_back(VD);
4158*67e74705SXin Li
4159*67e74705SXin Li assert(Chaining.size() >= 2);
4160*67e74705SXin Li NamedDecl **NamedChain =
4161*67e74705SXin Li new (SemaRef.Context)NamedDecl*[Chaining.size()];
4162*67e74705SXin Li for (unsigned i = 0; i < Chaining.size(); i++)
4163*67e74705SXin Li NamedChain[i] = Chaining[i];
4164*67e74705SXin Li
4165*67e74705SXin Li IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4166*67e74705SXin Li SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4167*67e74705SXin Li VD->getType(), {NamedChain, Chaining.size()});
4168*67e74705SXin Li
4169*67e74705SXin Li for (const auto *Attr : VD->attrs())
4170*67e74705SXin Li IndirectField->addAttr(Attr->clone(SemaRef.Context));
4171*67e74705SXin Li
4172*67e74705SXin Li IndirectField->setAccess(AS);
4173*67e74705SXin Li IndirectField->setImplicit();
4174*67e74705SXin Li SemaRef.PushOnScopeChains(IndirectField, S);
4175*67e74705SXin Li
4176*67e74705SXin Li // That includes picking up the appropriate access specifier.
4177*67e74705SXin Li if (AS != AS_none) IndirectField->setAccess(AS);
4178*67e74705SXin Li
4179*67e74705SXin Li Chaining.resize(OldChainingSize);
4180*67e74705SXin Li }
4181*67e74705SXin Li }
4182*67e74705SXin Li }
4183*67e74705SXin Li
4184*67e74705SXin Li return Invalid;
4185*67e74705SXin Li }
4186*67e74705SXin Li
4187*67e74705SXin Li /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4188*67e74705SXin Li /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4189*67e74705SXin Li /// illegal input values are mapped to SC_None.
4190*67e74705SXin Li static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)4191*67e74705SXin Li StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4192*67e74705SXin Li DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4193*67e74705SXin Li assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4194*67e74705SXin Li "Parser allowed 'typedef' as storage class VarDecl.");
4195*67e74705SXin Li switch (StorageClassSpec) {
4196*67e74705SXin Li case DeclSpec::SCS_unspecified: return SC_None;
4197*67e74705SXin Li case DeclSpec::SCS_extern:
4198*67e74705SXin Li if (DS.isExternInLinkageSpec())
4199*67e74705SXin Li return SC_None;
4200*67e74705SXin Li return SC_Extern;
4201*67e74705SXin Li case DeclSpec::SCS_static: return SC_Static;
4202*67e74705SXin Li case DeclSpec::SCS_auto: return SC_Auto;
4203*67e74705SXin Li case DeclSpec::SCS_register: return SC_Register;
4204*67e74705SXin Li case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4205*67e74705SXin Li // Illegal SCSs map to None: error reporting is up to the caller.
4206*67e74705SXin Li case DeclSpec::SCS_mutable: // Fall through.
4207*67e74705SXin Li case DeclSpec::SCS_typedef: return SC_None;
4208*67e74705SXin Li }
4209*67e74705SXin Li llvm_unreachable("unknown storage class specifier");
4210*67e74705SXin Li }
4211*67e74705SXin Li
findDefaultInitializer(const CXXRecordDecl * Record)4212*67e74705SXin Li static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4213*67e74705SXin Li assert(Record->hasInClassInitializer());
4214*67e74705SXin Li
4215*67e74705SXin Li for (const auto *I : Record->decls()) {
4216*67e74705SXin Li const auto *FD = dyn_cast<FieldDecl>(I);
4217*67e74705SXin Li if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4218*67e74705SXin Li FD = IFD->getAnonField();
4219*67e74705SXin Li if (FD && FD->hasInClassInitializer())
4220*67e74705SXin Li return FD->getLocation();
4221*67e74705SXin Li }
4222*67e74705SXin Li
4223*67e74705SXin Li llvm_unreachable("couldn't find in-class initializer");
4224*67e74705SXin Li }
4225*67e74705SXin Li
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)4226*67e74705SXin Li static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4227*67e74705SXin Li SourceLocation DefaultInitLoc) {
4228*67e74705SXin Li if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4229*67e74705SXin Li return;
4230*67e74705SXin Li
4231*67e74705SXin Li S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4232*67e74705SXin Li S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4233*67e74705SXin Li }
4234*67e74705SXin Li
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)4235*67e74705SXin Li static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4236*67e74705SXin Li CXXRecordDecl *AnonUnion) {
4237*67e74705SXin Li if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4238*67e74705SXin Li return;
4239*67e74705SXin Li
4240*67e74705SXin Li checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4241*67e74705SXin Li }
4242*67e74705SXin Li
4243*67e74705SXin Li /// BuildAnonymousStructOrUnion - Handle the declaration of an
4244*67e74705SXin Li /// anonymous structure or union. Anonymous unions are a C++ feature
4245*67e74705SXin Li /// (C++ [class.union]) and a C11 feature; anonymous structures
4246*67e74705SXin Li /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)4247*67e74705SXin Li Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4248*67e74705SXin Li AccessSpecifier AS,
4249*67e74705SXin Li RecordDecl *Record,
4250*67e74705SXin Li const PrintingPolicy &Policy) {
4251*67e74705SXin Li DeclContext *Owner = Record->getDeclContext();
4252*67e74705SXin Li
4253*67e74705SXin Li // Diagnose whether this anonymous struct/union is an extension.
4254*67e74705SXin Li if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4255*67e74705SXin Li Diag(Record->getLocation(), diag::ext_anonymous_union);
4256*67e74705SXin Li else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4257*67e74705SXin Li Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4258*67e74705SXin Li else if (!Record->isUnion() && !getLangOpts().C11)
4259*67e74705SXin Li Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4260*67e74705SXin Li
4261*67e74705SXin Li // C and C++ require different kinds of checks for anonymous
4262*67e74705SXin Li // structs/unions.
4263*67e74705SXin Li bool Invalid = false;
4264*67e74705SXin Li if (getLangOpts().CPlusPlus) {
4265*67e74705SXin Li const char *PrevSpec = nullptr;
4266*67e74705SXin Li unsigned DiagID;
4267*67e74705SXin Li if (Record->isUnion()) {
4268*67e74705SXin Li // C++ [class.union]p6:
4269*67e74705SXin Li // Anonymous unions declared in a named namespace or in the
4270*67e74705SXin Li // global namespace shall be declared static.
4271*67e74705SXin Li if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4272*67e74705SXin Li (isa<TranslationUnitDecl>(Owner) ||
4273*67e74705SXin Li (isa<NamespaceDecl>(Owner) &&
4274*67e74705SXin Li cast<NamespaceDecl>(Owner)->getDeclName()))) {
4275*67e74705SXin Li Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4276*67e74705SXin Li << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4277*67e74705SXin Li
4278*67e74705SXin Li // Recover by adding 'static'.
4279*67e74705SXin Li DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4280*67e74705SXin Li PrevSpec, DiagID, Policy);
4281*67e74705SXin Li }
4282*67e74705SXin Li // C++ [class.union]p6:
4283*67e74705SXin Li // A storage class is not allowed in a declaration of an
4284*67e74705SXin Li // anonymous union in a class scope.
4285*67e74705SXin Li else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4286*67e74705SXin Li isa<RecordDecl>(Owner)) {
4287*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(),
4288*67e74705SXin Li diag::err_anonymous_union_with_storage_spec)
4289*67e74705SXin Li << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4290*67e74705SXin Li
4291*67e74705SXin Li // Recover by removing the storage specifier.
4292*67e74705SXin Li DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4293*67e74705SXin Li SourceLocation(),
4294*67e74705SXin Li PrevSpec, DiagID, Context.getPrintingPolicy());
4295*67e74705SXin Li }
4296*67e74705SXin Li }
4297*67e74705SXin Li
4298*67e74705SXin Li // Ignore const/volatile/restrict qualifiers.
4299*67e74705SXin Li if (DS.getTypeQualifiers()) {
4300*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4301*67e74705SXin Li Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4302*67e74705SXin Li << Record->isUnion() << "const"
4303*67e74705SXin Li << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4304*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4305*67e74705SXin Li Diag(DS.getVolatileSpecLoc(),
4306*67e74705SXin Li diag::ext_anonymous_struct_union_qualified)
4307*67e74705SXin Li << Record->isUnion() << "volatile"
4308*67e74705SXin Li << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4309*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4310*67e74705SXin Li Diag(DS.getRestrictSpecLoc(),
4311*67e74705SXin Li diag::ext_anonymous_struct_union_qualified)
4312*67e74705SXin Li << Record->isUnion() << "restrict"
4313*67e74705SXin Li << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4314*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4315*67e74705SXin Li Diag(DS.getAtomicSpecLoc(),
4316*67e74705SXin Li diag::ext_anonymous_struct_union_qualified)
4317*67e74705SXin Li << Record->isUnion() << "_Atomic"
4318*67e74705SXin Li << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4319*67e74705SXin Li if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4320*67e74705SXin Li Diag(DS.getUnalignedSpecLoc(),
4321*67e74705SXin Li diag::ext_anonymous_struct_union_qualified)
4322*67e74705SXin Li << Record->isUnion() << "__unaligned"
4323*67e74705SXin Li << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4324*67e74705SXin Li
4325*67e74705SXin Li DS.ClearTypeQualifiers();
4326*67e74705SXin Li }
4327*67e74705SXin Li
4328*67e74705SXin Li // C++ [class.union]p2:
4329*67e74705SXin Li // The member-specification of an anonymous union shall only
4330*67e74705SXin Li // define non-static data members. [Note: nested types and
4331*67e74705SXin Li // functions cannot be declared within an anonymous union. ]
4332*67e74705SXin Li for (auto *Mem : Record->decls()) {
4333*67e74705SXin Li if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4334*67e74705SXin Li // C++ [class.union]p3:
4335*67e74705SXin Li // An anonymous union shall not have private or protected
4336*67e74705SXin Li // members (clause 11).
4337*67e74705SXin Li assert(FD->getAccess() != AS_none);
4338*67e74705SXin Li if (FD->getAccess() != AS_public) {
4339*67e74705SXin Li Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4340*67e74705SXin Li << Record->isUnion() << (FD->getAccess() == AS_protected);
4341*67e74705SXin Li Invalid = true;
4342*67e74705SXin Li }
4343*67e74705SXin Li
4344*67e74705SXin Li // C++ [class.union]p1
4345*67e74705SXin Li // An object of a class with a non-trivial constructor, a non-trivial
4346*67e74705SXin Li // copy constructor, a non-trivial destructor, or a non-trivial copy
4347*67e74705SXin Li // assignment operator cannot be a member of a union, nor can an
4348*67e74705SXin Li // array of such objects.
4349*67e74705SXin Li if (CheckNontrivialField(FD))
4350*67e74705SXin Li Invalid = true;
4351*67e74705SXin Li } else if (Mem->isImplicit()) {
4352*67e74705SXin Li // Any implicit members are fine.
4353*67e74705SXin Li } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4354*67e74705SXin Li // This is a type that showed up in an
4355*67e74705SXin Li // elaborated-type-specifier inside the anonymous struct or
4356*67e74705SXin Li // union, but which actually declares a type outside of the
4357*67e74705SXin Li // anonymous struct or union. It's okay.
4358*67e74705SXin Li } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4359*67e74705SXin Li if (!MemRecord->isAnonymousStructOrUnion() &&
4360*67e74705SXin Li MemRecord->getDeclName()) {
4361*67e74705SXin Li // Visual C++ allows type definition in anonymous struct or union.
4362*67e74705SXin Li if (getLangOpts().MicrosoftExt)
4363*67e74705SXin Li Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4364*67e74705SXin Li << Record->isUnion();
4365*67e74705SXin Li else {
4366*67e74705SXin Li // This is a nested type declaration.
4367*67e74705SXin Li Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4368*67e74705SXin Li << Record->isUnion();
4369*67e74705SXin Li Invalid = true;
4370*67e74705SXin Li }
4371*67e74705SXin Li } else {
4372*67e74705SXin Li // This is an anonymous type definition within another anonymous type.
4373*67e74705SXin Li // This is a popular extension, provided by Plan9, MSVC and GCC, but
4374*67e74705SXin Li // not part of standard C++.
4375*67e74705SXin Li Diag(MemRecord->getLocation(),
4376*67e74705SXin Li diag::ext_anonymous_record_with_anonymous_type)
4377*67e74705SXin Li << Record->isUnion();
4378*67e74705SXin Li }
4379*67e74705SXin Li } else if (isa<AccessSpecDecl>(Mem)) {
4380*67e74705SXin Li // Any access specifier is fine.
4381*67e74705SXin Li } else if (isa<StaticAssertDecl>(Mem)) {
4382*67e74705SXin Li // In C++1z, static_assert declarations are also fine.
4383*67e74705SXin Li } else {
4384*67e74705SXin Li // We have something that isn't a non-static data
4385*67e74705SXin Li // member. Complain about it.
4386*67e74705SXin Li unsigned DK = diag::err_anonymous_record_bad_member;
4387*67e74705SXin Li if (isa<TypeDecl>(Mem))
4388*67e74705SXin Li DK = diag::err_anonymous_record_with_type;
4389*67e74705SXin Li else if (isa<FunctionDecl>(Mem))
4390*67e74705SXin Li DK = diag::err_anonymous_record_with_function;
4391*67e74705SXin Li else if (isa<VarDecl>(Mem))
4392*67e74705SXin Li DK = diag::err_anonymous_record_with_static;
4393*67e74705SXin Li
4394*67e74705SXin Li // Visual C++ allows type definition in anonymous struct or union.
4395*67e74705SXin Li if (getLangOpts().MicrosoftExt &&
4396*67e74705SXin Li DK == diag::err_anonymous_record_with_type)
4397*67e74705SXin Li Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4398*67e74705SXin Li << Record->isUnion();
4399*67e74705SXin Li else {
4400*67e74705SXin Li Diag(Mem->getLocation(), DK) << Record->isUnion();
4401*67e74705SXin Li Invalid = true;
4402*67e74705SXin Li }
4403*67e74705SXin Li }
4404*67e74705SXin Li }
4405*67e74705SXin Li
4406*67e74705SXin Li // C++11 [class.union]p8 (DR1460):
4407*67e74705SXin Li // At most one variant member of a union may have a
4408*67e74705SXin Li // brace-or-equal-initializer.
4409*67e74705SXin Li if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4410*67e74705SXin Li Owner->isRecord())
4411*67e74705SXin Li checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4412*67e74705SXin Li cast<CXXRecordDecl>(Record));
4413*67e74705SXin Li }
4414*67e74705SXin Li
4415*67e74705SXin Li if (!Record->isUnion() && !Owner->isRecord()) {
4416*67e74705SXin Li Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4417*67e74705SXin Li << getLangOpts().CPlusPlus;
4418*67e74705SXin Li Invalid = true;
4419*67e74705SXin Li }
4420*67e74705SXin Li
4421*67e74705SXin Li // Mock up a declarator.
4422*67e74705SXin Li Declarator Dc(DS, Declarator::MemberContext);
4423*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4424*67e74705SXin Li assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4425*67e74705SXin Li
4426*67e74705SXin Li // Create a declaration for this anonymous struct/union.
4427*67e74705SXin Li NamedDecl *Anon = nullptr;
4428*67e74705SXin Li if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4429*67e74705SXin Li Anon = FieldDecl::Create(Context, OwningClass,
4430*67e74705SXin Li DS.getLocStart(),
4431*67e74705SXin Li Record->getLocation(),
4432*67e74705SXin Li /*IdentifierInfo=*/nullptr,
4433*67e74705SXin Li Context.getTypeDeclType(Record),
4434*67e74705SXin Li TInfo,
4435*67e74705SXin Li /*BitWidth=*/nullptr, /*Mutable=*/false,
4436*67e74705SXin Li /*InitStyle=*/ICIS_NoInit);
4437*67e74705SXin Li Anon->setAccess(AS);
4438*67e74705SXin Li if (getLangOpts().CPlusPlus)
4439*67e74705SXin Li FieldCollector->Add(cast<FieldDecl>(Anon));
4440*67e74705SXin Li } else {
4441*67e74705SXin Li DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4442*67e74705SXin Li StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4443*67e74705SXin Li if (SCSpec == DeclSpec::SCS_mutable) {
4444*67e74705SXin Li // mutable can only appear on non-static class members, so it's always
4445*67e74705SXin Li // an error here
4446*67e74705SXin Li Diag(Record->getLocation(), diag::err_mutable_nonmember);
4447*67e74705SXin Li Invalid = true;
4448*67e74705SXin Li SC = SC_None;
4449*67e74705SXin Li }
4450*67e74705SXin Li
4451*67e74705SXin Li Anon = VarDecl::Create(Context, Owner,
4452*67e74705SXin Li DS.getLocStart(),
4453*67e74705SXin Li Record->getLocation(), /*IdentifierInfo=*/nullptr,
4454*67e74705SXin Li Context.getTypeDeclType(Record),
4455*67e74705SXin Li TInfo, SC);
4456*67e74705SXin Li
4457*67e74705SXin Li // Default-initialize the implicit variable. This initialization will be
4458*67e74705SXin Li // trivial in almost all cases, except if a union member has an in-class
4459*67e74705SXin Li // initializer:
4460*67e74705SXin Li // union { int n = 0; };
4461*67e74705SXin Li ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4462*67e74705SXin Li }
4463*67e74705SXin Li Anon->setImplicit();
4464*67e74705SXin Li
4465*67e74705SXin Li // Mark this as an anonymous struct/union type.
4466*67e74705SXin Li Record->setAnonymousStructOrUnion(true);
4467*67e74705SXin Li
4468*67e74705SXin Li // Add the anonymous struct/union object to the current
4469*67e74705SXin Li // context. We'll be referencing this object when we refer to one of
4470*67e74705SXin Li // its members.
4471*67e74705SXin Li Owner->addDecl(Anon);
4472*67e74705SXin Li
4473*67e74705SXin Li // Inject the members of the anonymous struct/union into the owning
4474*67e74705SXin Li // context and into the identifier resolver chain for name lookup
4475*67e74705SXin Li // purposes.
4476*67e74705SXin Li SmallVector<NamedDecl*, 2> Chain;
4477*67e74705SXin Li Chain.push_back(Anon);
4478*67e74705SXin Li
4479*67e74705SXin Li if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4480*67e74705SXin Li Invalid = true;
4481*67e74705SXin Li
4482*67e74705SXin Li if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4483*67e74705SXin Li if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4484*67e74705SXin Li Decl *ManglingContextDecl;
4485*67e74705SXin Li if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4486*67e74705SXin Li NewVD->getDeclContext(), ManglingContextDecl)) {
4487*67e74705SXin Li Context.setManglingNumber(
4488*67e74705SXin Li NewVD, MCtx->getManglingNumber(
4489*67e74705SXin Li NewVD, getMSManglingNumber(getLangOpts(), S)));
4490*67e74705SXin Li Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4491*67e74705SXin Li }
4492*67e74705SXin Li }
4493*67e74705SXin Li }
4494*67e74705SXin Li
4495*67e74705SXin Li if (Invalid)
4496*67e74705SXin Li Anon->setInvalidDecl();
4497*67e74705SXin Li
4498*67e74705SXin Li return Anon;
4499*67e74705SXin Li }
4500*67e74705SXin Li
4501*67e74705SXin Li /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4502*67e74705SXin Li /// Microsoft C anonymous structure.
4503*67e74705SXin Li /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4504*67e74705SXin Li /// Example:
4505*67e74705SXin Li ///
4506*67e74705SXin Li /// struct A { int a; };
4507*67e74705SXin Li /// struct B { struct A; int b; };
4508*67e74705SXin Li ///
4509*67e74705SXin Li /// void foo() {
4510*67e74705SXin Li /// B var;
4511*67e74705SXin Li /// var.a = 3;
4512*67e74705SXin Li /// }
4513*67e74705SXin Li ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)4514*67e74705SXin Li Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4515*67e74705SXin Li RecordDecl *Record) {
4516*67e74705SXin Li assert(Record && "expected a record!");
4517*67e74705SXin Li
4518*67e74705SXin Li // Mock up a declarator.
4519*67e74705SXin Li Declarator Dc(DS, Declarator::TypeNameContext);
4520*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4521*67e74705SXin Li assert(TInfo && "couldn't build declarator info for anonymous struct");
4522*67e74705SXin Li
4523*67e74705SXin Li auto *ParentDecl = cast<RecordDecl>(CurContext);
4524*67e74705SXin Li QualType RecTy = Context.getTypeDeclType(Record);
4525*67e74705SXin Li
4526*67e74705SXin Li // Create a declaration for this anonymous struct.
4527*67e74705SXin Li NamedDecl *Anon = FieldDecl::Create(Context,
4528*67e74705SXin Li ParentDecl,
4529*67e74705SXin Li DS.getLocStart(),
4530*67e74705SXin Li DS.getLocStart(),
4531*67e74705SXin Li /*IdentifierInfo=*/nullptr,
4532*67e74705SXin Li RecTy,
4533*67e74705SXin Li TInfo,
4534*67e74705SXin Li /*BitWidth=*/nullptr, /*Mutable=*/false,
4535*67e74705SXin Li /*InitStyle=*/ICIS_NoInit);
4536*67e74705SXin Li Anon->setImplicit();
4537*67e74705SXin Li
4538*67e74705SXin Li // Add the anonymous struct object to the current context.
4539*67e74705SXin Li CurContext->addDecl(Anon);
4540*67e74705SXin Li
4541*67e74705SXin Li // Inject the members of the anonymous struct into the current
4542*67e74705SXin Li // context and into the identifier resolver chain for name lookup
4543*67e74705SXin Li // purposes.
4544*67e74705SXin Li SmallVector<NamedDecl*, 2> Chain;
4545*67e74705SXin Li Chain.push_back(Anon);
4546*67e74705SXin Li
4547*67e74705SXin Li RecordDecl *RecordDef = Record->getDefinition();
4548*67e74705SXin Li if (RequireCompleteType(Anon->getLocation(), RecTy,
4549*67e74705SXin Li diag::err_field_incomplete) ||
4550*67e74705SXin Li InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4551*67e74705SXin Li AS_none, Chain)) {
4552*67e74705SXin Li Anon->setInvalidDecl();
4553*67e74705SXin Li ParentDecl->setInvalidDecl();
4554*67e74705SXin Li }
4555*67e74705SXin Li
4556*67e74705SXin Li return Anon;
4557*67e74705SXin Li }
4558*67e74705SXin Li
4559*67e74705SXin Li /// GetNameForDeclarator - Determine the full declaration name for the
4560*67e74705SXin Li /// given Declarator.
GetNameForDeclarator(Declarator & D)4561*67e74705SXin Li DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4562*67e74705SXin Li return GetNameFromUnqualifiedId(D.getName());
4563*67e74705SXin Li }
4564*67e74705SXin Li
4565*67e74705SXin Li /// \brief Retrieves the declaration name from a parsed unqualified-id.
4566*67e74705SXin Li DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)4567*67e74705SXin Li Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4568*67e74705SXin Li DeclarationNameInfo NameInfo;
4569*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4570*67e74705SXin Li
4571*67e74705SXin Li switch (Name.getKind()) {
4572*67e74705SXin Li
4573*67e74705SXin Li case UnqualifiedId::IK_ImplicitSelfParam:
4574*67e74705SXin Li case UnqualifiedId::IK_Identifier:
4575*67e74705SXin Li NameInfo.setName(Name.Identifier);
4576*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4577*67e74705SXin Li return NameInfo;
4578*67e74705SXin Li
4579*67e74705SXin Li case UnqualifiedId::IK_OperatorFunctionId:
4580*67e74705SXin Li NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4581*67e74705SXin Li Name.OperatorFunctionId.Operator));
4582*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4583*67e74705SXin Li NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4584*67e74705SXin Li = Name.OperatorFunctionId.SymbolLocations[0];
4585*67e74705SXin Li NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4586*67e74705SXin Li = Name.EndLocation.getRawEncoding();
4587*67e74705SXin Li return NameInfo;
4588*67e74705SXin Li
4589*67e74705SXin Li case UnqualifiedId::IK_LiteralOperatorId:
4590*67e74705SXin Li NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4591*67e74705SXin Li Name.Identifier));
4592*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4593*67e74705SXin Li NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4594*67e74705SXin Li return NameInfo;
4595*67e74705SXin Li
4596*67e74705SXin Li case UnqualifiedId::IK_ConversionFunctionId: {
4597*67e74705SXin Li TypeSourceInfo *TInfo;
4598*67e74705SXin Li QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4599*67e74705SXin Li if (Ty.isNull())
4600*67e74705SXin Li return DeclarationNameInfo();
4601*67e74705SXin Li NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4602*67e74705SXin Li Context.getCanonicalType(Ty)));
4603*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4604*67e74705SXin Li NameInfo.setNamedTypeInfo(TInfo);
4605*67e74705SXin Li return NameInfo;
4606*67e74705SXin Li }
4607*67e74705SXin Li
4608*67e74705SXin Li case UnqualifiedId::IK_ConstructorName: {
4609*67e74705SXin Li TypeSourceInfo *TInfo;
4610*67e74705SXin Li QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4611*67e74705SXin Li if (Ty.isNull())
4612*67e74705SXin Li return DeclarationNameInfo();
4613*67e74705SXin Li NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4614*67e74705SXin Li Context.getCanonicalType(Ty)));
4615*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4616*67e74705SXin Li NameInfo.setNamedTypeInfo(TInfo);
4617*67e74705SXin Li return NameInfo;
4618*67e74705SXin Li }
4619*67e74705SXin Li
4620*67e74705SXin Li case UnqualifiedId::IK_ConstructorTemplateId: {
4621*67e74705SXin Li // In well-formed code, we can only have a constructor
4622*67e74705SXin Li // template-id that refers to the current context, so go there
4623*67e74705SXin Li // to find the actual type being constructed.
4624*67e74705SXin Li CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4625*67e74705SXin Li if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4626*67e74705SXin Li return DeclarationNameInfo();
4627*67e74705SXin Li
4628*67e74705SXin Li // Determine the type of the class being constructed.
4629*67e74705SXin Li QualType CurClassType = Context.getTypeDeclType(CurClass);
4630*67e74705SXin Li
4631*67e74705SXin Li // FIXME: Check two things: that the template-id names the same type as
4632*67e74705SXin Li // CurClassType, and that the template-id does not occur when the name
4633*67e74705SXin Li // was qualified.
4634*67e74705SXin Li
4635*67e74705SXin Li NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4636*67e74705SXin Li Context.getCanonicalType(CurClassType)));
4637*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4638*67e74705SXin Li // FIXME: should we retrieve TypeSourceInfo?
4639*67e74705SXin Li NameInfo.setNamedTypeInfo(nullptr);
4640*67e74705SXin Li return NameInfo;
4641*67e74705SXin Li }
4642*67e74705SXin Li
4643*67e74705SXin Li case UnqualifiedId::IK_DestructorName: {
4644*67e74705SXin Li TypeSourceInfo *TInfo;
4645*67e74705SXin Li QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4646*67e74705SXin Li if (Ty.isNull())
4647*67e74705SXin Li return DeclarationNameInfo();
4648*67e74705SXin Li NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4649*67e74705SXin Li Context.getCanonicalType(Ty)));
4650*67e74705SXin Li NameInfo.setLoc(Name.StartLocation);
4651*67e74705SXin Li NameInfo.setNamedTypeInfo(TInfo);
4652*67e74705SXin Li return NameInfo;
4653*67e74705SXin Li }
4654*67e74705SXin Li
4655*67e74705SXin Li case UnqualifiedId::IK_TemplateId: {
4656*67e74705SXin Li TemplateName TName = Name.TemplateId->Template.get();
4657*67e74705SXin Li SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4658*67e74705SXin Li return Context.getNameForTemplate(TName, TNameLoc);
4659*67e74705SXin Li }
4660*67e74705SXin Li
4661*67e74705SXin Li } // switch (Name.getKind())
4662*67e74705SXin Li
4663*67e74705SXin Li llvm_unreachable("Unknown name kind");
4664*67e74705SXin Li }
4665*67e74705SXin Li
getCoreType(QualType Ty)4666*67e74705SXin Li static QualType getCoreType(QualType Ty) {
4667*67e74705SXin Li do {
4668*67e74705SXin Li if (Ty->isPointerType() || Ty->isReferenceType())
4669*67e74705SXin Li Ty = Ty->getPointeeType();
4670*67e74705SXin Li else if (Ty->isArrayType())
4671*67e74705SXin Li Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4672*67e74705SXin Li else
4673*67e74705SXin Li return Ty.withoutLocalFastQualifiers();
4674*67e74705SXin Li } while (true);
4675*67e74705SXin Li }
4676*67e74705SXin Li
4677*67e74705SXin Li /// hasSimilarParameters - Determine whether the C++ functions Declaration
4678*67e74705SXin Li /// and Definition have "nearly" matching parameters. This heuristic is
4679*67e74705SXin Li /// used to improve diagnostics in the case where an out-of-line function
4680*67e74705SXin Li /// definition doesn't match any declaration within the class or namespace.
4681*67e74705SXin Li /// Also sets Params to the list of indices to the parameters that differ
4682*67e74705SXin Li /// between the declaration and the definition. If hasSimilarParameters
4683*67e74705SXin Li /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)4684*67e74705SXin Li static bool hasSimilarParameters(ASTContext &Context,
4685*67e74705SXin Li FunctionDecl *Declaration,
4686*67e74705SXin Li FunctionDecl *Definition,
4687*67e74705SXin Li SmallVectorImpl<unsigned> &Params) {
4688*67e74705SXin Li Params.clear();
4689*67e74705SXin Li if (Declaration->param_size() != Definition->param_size())
4690*67e74705SXin Li return false;
4691*67e74705SXin Li for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4692*67e74705SXin Li QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4693*67e74705SXin Li QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4694*67e74705SXin Li
4695*67e74705SXin Li // The parameter types are identical
4696*67e74705SXin Li if (Context.hasSameType(DefParamTy, DeclParamTy))
4697*67e74705SXin Li continue;
4698*67e74705SXin Li
4699*67e74705SXin Li QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4700*67e74705SXin Li QualType DefParamBaseTy = getCoreType(DefParamTy);
4701*67e74705SXin Li const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4702*67e74705SXin Li const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4703*67e74705SXin Li
4704*67e74705SXin Li if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4705*67e74705SXin Li (DeclTyName && DeclTyName == DefTyName))
4706*67e74705SXin Li Params.push_back(Idx);
4707*67e74705SXin Li else // The two parameters aren't even close
4708*67e74705SXin Li return false;
4709*67e74705SXin Li }
4710*67e74705SXin Li
4711*67e74705SXin Li return true;
4712*67e74705SXin Li }
4713*67e74705SXin Li
4714*67e74705SXin Li /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4715*67e74705SXin Li /// declarator needs to be rebuilt in the current instantiation.
4716*67e74705SXin Li /// Any bits of declarator which appear before the name are valid for
4717*67e74705SXin Li /// consideration here. That's specifically the type in the decl spec
4718*67e74705SXin Li /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)4719*67e74705SXin Li static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4720*67e74705SXin Li DeclarationName Name) {
4721*67e74705SXin Li // The types we specifically need to rebuild are:
4722*67e74705SXin Li // - typenames, typeofs, and decltypes
4723*67e74705SXin Li // - types which will become injected class names
4724*67e74705SXin Li // Of course, we also need to rebuild any type referencing such a
4725*67e74705SXin Li // type. It's safest to just say "dependent", but we call out a
4726*67e74705SXin Li // few cases here.
4727*67e74705SXin Li
4728*67e74705SXin Li DeclSpec &DS = D.getMutableDeclSpec();
4729*67e74705SXin Li switch (DS.getTypeSpecType()) {
4730*67e74705SXin Li case DeclSpec::TST_typename:
4731*67e74705SXin Li case DeclSpec::TST_typeofType:
4732*67e74705SXin Li case DeclSpec::TST_underlyingType:
4733*67e74705SXin Li case DeclSpec::TST_atomic: {
4734*67e74705SXin Li // Grab the type from the parser.
4735*67e74705SXin Li TypeSourceInfo *TSI = nullptr;
4736*67e74705SXin Li QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4737*67e74705SXin Li if (T.isNull() || !T->isDependentType()) break;
4738*67e74705SXin Li
4739*67e74705SXin Li // Make sure there's a type source info. This isn't really much
4740*67e74705SXin Li // of a waste; most dependent types should have type source info
4741*67e74705SXin Li // attached already.
4742*67e74705SXin Li if (!TSI)
4743*67e74705SXin Li TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4744*67e74705SXin Li
4745*67e74705SXin Li // Rebuild the type in the current instantiation.
4746*67e74705SXin Li TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4747*67e74705SXin Li if (!TSI) return true;
4748*67e74705SXin Li
4749*67e74705SXin Li // Store the new type back in the decl spec.
4750*67e74705SXin Li ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4751*67e74705SXin Li DS.UpdateTypeRep(LocType);
4752*67e74705SXin Li break;
4753*67e74705SXin Li }
4754*67e74705SXin Li
4755*67e74705SXin Li case DeclSpec::TST_decltype:
4756*67e74705SXin Li case DeclSpec::TST_typeofExpr: {
4757*67e74705SXin Li Expr *E = DS.getRepAsExpr();
4758*67e74705SXin Li ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4759*67e74705SXin Li if (Result.isInvalid()) return true;
4760*67e74705SXin Li DS.UpdateExprRep(Result.get());
4761*67e74705SXin Li break;
4762*67e74705SXin Li }
4763*67e74705SXin Li
4764*67e74705SXin Li default:
4765*67e74705SXin Li // Nothing to do for these decl specs.
4766*67e74705SXin Li break;
4767*67e74705SXin Li }
4768*67e74705SXin Li
4769*67e74705SXin Li // It doesn't matter what order we do this in.
4770*67e74705SXin Li for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4771*67e74705SXin Li DeclaratorChunk &Chunk = D.getTypeObject(I);
4772*67e74705SXin Li
4773*67e74705SXin Li // The only type information in the declarator which can come
4774*67e74705SXin Li // before the declaration name is the base type of a member
4775*67e74705SXin Li // pointer.
4776*67e74705SXin Li if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4777*67e74705SXin Li continue;
4778*67e74705SXin Li
4779*67e74705SXin Li // Rebuild the scope specifier in-place.
4780*67e74705SXin Li CXXScopeSpec &SS = Chunk.Mem.Scope();
4781*67e74705SXin Li if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4782*67e74705SXin Li return true;
4783*67e74705SXin Li }
4784*67e74705SXin Li
4785*67e74705SXin Li return false;
4786*67e74705SXin Li }
4787*67e74705SXin Li
ActOnDeclarator(Scope * S,Declarator & D)4788*67e74705SXin Li Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4789*67e74705SXin Li D.setFunctionDefinitionKind(FDK_Declaration);
4790*67e74705SXin Li Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4791*67e74705SXin Li
4792*67e74705SXin Li if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4793*67e74705SXin Li Dcl && Dcl->getDeclContext()->isFileContext())
4794*67e74705SXin Li Dcl->setTopLevelDeclInObjCContainer();
4795*67e74705SXin Li
4796*67e74705SXin Li return Dcl;
4797*67e74705SXin Li }
4798*67e74705SXin Li
4799*67e74705SXin Li /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4800*67e74705SXin Li /// If T is the name of a class, then each of the following shall have a
4801*67e74705SXin Li /// name different from T:
4802*67e74705SXin Li /// - every static data member of class T;
4803*67e74705SXin Li /// - every member function of class T
4804*67e74705SXin Li /// - every member of class T that is itself a type;
4805*67e74705SXin Li /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)4806*67e74705SXin Li bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4807*67e74705SXin Li DeclarationNameInfo NameInfo) {
4808*67e74705SXin Li DeclarationName Name = NameInfo.getName();
4809*67e74705SXin Li
4810*67e74705SXin Li CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4811*67e74705SXin Li while (Record && Record->isAnonymousStructOrUnion())
4812*67e74705SXin Li Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4813*67e74705SXin Li if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4814*67e74705SXin Li Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4815*67e74705SXin Li return true;
4816*67e74705SXin Li }
4817*67e74705SXin Li
4818*67e74705SXin Li return false;
4819*67e74705SXin Li }
4820*67e74705SXin Li
4821*67e74705SXin Li /// \brief Diagnose a declaration whose declarator-id has the given
4822*67e74705SXin Li /// nested-name-specifier.
4823*67e74705SXin Li ///
4824*67e74705SXin Li /// \param SS The nested-name-specifier of the declarator-id.
4825*67e74705SXin Li ///
4826*67e74705SXin Li /// \param DC The declaration context to which the nested-name-specifier
4827*67e74705SXin Li /// resolves.
4828*67e74705SXin Li ///
4829*67e74705SXin Li /// \param Name The name of the entity being declared.
4830*67e74705SXin Li ///
4831*67e74705SXin Li /// \param Loc The location of the name of the entity being declared.
4832*67e74705SXin Li ///
4833*67e74705SXin Li /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc)4834*67e74705SXin Li bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4835*67e74705SXin Li DeclarationName Name,
4836*67e74705SXin Li SourceLocation Loc) {
4837*67e74705SXin Li DeclContext *Cur = CurContext;
4838*67e74705SXin Li while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4839*67e74705SXin Li Cur = Cur->getParent();
4840*67e74705SXin Li
4841*67e74705SXin Li // If the user provided a superfluous scope specifier that refers back to the
4842*67e74705SXin Li // class in which the entity is already declared, diagnose and ignore it.
4843*67e74705SXin Li //
4844*67e74705SXin Li // class X {
4845*67e74705SXin Li // void X::f();
4846*67e74705SXin Li // };
4847*67e74705SXin Li //
4848*67e74705SXin Li // Note, it was once ill-formed to give redundant qualification in all
4849*67e74705SXin Li // contexts, but that rule was removed by DR482.
4850*67e74705SXin Li if (Cur->Equals(DC)) {
4851*67e74705SXin Li if (Cur->isRecord()) {
4852*67e74705SXin Li Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4853*67e74705SXin Li : diag::err_member_extra_qualification)
4854*67e74705SXin Li << Name << FixItHint::CreateRemoval(SS.getRange());
4855*67e74705SXin Li SS.clear();
4856*67e74705SXin Li } else {
4857*67e74705SXin Li Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4858*67e74705SXin Li }
4859*67e74705SXin Li return false;
4860*67e74705SXin Li }
4861*67e74705SXin Li
4862*67e74705SXin Li // Check whether the qualifying scope encloses the scope of the original
4863*67e74705SXin Li // declaration.
4864*67e74705SXin Li if (!Cur->Encloses(DC)) {
4865*67e74705SXin Li if (Cur->isRecord())
4866*67e74705SXin Li Diag(Loc, diag::err_member_qualification)
4867*67e74705SXin Li << Name << SS.getRange();
4868*67e74705SXin Li else if (isa<TranslationUnitDecl>(DC))
4869*67e74705SXin Li Diag(Loc, diag::err_invalid_declarator_global_scope)
4870*67e74705SXin Li << Name << SS.getRange();
4871*67e74705SXin Li else if (isa<FunctionDecl>(Cur))
4872*67e74705SXin Li Diag(Loc, diag::err_invalid_declarator_in_function)
4873*67e74705SXin Li << Name << SS.getRange();
4874*67e74705SXin Li else if (isa<BlockDecl>(Cur))
4875*67e74705SXin Li Diag(Loc, diag::err_invalid_declarator_in_block)
4876*67e74705SXin Li << Name << SS.getRange();
4877*67e74705SXin Li else
4878*67e74705SXin Li Diag(Loc, diag::err_invalid_declarator_scope)
4879*67e74705SXin Li << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4880*67e74705SXin Li
4881*67e74705SXin Li return true;
4882*67e74705SXin Li }
4883*67e74705SXin Li
4884*67e74705SXin Li if (Cur->isRecord()) {
4885*67e74705SXin Li // Cannot qualify members within a class.
4886*67e74705SXin Li Diag(Loc, diag::err_member_qualification)
4887*67e74705SXin Li << Name << SS.getRange();
4888*67e74705SXin Li SS.clear();
4889*67e74705SXin Li
4890*67e74705SXin Li // C++ constructors and destructors with incorrect scopes can break
4891*67e74705SXin Li // our AST invariants by having the wrong underlying types. If
4892*67e74705SXin Li // that's the case, then drop this declaration entirely.
4893*67e74705SXin Li if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4894*67e74705SXin Li Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4895*67e74705SXin Li !Context.hasSameType(Name.getCXXNameType(),
4896*67e74705SXin Li Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4897*67e74705SXin Li return true;
4898*67e74705SXin Li
4899*67e74705SXin Li return false;
4900*67e74705SXin Li }
4901*67e74705SXin Li
4902*67e74705SXin Li // C++11 [dcl.meaning]p1:
4903*67e74705SXin Li // [...] "The nested-name-specifier of the qualified declarator-id shall
4904*67e74705SXin Li // not begin with a decltype-specifer"
4905*67e74705SXin Li NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4906*67e74705SXin Li while (SpecLoc.getPrefix())
4907*67e74705SXin Li SpecLoc = SpecLoc.getPrefix();
4908*67e74705SXin Li if (dyn_cast_or_null<DecltypeType>(
4909*67e74705SXin Li SpecLoc.getNestedNameSpecifier()->getAsType()))
4910*67e74705SXin Li Diag(Loc, diag::err_decltype_in_declarator)
4911*67e74705SXin Li << SpecLoc.getTypeLoc().getSourceRange();
4912*67e74705SXin Li
4913*67e74705SXin Li return false;
4914*67e74705SXin Li }
4915*67e74705SXin Li
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)4916*67e74705SXin Li NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4917*67e74705SXin Li MultiTemplateParamsArg TemplateParamLists) {
4918*67e74705SXin Li // TODO: consider using NameInfo for diagnostic.
4919*67e74705SXin Li DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4920*67e74705SXin Li DeclarationName Name = NameInfo.getName();
4921*67e74705SXin Li
4922*67e74705SXin Li // All of these full declarators require an identifier. If it doesn't have
4923*67e74705SXin Li // one, the ParsedFreeStandingDeclSpec action should be used.
4924*67e74705SXin Li if (!Name) {
4925*67e74705SXin Li if (!D.isInvalidType()) // Reject this if we think it is valid.
4926*67e74705SXin Li Diag(D.getDeclSpec().getLocStart(),
4927*67e74705SXin Li diag::err_declarator_need_ident)
4928*67e74705SXin Li << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4929*67e74705SXin Li return nullptr;
4930*67e74705SXin Li } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4931*67e74705SXin Li return nullptr;
4932*67e74705SXin Li
4933*67e74705SXin Li // The scope passed in may not be a decl scope. Zip up the scope tree until
4934*67e74705SXin Li // we find one that is.
4935*67e74705SXin Li while ((S->getFlags() & Scope::DeclScope) == 0 ||
4936*67e74705SXin Li (S->getFlags() & Scope::TemplateParamScope) != 0)
4937*67e74705SXin Li S = S->getParent();
4938*67e74705SXin Li
4939*67e74705SXin Li DeclContext *DC = CurContext;
4940*67e74705SXin Li if (D.getCXXScopeSpec().isInvalid())
4941*67e74705SXin Li D.setInvalidType();
4942*67e74705SXin Li else if (D.getCXXScopeSpec().isSet()) {
4943*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4944*67e74705SXin Li UPPC_DeclarationQualifier))
4945*67e74705SXin Li return nullptr;
4946*67e74705SXin Li
4947*67e74705SXin Li bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4948*67e74705SXin Li DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4949*67e74705SXin Li if (!DC || isa<EnumDecl>(DC)) {
4950*67e74705SXin Li // If we could not compute the declaration context, it's because the
4951*67e74705SXin Li // declaration context is dependent but does not refer to a class,
4952*67e74705SXin Li // class template, or class template partial specialization. Complain
4953*67e74705SXin Li // and return early, to avoid the coming semantic disaster.
4954*67e74705SXin Li Diag(D.getIdentifierLoc(),
4955*67e74705SXin Li diag::err_template_qualified_declarator_no_match)
4956*67e74705SXin Li << D.getCXXScopeSpec().getScopeRep()
4957*67e74705SXin Li << D.getCXXScopeSpec().getRange();
4958*67e74705SXin Li return nullptr;
4959*67e74705SXin Li }
4960*67e74705SXin Li bool IsDependentContext = DC->isDependentContext();
4961*67e74705SXin Li
4962*67e74705SXin Li if (!IsDependentContext &&
4963*67e74705SXin Li RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4964*67e74705SXin Li return nullptr;
4965*67e74705SXin Li
4966*67e74705SXin Li // If a class is incomplete, do not parse entities inside it.
4967*67e74705SXin Li if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4968*67e74705SXin Li Diag(D.getIdentifierLoc(),
4969*67e74705SXin Li diag::err_member_def_undefined_record)
4970*67e74705SXin Li << Name << DC << D.getCXXScopeSpec().getRange();
4971*67e74705SXin Li return nullptr;
4972*67e74705SXin Li }
4973*67e74705SXin Li if (!D.getDeclSpec().isFriendSpecified()) {
4974*67e74705SXin Li if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4975*67e74705SXin Li Name, D.getIdentifierLoc())) {
4976*67e74705SXin Li if (DC->isRecord())
4977*67e74705SXin Li return nullptr;
4978*67e74705SXin Li
4979*67e74705SXin Li D.setInvalidType();
4980*67e74705SXin Li }
4981*67e74705SXin Li }
4982*67e74705SXin Li
4983*67e74705SXin Li // Check whether we need to rebuild the type of the given
4984*67e74705SXin Li // declaration in the current instantiation.
4985*67e74705SXin Li if (EnteringContext && IsDependentContext &&
4986*67e74705SXin Li TemplateParamLists.size() != 0) {
4987*67e74705SXin Li ContextRAII SavedContext(*this, DC);
4988*67e74705SXin Li if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4989*67e74705SXin Li D.setInvalidType();
4990*67e74705SXin Li }
4991*67e74705SXin Li }
4992*67e74705SXin Li
4993*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4994*67e74705SXin Li QualType R = TInfo->getType();
4995*67e74705SXin Li
4996*67e74705SXin Li if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4997*67e74705SXin Li // If this is a typedef, we'll end up spewing multiple diagnostics.
4998*67e74705SXin Li // Just return early; it's safer. If this is a function, let the
4999*67e74705SXin Li // "constructor cannot have a return type" diagnostic handle it.
5000*67e74705SXin Li if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5001*67e74705SXin Li return nullptr;
5002*67e74705SXin Li
5003*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5004*67e74705SXin Li UPPC_DeclarationType))
5005*67e74705SXin Li D.setInvalidType();
5006*67e74705SXin Li
5007*67e74705SXin Li LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5008*67e74705SXin Li ForRedeclaration);
5009*67e74705SXin Li
5010*67e74705SXin Li // See if this is a redefinition of a variable in the same scope.
5011*67e74705SXin Li if (!D.getCXXScopeSpec().isSet()) {
5012*67e74705SXin Li bool IsLinkageLookup = false;
5013*67e74705SXin Li bool CreateBuiltins = false;
5014*67e74705SXin Li
5015*67e74705SXin Li // If the declaration we're planning to build will be a function
5016*67e74705SXin Li // or object with linkage, then look for another declaration with
5017*67e74705SXin Li // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5018*67e74705SXin Li //
5019*67e74705SXin Li // If the declaration we're planning to build will be declared with
5020*67e74705SXin Li // external linkage in the translation unit, create any builtin with
5021*67e74705SXin Li // the same name.
5022*67e74705SXin Li if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5023*67e74705SXin Li /* Do nothing*/;
5024*67e74705SXin Li else if (CurContext->isFunctionOrMethod() &&
5025*67e74705SXin Li (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5026*67e74705SXin Li R->isFunctionType())) {
5027*67e74705SXin Li IsLinkageLookup = true;
5028*67e74705SXin Li CreateBuiltins =
5029*67e74705SXin Li CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5030*67e74705SXin Li } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5031*67e74705SXin Li D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5032*67e74705SXin Li CreateBuiltins = true;
5033*67e74705SXin Li
5034*67e74705SXin Li if (IsLinkageLookup)
5035*67e74705SXin Li Previous.clear(LookupRedeclarationWithLinkage);
5036*67e74705SXin Li
5037*67e74705SXin Li LookupName(Previous, S, CreateBuiltins);
5038*67e74705SXin Li } else { // Something like "int foo::x;"
5039*67e74705SXin Li LookupQualifiedName(Previous, DC);
5040*67e74705SXin Li
5041*67e74705SXin Li // C++ [dcl.meaning]p1:
5042*67e74705SXin Li // When the declarator-id is qualified, the declaration shall refer to a
5043*67e74705SXin Li // previously declared member of the class or namespace to which the
5044*67e74705SXin Li // qualifier refers (or, in the case of a namespace, of an element of the
5045*67e74705SXin Li // inline namespace set of that namespace (7.3.1)) or to a specialization
5046*67e74705SXin Li // thereof; [...]
5047*67e74705SXin Li //
5048*67e74705SXin Li // Note that we already checked the context above, and that we do not have
5049*67e74705SXin Li // enough information to make sure that Previous contains the declaration
5050*67e74705SXin Li // we want to match. For example, given:
5051*67e74705SXin Li //
5052*67e74705SXin Li // class X {
5053*67e74705SXin Li // void f();
5054*67e74705SXin Li // void f(float);
5055*67e74705SXin Li // };
5056*67e74705SXin Li //
5057*67e74705SXin Li // void X::f(int) { } // ill-formed
5058*67e74705SXin Li //
5059*67e74705SXin Li // In this case, Previous will point to the overload set
5060*67e74705SXin Li // containing the two f's declared in X, but neither of them
5061*67e74705SXin Li // matches.
5062*67e74705SXin Li
5063*67e74705SXin Li // C++ [dcl.meaning]p1:
5064*67e74705SXin Li // [...] the member shall not merely have been introduced by a
5065*67e74705SXin Li // using-declaration in the scope of the class or namespace nominated by
5066*67e74705SXin Li // the nested-name-specifier of the declarator-id.
5067*67e74705SXin Li RemoveUsingDecls(Previous);
5068*67e74705SXin Li }
5069*67e74705SXin Li
5070*67e74705SXin Li if (Previous.isSingleResult() &&
5071*67e74705SXin Li Previous.getFoundDecl()->isTemplateParameter()) {
5072*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
5073*67e74705SXin Li if (!D.isInvalidType())
5074*67e74705SXin Li DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5075*67e74705SXin Li Previous.getFoundDecl());
5076*67e74705SXin Li
5077*67e74705SXin Li // Just pretend that we didn't see the previous declaration.
5078*67e74705SXin Li Previous.clear();
5079*67e74705SXin Li }
5080*67e74705SXin Li
5081*67e74705SXin Li // In C++, the previous declaration we find might be a tag type
5082*67e74705SXin Li // (class or enum). In this case, the new declaration will hide the
5083*67e74705SXin Li // tag type. Note that this does does not apply if we're declaring a
5084*67e74705SXin Li // typedef (C++ [dcl.typedef]p4).
5085*67e74705SXin Li if (Previous.isSingleTagDecl() &&
5086*67e74705SXin Li D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5087*67e74705SXin Li Previous.clear();
5088*67e74705SXin Li
5089*67e74705SXin Li // Check that there are no default arguments other than in the parameters
5090*67e74705SXin Li // of a function declaration (C++ only).
5091*67e74705SXin Li if (getLangOpts().CPlusPlus)
5092*67e74705SXin Li CheckExtraCXXDefaultArguments(D);
5093*67e74705SXin Li
5094*67e74705SXin Li if (D.getDeclSpec().isConceptSpecified()) {
5095*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5096*67e74705SXin Li // applied only to the definition of a function template or variable
5097*67e74705SXin Li // template, declared in namespace scope
5098*67e74705SXin Li if (!TemplateParamLists.size()) {
5099*67e74705SXin Li Diag(D.getDeclSpec().getConceptSpecLoc(),
5100*67e74705SXin Li diag:: err_concept_wrong_decl_kind);
5101*67e74705SXin Li return nullptr;
5102*67e74705SXin Li }
5103*67e74705SXin Li
5104*67e74705SXin Li if (!DC->getRedeclContext()->isFileContext()) {
5105*67e74705SXin Li Diag(D.getIdentifierLoc(),
5106*67e74705SXin Li diag::err_concept_decls_may_only_appear_in_namespace_scope);
5107*67e74705SXin Li return nullptr;
5108*67e74705SXin Li }
5109*67e74705SXin Li }
5110*67e74705SXin Li
5111*67e74705SXin Li NamedDecl *New;
5112*67e74705SXin Li
5113*67e74705SXin Li bool AddToScope = true;
5114*67e74705SXin Li if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5115*67e74705SXin Li if (TemplateParamLists.size()) {
5116*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5117*67e74705SXin Li return nullptr;
5118*67e74705SXin Li }
5119*67e74705SXin Li
5120*67e74705SXin Li New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5121*67e74705SXin Li } else if (R->isFunctionType()) {
5122*67e74705SXin Li New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5123*67e74705SXin Li TemplateParamLists,
5124*67e74705SXin Li AddToScope);
5125*67e74705SXin Li } else {
5126*67e74705SXin Li New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5127*67e74705SXin Li AddToScope);
5128*67e74705SXin Li }
5129*67e74705SXin Li
5130*67e74705SXin Li if (!New)
5131*67e74705SXin Li return nullptr;
5132*67e74705SXin Li
5133*67e74705SXin Li // If this has an identifier and is not a function template specialization,
5134*67e74705SXin Li // add it to the scope stack.
5135*67e74705SXin Li if (New->getDeclName() && AddToScope) {
5136*67e74705SXin Li // Only make a locally-scoped extern declaration visible if it is the first
5137*67e74705SXin Li // declaration of this entity. Qualified lookup for such an entity should
5138*67e74705SXin Li // only find this declaration if there is no visible declaration of it.
5139*67e74705SXin Li bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5140*67e74705SXin Li PushOnScopeChains(New, S, AddToContext);
5141*67e74705SXin Li if (!AddToContext)
5142*67e74705SXin Li CurContext->addHiddenDecl(New);
5143*67e74705SXin Li }
5144*67e74705SXin Li
5145*67e74705SXin Li if (isInOpenMPDeclareTargetContext())
5146*67e74705SXin Li checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5147*67e74705SXin Li
5148*67e74705SXin Li return New;
5149*67e74705SXin Li }
5150*67e74705SXin Li
5151*67e74705SXin Li /// Helper method to turn variable array types into constant array
5152*67e74705SXin Li /// types in certain situations which would otherwise be errors (for
5153*67e74705SXin Li /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5154*67e74705SXin Li static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5155*67e74705SXin Li ASTContext &Context,
5156*67e74705SXin Li bool &SizeIsNegative,
5157*67e74705SXin Li llvm::APSInt &Oversized) {
5158*67e74705SXin Li // This method tries to turn a variable array into a constant
5159*67e74705SXin Li // array even when the size isn't an ICE. This is necessary
5160*67e74705SXin Li // for compatibility with code that depends on gcc's buggy
5161*67e74705SXin Li // constant expression folding, like struct {char x[(int)(char*)2];}
5162*67e74705SXin Li SizeIsNegative = false;
5163*67e74705SXin Li Oversized = 0;
5164*67e74705SXin Li
5165*67e74705SXin Li if (T->isDependentType())
5166*67e74705SXin Li return QualType();
5167*67e74705SXin Li
5168*67e74705SXin Li QualifierCollector Qs;
5169*67e74705SXin Li const Type *Ty = Qs.strip(T);
5170*67e74705SXin Li
5171*67e74705SXin Li if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5172*67e74705SXin Li QualType Pointee = PTy->getPointeeType();
5173*67e74705SXin Li QualType FixedType =
5174*67e74705SXin Li TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5175*67e74705SXin Li Oversized);
5176*67e74705SXin Li if (FixedType.isNull()) return FixedType;
5177*67e74705SXin Li FixedType = Context.getPointerType(FixedType);
5178*67e74705SXin Li return Qs.apply(Context, FixedType);
5179*67e74705SXin Li }
5180*67e74705SXin Li if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5181*67e74705SXin Li QualType Inner = PTy->getInnerType();
5182*67e74705SXin Li QualType FixedType =
5183*67e74705SXin Li TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5184*67e74705SXin Li Oversized);
5185*67e74705SXin Li if (FixedType.isNull()) return FixedType;
5186*67e74705SXin Li FixedType = Context.getParenType(FixedType);
5187*67e74705SXin Li return Qs.apply(Context, FixedType);
5188*67e74705SXin Li }
5189*67e74705SXin Li
5190*67e74705SXin Li const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5191*67e74705SXin Li if (!VLATy)
5192*67e74705SXin Li return QualType();
5193*67e74705SXin Li // FIXME: We should probably handle this case
5194*67e74705SXin Li if (VLATy->getElementType()->isVariablyModifiedType())
5195*67e74705SXin Li return QualType();
5196*67e74705SXin Li
5197*67e74705SXin Li llvm::APSInt Res;
5198*67e74705SXin Li if (!VLATy->getSizeExpr() ||
5199*67e74705SXin Li !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5200*67e74705SXin Li return QualType();
5201*67e74705SXin Li
5202*67e74705SXin Li // Check whether the array size is negative.
5203*67e74705SXin Li if (Res.isSigned() && Res.isNegative()) {
5204*67e74705SXin Li SizeIsNegative = true;
5205*67e74705SXin Li return QualType();
5206*67e74705SXin Li }
5207*67e74705SXin Li
5208*67e74705SXin Li // Check whether the array is too large to be addressed.
5209*67e74705SXin Li unsigned ActiveSizeBits
5210*67e74705SXin Li = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5211*67e74705SXin Li Res);
5212*67e74705SXin Li if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5213*67e74705SXin Li Oversized = Res;
5214*67e74705SXin Li return QualType();
5215*67e74705SXin Li }
5216*67e74705SXin Li
5217*67e74705SXin Li return Context.getConstantArrayType(VLATy->getElementType(),
5218*67e74705SXin Li Res, ArrayType::Normal, 0);
5219*67e74705SXin Li }
5220*67e74705SXin Li
5221*67e74705SXin Li static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)5222*67e74705SXin Li FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5223*67e74705SXin Li SrcTL = SrcTL.getUnqualifiedLoc();
5224*67e74705SXin Li DstTL = DstTL.getUnqualifiedLoc();
5225*67e74705SXin Li if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5226*67e74705SXin Li PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5227*67e74705SXin Li FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5228*67e74705SXin Li DstPTL.getPointeeLoc());
5229*67e74705SXin Li DstPTL.setStarLoc(SrcPTL.getStarLoc());
5230*67e74705SXin Li return;
5231*67e74705SXin Li }
5232*67e74705SXin Li if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5233*67e74705SXin Li ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5234*67e74705SXin Li FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5235*67e74705SXin Li DstPTL.getInnerLoc());
5236*67e74705SXin Li DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5237*67e74705SXin Li DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5238*67e74705SXin Li return;
5239*67e74705SXin Li }
5240*67e74705SXin Li ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5241*67e74705SXin Li ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5242*67e74705SXin Li TypeLoc SrcElemTL = SrcATL.getElementLoc();
5243*67e74705SXin Li TypeLoc DstElemTL = DstATL.getElementLoc();
5244*67e74705SXin Li DstElemTL.initializeFullCopy(SrcElemTL);
5245*67e74705SXin Li DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5246*67e74705SXin Li DstATL.setSizeExpr(SrcATL.getSizeExpr());
5247*67e74705SXin Li DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5248*67e74705SXin Li }
5249*67e74705SXin Li
5250*67e74705SXin Li /// Helper method to turn variable array types into constant array
5251*67e74705SXin Li /// types in certain situations which would otherwise be errors (for
5252*67e74705SXin Li /// GCC compatibility).
5253*67e74705SXin Li static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5254*67e74705SXin Li TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5255*67e74705SXin Li ASTContext &Context,
5256*67e74705SXin Li bool &SizeIsNegative,
5257*67e74705SXin Li llvm::APSInt &Oversized) {
5258*67e74705SXin Li QualType FixedTy
5259*67e74705SXin Li = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5260*67e74705SXin Li SizeIsNegative, Oversized);
5261*67e74705SXin Li if (FixedTy.isNull())
5262*67e74705SXin Li return nullptr;
5263*67e74705SXin Li TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5264*67e74705SXin Li FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5265*67e74705SXin Li FixedTInfo->getTypeLoc());
5266*67e74705SXin Li return FixedTInfo;
5267*67e74705SXin Li }
5268*67e74705SXin Li
5269*67e74705SXin Li /// \brief Register the given locally-scoped extern "C" declaration so
5270*67e74705SXin Li /// that it can be found later for redeclarations. We include any extern "C"
5271*67e74705SXin Li /// declaration that is not visible in the translation unit here, not just
5272*67e74705SXin Li /// function-scope declarations.
5273*67e74705SXin Li void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)5274*67e74705SXin Li Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5275*67e74705SXin Li if (!getLangOpts().CPlusPlus &&
5276*67e74705SXin Li ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5277*67e74705SXin Li // Don't need to track declarations in the TU in C.
5278*67e74705SXin Li return;
5279*67e74705SXin Li
5280*67e74705SXin Li // Note that we have a locally-scoped external with this name.
5281*67e74705SXin Li Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5282*67e74705SXin Li }
5283*67e74705SXin Li
findLocallyScopedExternCDecl(DeclarationName Name)5284*67e74705SXin Li NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5285*67e74705SXin Li // FIXME: We can have multiple results via __attribute__((overloadable)).
5286*67e74705SXin Li auto Result = Context.getExternCContextDecl()->lookup(Name);
5287*67e74705SXin Li return Result.empty() ? nullptr : *Result.begin();
5288*67e74705SXin Li }
5289*67e74705SXin Li
5290*67e74705SXin Li /// \brief Diagnose function specifiers on a declaration of an identifier that
5291*67e74705SXin Li /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)5292*67e74705SXin Li void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5293*67e74705SXin Li // FIXME: We should probably indicate the identifier in question to avoid
5294*67e74705SXin Li // confusion for constructs like "virtual int a(), b;"
5295*67e74705SXin Li if (DS.isVirtualSpecified())
5296*67e74705SXin Li Diag(DS.getVirtualSpecLoc(),
5297*67e74705SXin Li diag::err_virtual_non_function);
5298*67e74705SXin Li
5299*67e74705SXin Li if (DS.isExplicitSpecified())
5300*67e74705SXin Li Diag(DS.getExplicitSpecLoc(),
5301*67e74705SXin Li diag::err_explicit_non_function);
5302*67e74705SXin Li
5303*67e74705SXin Li if (DS.isNoreturnSpecified())
5304*67e74705SXin Li Diag(DS.getNoreturnSpecLoc(),
5305*67e74705SXin Li diag::err_noreturn_non_function);
5306*67e74705SXin Li }
5307*67e74705SXin Li
5308*67e74705SXin Li NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)5309*67e74705SXin Li Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5310*67e74705SXin Li TypeSourceInfo *TInfo, LookupResult &Previous) {
5311*67e74705SXin Li // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5312*67e74705SXin Li if (D.getCXXScopeSpec().isSet()) {
5313*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5314*67e74705SXin Li << D.getCXXScopeSpec().getRange();
5315*67e74705SXin Li D.setInvalidType();
5316*67e74705SXin Li // Pretend we didn't see the scope specifier.
5317*67e74705SXin Li DC = CurContext;
5318*67e74705SXin Li Previous.clear();
5319*67e74705SXin Li }
5320*67e74705SXin Li
5321*67e74705SXin Li DiagnoseFunctionSpecifiers(D.getDeclSpec());
5322*67e74705SXin Li
5323*67e74705SXin Li if (D.getDeclSpec().isInlineSpecified())
5324*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5325*67e74705SXin Li << getLangOpts().CPlusPlus1z;
5326*67e74705SXin Li if (D.getDeclSpec().isConstexprSpecified())
5327*67e74705SXin Li Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5328*67e74705SXin Li << 1;
5329*67e74705SXin Li if (D.getDeclSpec().isConceptSpecified())
5330*67e74705SXin Li Diag(D.getDeclSpec().getConceptSpecLoc(),
5331*67e74705SXin Li diag::err_concept_wrong_decl_kind);
5332*67e74705SXin Li
5333*67e74705SXin Li if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5334*67e74705SXin Li Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5335*67e74705SXin Li << D.getName().getSourceRange();
5336*67e74705SXin Li return nullptr;
5337*67e74705SXin Li }
5338*67e74705SXin Li
5339*67e74705SXin Li TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5340*67e74705SXin Li if (!NewTD) return nullptr;
5341*67e74705SXin Li
5342*67e74705SXin Li // Handle attributes prior to checking for duplicates in MergeVarDecl
5343*67e74705SXin Li ProcessDeclAttributes(S, NewTD, D);
5344*67e74705SXin Li
5345*67e74705SXin Li CheckTypedefForVariablyModifiedType(S, NewTD);
5346*67e74705SXin Li
5347*67e74705SXin Li bool Redeclaration = D.isRedeclaration();
5348*67e74705SXin Li NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5349*67e74705SXin Li D.setRedeclaration(Redeclaration);
5350*67e74705SXin Li return ND;
5351*67e74705SXin Li }
5352*67e74705SXin Li
5353*67e74705SXin Li void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)5354*67e74705SXin Li Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5355*67e74705SXin Li // C99 6.7.7p2: If a typedef name specifies a variably modified type
5356*67e74705SXin Li // then it shall have block scope.
5357*67e74705SXin Li // Note that variably modified types must be fixed before merging the decl so
5358*67e74705SXin Li // that redeclarations will match.
5359*67e74705SXin Li TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5360*67e74705SXin Li QualType T = TInfo->getType();
5361*67e74705SXin Li if (T->isVariablyModifiedType()) {
5362*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
5363*67e74705SXin Li
5364*67e74705SXin Li if (S->getFnParent() == nullptr) {
5365*67e74705SXin Li bool SizeIsNegative;
5366*67e74705SXin Li llvm::APSInt Oversized;
5367*67e74705SXin Li TypeSourceInfo *FixedTInfo =
5368*67e74705SXin Li TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5369*67e74705SXin Li SizeIsNegative,
5370*67e74705SXin Li Oversized);
5371*67e74705SXin Li if (FixedTInfo) {
5372*67e74705SXin Li Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5373*67e74705SXin Li NewTD->setTypeSourceInfo(FixedTInfo);
5374*67e74705SXin Li } else {
5375*67e74705SXin Li if (SizeIsNegative)
5376*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5377*67e74705SXin Li else if (T->isVariableArrayType())
5378*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5379*67e74705SXin Li else if (Oversized.getBoolValue())
5380*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_array_too_large)
5381*67e74705SXin Li << Oversized.toString(10);
5382*67e74705SXin Li else
5383*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5384*67e74705SXin Li NewTD->setInvalidDecl();
5385*67e74705SXin Li }
5386*67e74705SXin Li }
5387*67e74705SXin Li }
5388*67e74705SXin Li }
5389*67e74705SXin Li
5390*67e74705SXin Li /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5391*67e74705SXin Li /// declares a typedef-name, either using the 'typedef' type specifier or via
5392*67e74705SXin Li /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5393*67e74705SXin Li NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)5394*67e74705SXin Li Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5395*67e74705SXin Li LookupResult &Previous, bool &Redeclaration) {
5396*67e74705SXin Li // Merge the decl with the existing one if appropriate. If the decl is
5397*67e74705SXin Li // in an outer scope, it isn't the same thing.
5398*67e74705SXin Li FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5399*67e74705SXin Li /*AllowInlineNamespace*/false);
5400*67e74705SXin Li filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5401*67e74705SXin Li if (!Previous.empty()) {
5402*67e74705SXin Li Redeclaration = true;
5403*67e74705SXin Li MergeTypedefNameDecl(S, NewTD, Previous);
5404*67e74705SXin Li }
5405*67e74705SXin Li
5406*67e74705SXin Li // If this is the C FILE type, notify the AST context.
5407*67e74705SXin Li if (IdentifierInfo *II = NewTD->getIdentifier())
5408*67e74705SXin Li if (!NewTD->isInvalidDecl() &&
5409*67e74705SXin Li NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5410*67e74705SXin Li if (II->isStr("FILE"))
5411*67e74705SXin Li Context.setFILEDecl(NewTD);
5412*67e74705SXin Li else if (II->isStr("jmp_buf"))
5413*67e74705SXin Li Context.setjmp_bufDecl(NewTD);
5414*67e74705SXin Li else if (II->isStr("sigjmp_buf"))
5415*67e74705SXin Li Context.setsigjmp_bufDecl(NewTD);
5416*67e74705SXin Li else if (II->isStr("ucontext_t"))
5417*67e74705SXin Li Context.setucontext_tDecl(NewTD);
5418*67e74705SXin Li }
5419*67e74705SXin Li
5420*67e74705SXin Li return NewTD;
5421*67e74705SXin Li }
5422*67e74705SXin Li
5423*67e74705SXin Li /// \brief Determines whether the given declaration is an out-of-scope
5424*67e74705SXin Li /// previous declaration.
5425*67e74705SXin Li ///
5426*67e74705SXin Li /// This routine should be invoked when name lookup has found a
5427*67e74705SXin Li /// previous declaration (PrevDecl) that is not in the scope where a
5428*67e74705SXin Li /// new declaration by the same name is being introduced. If the new
5429*67e74705SXin Li /// declaration occurs in a local scope, previous declarations with
5430*67e74705SXin Li /// linkage may still be considered previous declarations (C99
5431*67e74705SXin Li /// 6.2.2p4-5, C++ [basic.link]p6).
5432*67e74705SXin Li ///
5433*67e74705SXin Li /// \param PrevDecl the previous declaration found by name
5434*67e74705SXin Li /// lookup
5435*67e74705SXin Li ///
5436*67e74705SXin Li /// \param DC the context in which the new declaration is being
5437*67e74705SXin Li /// declared.
5438*67e74705SXin Li ///
5439*67e74705SXin Li /// \returns true if PrevDecl is an out-of-scope previous declaration
5440*67e74705SXin Li /// for a new delcaration with the same name.
5441*67e74705SXin Li static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)5442*67e74705SXin Li isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5443*67e74705SXin Li ASTContext &Context) {
5444*67e74705SXin Li if (!PrevDecl)
5445*67e74705SXin Li return false;
5446*67e74705SXin Li
5447*67e74705SXin Li if (!PrevDecl->hasLinkage())
5448*67e74705SXin Li return false;
5449*67e74705SXin Li
5450*67e74705SXin Li if (Context.getLangOpts().CPlusPlus) {
5451*67e74705SXin Li // C++ [basic.link]p6:
5452*67e74705SXin Li // If there is a visible declaration of an entity with linkage
5453*67e74705SXin Li // having the same name and type, ignoring entities declared
5454*67e74705SXin Li // outside the innermost enclosing namespace scope, the block
5455*67e74705SXin Li // scope declaration declares that same entity and receives the
5456*67e74705SXin Li // linkage of the previous declaration.
5457*67e74705SXin Li DeclContext *OuterContext = DC->getRedeclContext();
5458*67e74705SXin Li if (!OuterContext->isFunctionOrMethod())
5459*67e74705SXin Li // This rule only applies to block-scope declarations.
5460*67e74705SXin Li return false;
5461*67e74705SXin Li
5462*67e74705SXin Li DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5463*67e74705SXin Li if (PrevOuterContext->isRecord())
5464*67e74705SXin Li // We found a member function: ignore it.
5465*67e74705SXin Li return false;
5466*67e74705SXin Li
5467*67e74705SXin Li // Find the innermost enclosing namespace for the new and
5468*67e74705SXin Li // previous declarations.
5469*67e74705SXin Li OuterContext = OuterContext->getEnclosingNamespaceContext();
5470*67e74705SXin Li PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5471*67e74705SXin Li
5472*67e74705SXin Li // The previous declaration is in a different namespace, so it
5473*67e74705SXin Li // isn't the same function.
5474*67e74705SXin Li if (!OuterContext->Equals(PrevOuterContext))
5475*67e74705SXin Li return false;
5476*67e74705SXin Li }
5477*67e74705SXin Li
5478*67e74705SXin Li return true;
5479*67e74705SXin Li }
5480*67e74705SXin Li
SetNestedNameSpecifier(DeclaratorDecl * DD,Declarator & D)5481*67e74705SXin Li static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5482*67e74705SXin Li CXXScopeSpec &SS = D.getCXXScopeSpec();
5483*67e74705SXin Li if (!SS.isSet()) return;
5484*67e74705SXin Li DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5485*67e74705SXin Li }
5486*67e74705SXin Li
inferObjCARCLifetime(ValueDecl * decl)5487*67e74705SXin Li bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5488*67e74705SXin Li QualType type = decl->getType();
5489*67e74705SXin Li Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5490*67e74705SXin Li if (lifetime == Qualifiers::OCL_Autoreleasing) {
5491*67e74705SXin Li // Various kinds of declaration aren't allowed to be __autoreleasing.
5492*67e74705SXin Li unsigned kind = -1U;
5493*67e74705SXin Li if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5494*67e74705SXin Li if (var->hasAttr<BlocksAttr>())
5495*67e74705SXin Li kind = 0; // __block
5496*67e74705SXin Li else if (!var->hasLocalStorage())
5497*67e74705SXin Li kind = 1; // global
5498*67e74705SXin Li } else if (isa<ObjCIvarDecl>(decl)) {
5499*67e74705SXin Li kind = 3; // ivar
5500*67e74705SXin Li } else if (isa<FieldDecl>(decl)) {
5501*67e74705SXin Li kind = 2; // field
5502*67e74705SXin Li }
5503*67e74705SXin Li
5504*67e74705SXin Li if (kind != -1U) {
5505*67e74705SXin Li Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5506*67e74705SXin Li << kind;
5507*67e74705SXin Li }
5508*67e74705SXin Li } else if (lifetime == Qualifiers::OCL_None) {
5509*67e74705SXin Li // Try to infer lifetime.
5510*67e74705SXin Li if (!type->isObjCLifetimeType())
5511*67e74705SXin Li return false;
5512*67e74705SXin Li
5513*67e74705SXin Li lifetime = type->getObjCARCImplicitLifetime();
5514*67e74705SXin Li type = Context.getLifetimeQualifiedType(type, lifetime);
5515*67e74705SXin Li decl->setType(type);
5516*67e74705SXin Li }
5517*67e74705SXin Li
5518*67e74705SXin Li if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5519*67e74705SXin Li // Thread-local variables cannot have lifetime.
5520*67e74705SXin Li if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5521*67e74705SXin Li var->getTLSKind()) {
5522*67e74705SXin Li Diag(var->getLocation(), diag::err_arc_thread_ownership)
5523*67e74705SXin Li << var->getType();
5524*67e74705SXin Li return true;
5525*67e74705SXin Li }
5526*67e74705SXin Li }
5527*67e74705SXin Li
5528*67e74705SXin Li return false;
5529*67e74705SXin Li }
5530*67e74705SXin Li
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)5531*67e74705SXin Li static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5532*67e74705SXin Li // Ensure that an auto decl is deduced otherwise the checks below might cache
5533*67e74705SXin Li // the wrong linkage.
5534*67e74705SXin Li assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5535*67e74705SXin Li
5536*67e74705SXin Li // 'weak' only applies to declarations with external linkage.
5537*67e74705SXin Li if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5538*67e74705SXin Li if (!ND.isExternallyVisible()) {
5539*67e74705SXin Li S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5540*67e74705SXin Li ND.dropAttr<WeakAttr>();
5541*67e74705SXin Li }
5542*67e74705SXin Li }
5543*67e74705SXin Li if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5544*67e74705SXin Li if (ND.isExternallyVisible()) {
5545*67e74705SXin Li S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5546*67e74705SXin Li ND.dropAttr<WeakRefAttr>();
5547*67e74705SXin Li ND.dropAttr<AliasAttr>();
5548*67e74705SXin Li }
5549*67e74705SXin Li }
5550*67e74705SXin Li
5551*67e74705SXin Li if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5552*67e74705SXin Li if (VD->hasInit()) {
5553*67e74705SXin Li if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5554*67e74705SXin Li assert(VD->isThisDeclarationADefinition() &&
5555*67e74705SXin Li !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5556*67e74705SXin Li S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5557*67e74705SXin Li VD->dropAttr<AliasAttr>();
5558*67e74705SXin Li }
5559*67e74705SXin Li }
5560*67e74705SXin Li }
5561*67e74705SXin Li
5562*67e74705SXin Li // 'selectany' only applies to externally visible variable declarations.
5563*67e74705SXin Li // It does not apply to functions.
5564*67e74705SXin Li if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5565*67e74705SXin Li if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5566*67e74705SXin Li S.Diag(Attr->getLocation(),
5567*67e74705SXin Li diag::err_attribute_selectany_non_extern_data);
5568*67e74705SXin Li ND.dropAttr<SelectAnyAttr>();
5569*67e74705SXin Li }
5570*67e74705SXin Li }
5571*67e74705SXin Li
5572*67e74705SXin Li if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5573*67e74705SXin Li // dll attributes require external linkage. Static locals may have external
5574*67e74705SXin Li // linkage but still cannot be explicitly imported or exported.
5575*67e74705SXin Li auto *VD = dyn_cast<VarDecl>(&ND);
5576*67e74705SXin Li if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5577*67e74705SXin Li S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5578*67e74705SXin Li << &ND << Attr;
5579*67e74705SXin Li ND.setInvalidDecl();
5580*67e74705SXin Li }
5581*67e74705SXin Li }
5582*67e74705SXin Li
5583*67e74705SXin Li // Virtual functions cannot be marked as 'notail'.
5584*67e74705SXin Li if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5585*67e74705SXin Li if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5586*67e74705SXin Li if (MD->isVirtual()) {
5587*67e74705SXin Li S.Diag(ND.getLocation(),
5588*67e74705SXin Li diag::err_invalid_attribute_on_virtual_function)
5589*67e74705SXin Li << Attr;
5590*67e74705SXin Li ND.dropAttr<NotTailCalledAttr>();
5591*67e74705SXin Li }
5592*67e74705SXin Li }
5593*67e74705SXin Li
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)5594*67e74705SXin Li static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5595*67e74705SXin Li NamedDecl *NewDecl,
5596*67e74705SXin Li bool IsSpecialization,
5597*67e74705SXin Li bool IsDefinition) {
5598*67e74705SXin Li if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5599*67e74705SXin Li OldDecl = OldTD->getTemplatedDecl();
5600*67e74705SXin Li if (!IsSpecialization)
5601*67e74705SXin Li IsDefinition = false;
5602*67e74705SXin Li }
5603*67e74705SXin Li if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5604*67e74705SXin Li NewDecl = NewTD->getTemplatedDecl();
5605*67e74705SXin Li
5606*67e74705SXin Li if (!OldDecl || !NewDecl)
5607*67e74705SXin Li return;
5608*67e74705SXin Li
5609*67e74705SXin Li const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5610*67e74705SXin Li const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5611*67e74705SXin Li const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5612*67e74705SXin Li const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5613*67e74705SXin Li
5614*67e74705SXin Li // dllimport and dllexport are inheritable attributes so we have to exclude
5615*67e74705SXin Li // inherited attribute instances.
5616*67e74705SXin Li bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5617*67e74705SXin Li (NewExportAttr && !NewExportAttr->isInherited());
5618*67e74705SXin Li
5619*67e74705SXin Li // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5620*67e74705SXin Li // the only exception being explicit specializations.
5621*67e74705SXin Li // Implicitly generated declarations are also excluded for now because there
5622*67e74705SXin Li // is no other way to switch these to use dllimport or dllexport.
5623*67e74705SXin Li bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5624*67e74705SXin Li
5625*67e74705SXin Li if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5626*67e74705SXin Li // Allow with a warning for free functions and global variables.
5627*67e74705SXin Li bool JustWarn = false;
5628*67e74705SXin Li if (!OldDecl->isCXXClassMember()) {
5629*67e74705SXin Li auto *VD = dyn_cast<VarDecl>(OldDecl);
5630*67e74705SXin Li if (VD && !VD->getDescribedVarTemplate())
5631*67e74705SXin Li JustWarn = true;
5632*67e74705SXin Li auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5633*67e74705SXin Li if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5634*67e74705SXin Li JustWarn = true;
5635*67e74705SXin Li }
5636*67e74705SXin Li
5637*67e74705SXin Li // We cannot change a declaration that's been used because IR has already
5638*67e74705SXin Li // been emitted. Dllimported functions will still work though (modulo
5639*67e74705SXin Li // address equality) as they can use the thunk.
5640*67e74705SXin Li if (OldDecl->isUsed())
5641*67e74705SXin Li if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5642*67e74705SXin Li JustWarn = false;
5643*67e74705SXin Li
5644*67e74705SXin Li unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5645*67e74705SXin Li : diag::err_attribute_dll_redeclaration;
5646*67e74705SXin Li S.Diag(NewDecl->getLocation(), DiagID)
5647*67e74705SXin Li << NewDecl
5648*67e74705SXin Li << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5649*67e74705SXin Li S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5650*67e74705SXin Li if (!JustWarn) {
5651*67e74705SXin Li NewDecl->setInvalidDecl();
5652*67e74705SXin Li return;
5653*67e74705SXin Li }
5654*67e74705SXin Li }
5655*67e74705SXin Li
5656*67e74705SXin Li // A redeclaration is not allowed to drop a dllimport attribute, the only
5657*67e74705SXin Li // exceptions being inline function definitions, local extern declarations,
5658*67e74705SXin Li // qualified friend declarations or special MSVC extension: in the last case,
5659*67e74705SXin Li // the declaration is treated as if it were marked dllexport.
5660*67e74705SXin Li bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5661*67e74705SXin Li bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5662*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5663*67e74705SXin Li // Ignore static data because out-of-line definitions are diagnosed
5664*67e74705SXin Li // separately.
5665*67e74705SXin Li IsStaticDataMember = VD->isStaticDataMember();
5666*67e74705SXin Li IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5667*67e74705SXin Li VarDecl::DeclarationOnly;
5668*67e74705SXin Li } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5669*67e74705SXin Li IsInline = FD->isInlined();
5670*67e74705SXin Li IsQualifiedFriend = FD->getQualifier() &&
5671*67e74705SXin Li FD->getFriendObjectKind() == Decl::FOK_Declared;
5672*67e74705SXin Li }
5673*67e74705SXin Li
5674*67e74705SXin Li if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5675*67e74705SXin Li !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5676*67e74705SXin Li if (IsMicrosoft && IsDefinition) {
5677*67e74705SXin Li S.Diag(NewDecl->getLocation(),
5678*67e74705SXin Li diag::warn_redeclaration_without_import_attribute)
5679*67e74705SXin Li << NewDecl;
5680*67e74705SXin Li S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5681*67e74705SXin Li NewDecl->dropAttr<DLLImportAttr>();
5682*67e74705SXin Li NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5683*67e74705SXin Li NewImportAttr->getRange(), S.Context,
5684*67e74705SXin Li NewImportAttr->getSpellingListIndex()));
5685*67e74705SXin Li } else {
5686*67e74705SXin Li S.Diag(NewDecl->getLocation(),
5687*67e74705SXin Li diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5688*67e74705SXin Li << NewDecl << OldImportAttr;
5689*67e74705SXin Li S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5690*67e74705SXin Li S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5691*67e74705SXin Li OldDecl->dropAttr<DLLImportAttr>();
5692*67e74705SXin Li NewDecl->dropAttr<DLLImportAttr>();
5693*67e74705SXin Li }
5694*67e74705SXin Li } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5695*67e74705SXin Li // In MinGW, seeing a function declared inline drops the dllimport attribute.
5696*67e74705SXin Li OldDecl->dropAttr<DLLImportAttr>();
5697*67e74705SXin Li NewDecl->dropAttr<DLLImportAttr>();
5698*67e74705SXin Li S.Diag(NewDecl->getLocation(),
5699*67e74705SXin Li diag::warn_dllimport_dropped_from_inline_function)
5700*67e74705SXin Li << NewDecl << OldImportAttr;
5701*67e74705SXin Li }
5702*67e74705SXin Li }
5703*67e74705SXin Li
5704*67e74705SXin Li /// Given that we are within the definition of the given function,
5705*67e74705SXin Li /// will that definition behave like C99's 'inline', where the
5706*67e74705SXin Li /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)5707*67e74705SXin Li static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5708*67e74705SXin Li // Try to avoid calling GetGVALinkageForFunction.
5709*67e74705SXin Li
5710*67e74705SXin Li // All cases of this require the 'inline' keyword.
5711*67e74705SXin Li if (!FD->isInlined()) return false;
5712*67e74705SXin Li
5713*67e74705SXin Li // This is only possible in C++ with the gnu_inline attribute.
5714*67e74705SXin Li if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5715*67e74705SXin Li return false;
5716*67e74705SXin Li
5717*67e74705SXin Li // Okay, go ahead and call the relatively-more-expensive function.
5718*67e74705SXin Li
5719*67e74705SXin Li #ifndef NDEBUG
5720*67e74705SXin Li // AST quite reasonably asserts that it's working on a function
5721*67e74705SXin Li // definition. We don't really have a way to tell it that we're
5722*67e74705SXin Li // currently defining the function, so just lie to it in +Asserts
5723*67e74705SXin Li // builds. This is an awful hack.
5724*67e74705SXin Li FD->setLazyBody(1);
5725*67e74705SXin Li #endif
5726*67e74705SXin Li
5727*67e74705SXin Li bool isC99Inline =
5728*67e74705SXin Li S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5729*67e74705SXin Li
5730*67e74705SXin Li #ifndef NDEBUG
5731*67e74705SXin Li FD->setLazyBody(0);
5732*67e74705SXin Li #endif
5733*67e74705SXin Li
5734*67e74705SXin Li return isC99Inline;
5735*67e74705SXin Li }
5736*67e74705SXin Li
5737*67e74705SXin Li /// Determine whether a variable is extern "C" prior to attaching
5738*67e74705SXin Li /// an initializer. We can't just call isExternC() here, because that
5739*67e74705SXin Li /// will also compute and cache whether the declaration is externally
5740*67e74705SXin Li /// visible, which might change when we attach the initializer.
5741*67e74705SXin Li ///
5742*67e74705SXin Li /// This can only be used if the declaration is known to not be a
5743*67e74705SXin Li /// redeclaration of an internal linkage declaration.
5744*67e74705SXin Li ///
5745*67e74705SXin Li /// For instance:
5746*67e74705SXin Li ///
5747*67e74705SXin Li /// auto x = []{};
5748*67e74705SXin Li ///
5749*67e74705SXin Li /// Attaching the initializer here makes this declaration not externally
5750*67e74705SXin Li /// visible, because its type has internal linkage.
5751*67e74705SXin Li ///
5752*67e74705SXin Li /// FIXME: This is a hack.
5753*67e74705SXin Li template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)5754*67e74705SXin Li static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5755*67e74705SXin Li if (S.getLangOpts().CPlusPlus) {
5756*67e74705SXin Li // In C++, the overloadable attribute negates the effects of extern "C".
5757*67e74705SXin Li if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5758*67e74705SXin Li return false;
5759*67e74705SXin Li
5760*67e74705SXin Li // So do CUDA's host/device attributes.
5761*67e74705SXin Li if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5762*67e74705SXin Li D->template hasAttr<CUDAHostAttr>()))
5763*67e74705SXin Li return false;
5764*67e74705SXin Li }
5765*67e74705SXin Li return D->isExternC();
5766*67e74705SXin Li }
5767*67e74705SXin Li
shouldConsiderLinkage(const VarDecl * VD)5768*67e74705SXin Li static bool shouldConsiderLinkage(const VarDecl *VD) {
5769*67e74705SXin Li const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5770*67e74705SXin Li if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5771*67e74705SXin Li return VD->hasExternalStorage();
5772*67e74705SXin Li if (DC->isFileContext())
5773*67e74705SXin Li return true;
5774*67e74705SXin Li if (DC->isRecord())
5775*67e74705SXin Li return false;
5776*67e74705SXin Li llvm_unreachable("Unexpected context");
5777*67e74705SXin Li }
5778*67e74705SXin Li
shouldConsiderLinkage(const FunctionDecl * FD)5779*67e74705SXin Li static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5780*67e74705SXin Li const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5781*67e74705SXin Li if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5782*67e74705SXin Li isa<OMPDeclareReductionDecl>(DC))
5783*67e74705SXin Li return true;
5784*67e74705SXin Li if (DC->isRecord())
5785*67e74705SXin Li return false;
5786*67e74705SXin Li llvm_unreachable("Unexpected context");
5787*67e74705SXin Li }
5788*67e74705SXin Li
hasParsedAttr(Scope * S,const AttributeList * AttrList,AttributeList::Kind Kind)5789*67e74705SXin Li static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5790*67e74705SXin Li AttributeList::Kind Kind) {
5791*67e74705SXin Li for (const AttributeList *L = AttrList; L; L = L->getNext())
5792*67e74705SXin Li if (L->getKind() == Kind)
5793*67e74705SXin Li return true;
5794*67e74705SXin Li return false;
5795*67e74705SXin Li }
5796*67e74705SXin Li
hasParsedAttr(Scope * S,const Declarator & PD,AttributeList::Kind Kind)5797*67e74705SXin Li static bool hasParsedAttr(Scope *S, const Declarator &PD,
5798*67e74705SXin Li AttributeList::Kind Kind) {
5799*67e74705SXin Li // Check decl attributes on the DeclSpec.
5800*67e74705SXin Li if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5801*67e74705SXin Li return true;
5802*67e74705SXin Li
5803*67e74705SXin Li // Walk the declarator structure, checking decl attributes that were in a type
5804*67e74705SXin Li // position to the decl itself.
5805*67e74705SXin Li for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5806*67e74705SXin Li if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5807*67e74705SXin Li return true;
5808*67e74705SXin Li }
5809*67e74705SXin Li
5810*67e74705SXin Li // Finally, check attributes on the decl itself.
5811*67e74705SXin Li return hasParsedAttr(S, PD.getAttributes(), Kind);
5812*67e74705SXin Li }
5813*67e74705SXin Li
5814*67e74705SXin Li /// Adjust the \c DeclContext for a function or variable that might be a
5815*67e74705SXin Li /// function-local external declaration.
adjustContextForLocalExternDecl(DeclContext * & DC)5816*67e74705SXin Li bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5817*67e74705SXin Li if (!DC->isFunctionOrMethod())
5818*67e74705SXin Li return false;
5819*67e74705SXin Li
5820*67e74705SXin Li // If this is a local extern function or variable declared within a function
5821*67e74705SXin Li // template, don't add it into the enclosing namespace scope until it is
5822*67e74705SXin Li // instantiated; it might have a dependent type right now.
5823*67e74705SXin Li if (DC->isDependentContext())
5824*67e74705SXin Li return true;
5825*67e74705SXin Li
5826*67e74705SXin Li // C++11 [basic.link]p7:
5827*67e74705SXin Li // When a block scope declaration of an entity with linkage is not found to
5828*67e74705SXin Li // refer to some other declaration, then that entity is a member of the
5829*67e74705SXin Li // innermost enclosing namespace.
5830*67e74705SXin Li //
5831*67e74705SXin Li // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5832*67e74705SXin Li // semantically-enclosing namespace, not a lexically-enclosing one.
5833*67e74705SXin Li while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5834*67e74705SXin Li DC = DC->getParent();
5835*67e74705SXin Li return true;
5836*67e74705SXin Li }
5837*67e74705SXin Li
5838*67e74705SXin Li /// \brief Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)5839*67e74705SXin Li static bool isDeclExternC(const Decl *D) {
5840*67e74705SXin Li if (const auto *FD = dyn_cast<FunctionDecl>(D))
5841*67e74705SXin Li return FD->isExternC();
5842*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(D))
5843*67e74705SXin Li return VD->isExternC();
5844*67e74705SXin Li
5845*67e74705SXin Li llvm_unreachable("Unknown type of decl!");
5846*67e74705SXin Li }
5847*67e74705SXin Li
5848*67e74705SXin Li NamedDecl *
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope)5849*67e74705SXin Li Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5850*67e74705SXin Li TypeSourceInfo *TInfo, LookupResult &Previous,
5851*67e74705SXin Li MultiTemplateParamsArg TemplateParamLists,
5852*67e74705SXin Li bool &AddToScope) {
5853*67e74705SXin Li QualType R = TInfo->getType();
5854*67e74705SXin Li DeclarationName Name = GetNameForDeclarator(D).getName();
5855*67e74705SXin Li
5856*67e74705SXin Li // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5857*67e74705SXin Li // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5858*67e74705SXin Li // argument.
5859*67e74705SXin Li if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5860*67e74705SXin Li Diag(D.getIdentifierLoc(),
5861*67e74705SXin Li diag::err_opencl_type_can_only_be_used_as_function_parameter)
5862*67e74705SXin Li << R;
5863*67e74705SXin Li D.setInvalidType();
5864*67e74705SXin Li return nullptr;
5865*67e74705SXin Li }
5866*67e74705SXin Li
5867*67e74705SXin Li DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5868*67e74705SXin Li StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5869*67e74705SXin Li
5870*67e74705SXin Li // dllimport globals without explicit storage class are treated as extern. We
5871*67e74705SXin Li // have to change the storage class this early to get the right DeclContext.
5872*67e74705SXin Li if (SC == SC_None && !DC->isRecord() &&
5873*67e74705SXin Li hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5874*67e74705SXin Li !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5875*67e74705SXin Li SC = SC_Extern;
5876*67e74705SXin Li
5877*67e74705SXin Li DeclContext *OriginalDC = DC;
5878*67e74705SXin Li bool IsLocalExternDecl = SC == SC_Extern &&
5879*67e74705SXin Li adjustContextForLocalExternDecl(DC);
5880*67e74705SXin Li
5881*67e74705SXin Li if (getLangOpts().OpenCL) {
5882*67e74705SXin Li // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5883*67e74705SXin Li QualType NR = R;
5884*67e74705SXin Li while (NR->isPointerType()) {
5885*67e74705SXin Li if (NR->isFunctionPointerType()) {
5886*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5887*67e74705SXin Li D.setInvalidType();
5888*67e74705SXin Li break;
5889*67e74705SXin Li }
5890*67e74705SXin Li NR = NR->getPointeeType();
5891*67e74705SXin Li }
5892*67e74705SXin Li
5893*67e74705SXin Li if (!getOpenCLOptions().cl_khr_fp16) {
5894*67e74705SXin Li // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5895*67e74705SXin Li // half array type (unless the cl_khr_fp16 extension is enabled).
5896*67e74705SXin Li if (Context.getBaseElementType(R)->isHalfType()) {
5897*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5898*67e74705SXin Li D.setInvalidType();
5899*67e74705SXin Li }
5900*67e74705SXin Li }
5901*67e74705SXin Li }
5902*67e74705SXin Li
5903*67e74705SXin Li if (SCSpec == DeclSpec::SCS_mutable) {
5904*67e74705SXin Li // mutable can only appear on non-static class members, so it's always
5905*67e74705SXin Li // an error here
5906*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5907*67e74705SXin Li D.setInvalidType();
5908*67e74705SXin Li SC = SC_None;
5909*67e74705SXin Li }
5910*67e74705SXin Li
5911*67e74705SXin Li if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5912*67e74705SXin Li !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5913*67e74705SXin Li D.getDeclSpec().getStorageClassSpecLoc())) {
5914*67e74705SXin Li // In C++11, the 'register' storage class specifier is deprecated.
5915*67e74705SXin Li // Suppress the warning in system macros, it's used in macros in some
5916*67e74705SXin Li // popular C system headers, such as in glibc's htonl() macro.
5917*67e74705SXin Li Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5918*67e74705SXin Li getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5919*67e74705SXin Li : diag::warn_deprecated_register)
5920*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5921*67e74705SXin Li }
5922*67e74705SXin Li
5923*67e74705SXin Li IdentifierInfo *II = Name.getAsIdentifierInfo();
5924*67e74705SXin Li if (!II) {
5925*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5926*67e74705SXin Li << Name;
5927*67e74705SXin Li return nullptr;
5928*67e74705SXin Li }
5929*67e74705SXin Li
5930*67e74705SXin Li DiagnoseFunctionSpecifiers(D.getDeclSpec());
5931*67e74705SXin Li
5932*67e74705SXin Li if (!DC->isRecord() && S->getFnParent() == nullptr) {
5933*67e74705SXin Li // C99 6.9p2: The storage-class specifiers auto and register shall not
5934*67e74705SXin Li // appear in the declaration specifiers in an external declaration.
5935*67e74705SXin Li // Global Register+Asm is a GNU extension we support.
5936*67e74705SXin Li if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5937*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5938*67e74705SXin Li D.setInvalidType();
5939*67e74705SXin Li }
5940*67e74705SXin Li }
5941*67e74705SXin Li
5942*67e74705SXin Li if (getLangOpts().OpenCL) {
5943*67e74705SXin Li // OpenCL v1.2 s6.9.b p4:
5944*67e74705SXin Li // The sampler type cannot be used with the __local and __global address
5945*67e74705SXin Li // space qualifiers.
5946*67e74705SXin Li if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5947*67e74705SXin Li R.getAddressSpace() == LangAS::opencl_global)) {
5948*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5949*67e74705SXin Li }
5950*67e74705SXin Li
5951*67e74705SXin Li // OpenCL 1.2 spec, p6.9 r:
5952*67e74705SXin Li // The event type cannot be used to declare a program scope variable.
5953*67e74705SXin Li // The event type cannot be used with the __local, __constant and __global
5954*67e74705SXin Li // address space qualifiers.
5955*67e74705SXin Li if (R->isEventT()) {
5956*67e74705SXin Li if (S->getParent() == nullptr) {
5957*67e74705SXin Li Diag(D.getLocStart(), diag::err_event_t_global_var);
5958*67e74705SXin Li D.setInvalidType();
5959*67e74705SXin Li }
5960*67e74705SXin Li
5961*67e74705SXin Li if (R.getAddressSpace()) {
5962*67e74705SXin Li Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5963*67e74705SXin Li D.setInvalidType();
5964*67e74705SXin Li }
5965*67e74705SXin Li }
5966*67e74705SXin Li }
5967*67e74705SXin Li
5968*67e74705SXin Li bool IsExplicitSpecialization = false;
5969*67e74705SXin Li bool IsVariableTemplateSpecialization = false;
5970*67e74705SXin Li bool IsPartialSpecialization = false;
5971*67e74705SXin Li bool IsVariableTemplate = false;
5972*67e74705SXin Li VarDecl *NewVD = nullptr;
5973*67e74705SXin Li VarTemplateDecl *NewTemplate = nullptr;
5974*67e74705SXin Li TemplateParameterList *TemplateParams = nullptr;
5975*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
5976*67e74705SXin Li NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5977*67e74705SXin Li D.getIdentifierLoc(), II,
5978*67e74705SXin Li R, TInfo, SC);
5979*67e74705SXin Li
5980*67e74705SXin Li if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5981*67e74705SXin Li ParsingInitForAutoVars.insert(NewVD);
5982*67e74705SXin Li
5983*67e74705SXin Li if (D.isInvalidType())
5984*67e74705SXin Li NewVD->setInvalidDecl();
5985*67e74705SXin Li } else {
5986*67e74705SXin Li bool Invalid = false;
5987*67e74705SXin Li
5988*67e74705SXin Li if (DC->isRecord() && !CurContext->isRecord()) {
5989*67e74705SXin Li // This is an out-of-line definition of a static data member.
5990*67e74705SXin Li switch (SC) {
5991*67e74705SXin Li case SC_None:
5992*67e74705SXin Li break;
5993*67e74705SXin Li case SC_Static:
5994*67e74705SXin Li Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5995*67e74705SXin Li diag::err_static_out_of_line)
5996*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5997*67e74705SXin Li break;
5998*67e74705SXin Li case SC_Auto:
5999*67e74705SXin Li case SC_Register:
6000*67e74705SXin Li case SC_Extern:
6001*67e74705SXin Li // [dcl.stc] p2: The auto or register specifiers shall be applied only
6002*67e74705SXin Li // to names of variables declared in a block or to function parameters.
6003*67e74705SXin Li // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6004*67e74705SXin Li // of class members
6005*67e74705SXin Li
6006*67e74705SXin Li Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6007*67e74705SXin Li diag::err_storage_class_for_static_member)
6008*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6009*67e74705SXin Li break;
6010*67e74705SXin Li case SC_PrivateExtern:
6011*67e74705SXin Li llvm_unreachable("C storage class in c++!");
6012*67e74705SXin Li }
6013*67e74705SXin Li }
6014*67e74705SXin Li
6015*67e74705SXin Li if (SC == SC_Static && CurContext->isRecord()) {
6016*67e74705SXin Li if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6017*67e74705SXin Li if (RD->isLocalClass())
6018*67e74705SXin Li Diag(D.getIdentifierLoc(),
6019*67e74705SXin Li diag::err_static_data_member_not_allowed_in_local_class)
6020*67e74705SXin Li << Name << RD->getDeclName();
6021*67e74705SXin Li
6022*67e74705SXin Li // C++98 [class.union]p1: If a union contains a static data member,
6023*67e74705SXin Li // the program is ill-formed. C++11 drops this restriction.
6024*67e74705SXin Li if (RD->isUnion())
6025*67e74705SXin Li Diag(D.getIdentifierLoc(),
6026*67e74705SXin Li getLangOpts().CPlusPlus11
6027*67e74705SXin Li ? diag::warn_cxx98_compat_static_data_member_in_union
6028*67e74705SXin Li : diag::ext_static_data_member_in_union) << Name;
6029*67e74705SXin Li // We conservatively disallow static data members in anonymous structs.
6030*67e74705SXin Li else if (!RD->getDeclName())
6031*67e74705SXin Li Diag(D.getIdentifierLoc(),
6032*67e74705SXin Li diag::err_static_data_member_not_allowed_in_anon_struct)
6033*67e74705SXin Li << Name << RD->isUnion();
6034*67e74705SXin Li }
6035*67e74705SXin Li }
6036*67e74705SXin Li
6037*67e74705SXin Li // Match up the template parameter lists with the scope specifier, then
6038*67e74705SXin Li // determine whether we have a template or a template specialization.
6039*67e74705SXin Li TemplateParams = MatchTemplateParametersToScopeSpecifier(
6040*67e74705SXin Li D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6041*67e74705SXin Li D.getCXXScopeSpec(),
6042*67e74705SXin Li D.getName().getKind() == UnqualifiedId::IK_TemplateId
6043*67e74705SXin Li ? D.getName().TemplateId
6044*67e74705SXin Li : nullptr,
6045*67e74705SXin Li TemplateParamLists,
6046*67e74705SXin Li /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6047*67e74705SXin Li
6048*67e74705SXin Li if (TemplateParams) {
6049*67e74705SXin Li if (!TemplateParams->size() &&
6050*67e74705SXin Li D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6051*67e74705SXin Li // There is an extraneous 'template<>' for this variable. Complain
6052*67e74705SXin Li // about it, but allow the declaration of the variable.
6053*67e74705SXin Li Diag(TemplateParams->getTemplateLoc(),
6054*67e74705SXin Li diag::err_template_variable_noparams)
6055*67e74705SXin Li << II
6056*67e74705SXin Li << SourceRange(TemplateParams->getTemplateLoc(),
6057*67e74705SXin Li TemplateParams->getRAngleLoc());
6058*67e74705SXin Li TemplateParams = nullptr;
6059*67e74705SXin Li } else {
6060*67e74705SXin Li if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6061*67e74705SXin Li // This is an explicit specialization or a partial specialization.
6062*67e74705SXin Li // FIXME: Check that we can declare a specialization here.
6063*67e74705SXin Li IsVariableTemplateSpecialization = true;
6064*67e74705SXin Li IsPartialSpecialization = TemplateParams->size() > 0;
6065*67e74705SXin Li } else { // if (TemplateParams->size() > 0)
6066*67e74705SXin Li // This is a template declaration.
6067*67e74705SXin Li IsVariableTemplate = true;
6068*67e74705SXin Li
6069*67e74705SXin Li // Check that we can declare a template here.
6070*67e74705SXin Li if (CheckTemplateDeclScope(S, TemplateParams))
6071*67e74705SXin Li return nullptr;
6072*67e74705SXin Li
6073*67e74705SXin Li // Only C++1y supports variable templates (N3651).
6074*67e74705SXin Li Diag(D.getIdentifierLoc(),
6075*67e74705SXin Li getLangOpts().CPlusPlus14
6076*67e74705SXin Li ? diag::warn_cxx11_compat_variable_template
6077*67e74705SXin Li : diag::ext_variable_template);
6078*67e74705SXin Li }
6079*67e74705SXin Li }
6080*67e74705SXin Li } else {
6081*67e74705SXin Li assert(
6082*67e74705SXin Li (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6083*67e74705SXin Li "should have a 'template<>' for this decl");
6084*67e74705SXin Li }
6085*67e74705SXin Li
6086*67e74705SXin Li if (IsVariableTemplateSpecialization) {
6087*67e74705SXin Li SourceLocation TemplateKWLoc =
6088*67e74705SXin Li TemplateParamLists.size() > 0
6089*67e74705SXin Li ? TemplateParamLists[0]->getTemplateLoc()
6090*67e74705SXin Li : SourceLocation();
6091*67e74705SXin Li DeclResult Res = ActOnVarTemplateSpecialization(
6092*67e74705SXin Li S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6093*67e74705SXin Li IsPartialSpecialization);
6094*67e74705SXin Li if (Res.isInvalid())
6095*67e74705SXin Li return nullptr;
6096*67e74705SXin Li NewVD = cast<VarDecl>(Res.get());
6097*67e74705SXin Li AddToScope = false;
6098*67e74705SXin Li } else
6099*67e74705SXin Li NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6100*67e74705SXin Li D.getIdentifierLoc(), II, R, TInfo, SC);
6101*67e74705SXin Li
6102*67e74705SXin Li // If this is supposed to be a variable template, create it as such.
6103*67e74705SXin Li if (IsVariableTemplate) {
6104*67e74705SXin Li NewTemplate =
6105*67e74705SXin Li VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6106*67e74705SXin Li TemplateParams, NewVD);
6107*67e74705SXin Li NewVD->setDescribedVarTemplate(NewTemplate);
6108*67e74705SXin Li }
6109*67e74705SXin Li
6110*67e74705SXin Li // If this decl has an auto type in need of deduction, make a note of the
6111*67e74705SXin Li // Decl so we can diagnose uses of it in its own initializer.
6112*67e74705SXin Li if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6113*67e74705SXin Li ParsingInitForAutoVars.insert(NewVD);
6114*67e74705SXin Li
6115*67e74705SXin Li if (D.isInvalidType() || Invalid) {
6116*67e74705SXin Li NewVD->setInvalidDecl();
6117*67e74705SXin Li if (NewTemplate)
6118*67e74705SXin Li NewTemplate->setInvalidDecl();
6119*67e74705SXin Li }
6120*67e74705SXin Li
6121*67e74705SXin Li SetNestedNameSpecifier(NewVD, D);
6122*67e74705SXin Li
6123*67e74705SXin Li // If we have any template parameter lists that don't directly belong to
6124*67e74705SXin Li // the variable (matching the scope specifier), store them.
6125*67e74705SXin Li unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6126*67e74705SXin Li if (TemplateParamLists.size() > VDTemplateParamLists)
6127*67e74705SXin Li NewVD->setTemplateParameterListsInfo(
6128*67e74705SXin Li Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6129*67e74705SXin Li
6130*67e74705SXin Li if (D.getDeclSpec().isConstexprSpecified()) {
6131*67e74705SXin Li NewVD->setConstexpr(true);
6132*67e74705SXin Li // C++1z [dcl.spec.constexpr]p1:
6133*67e74705SXin Li // A static data member declared with the constexpr specifier is
6134*67e74705SXin Li // implicitly an inline variable.
6135*67e74705SXin Li if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6136*67e74705SXin Li NewVD->setImplicitlyInline();
6137*67e74705SXin Li }
6138*67e74705SXin Li
6139*67e74705SXin Li if (D.getDeclSpec().isConceptSpecified()) {
6140*67e74705SXin Li if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6141*67e74705SXin Li VTD->setConcept();
6142*67e74705SXin Li
6143*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6144*67e74705SXin Li // be declared with the thread_local, inline, friend, or constexpr
6145*67e74705SXin Li // specifiers, [...]
6146*67e74705SXin Li if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6147*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6148*67e74705SXin Li diag::err_concept_decl_invalid_specifiers)
6149*67e74705SXin Li << 0 << 0;
6150*67e74705SXin Li NewVD->setInvalidDecl(true);
6151*67e74705SXin Li }
6152*67e74705SXin Li
6153*67e74705SXin Li if (D.getDeclSpec().isConstexprSpecified()) {
6154*67e74705SXin Li Diag(D.getDeclSpec().getConstexprSpecLoc(),
6155*67e74705SXin Li diag::err_concept_decl_invalid_specifiers)
6156*67e74705SXin Li << 0 << 3;
6157*67e74705SXin Li NewVD->setInvalidDecl(true);
6158*67e74705SXin Li }
6159*67e74705SXin Li
6160*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6161*67e74705SXin Li // applied only to the definition of a function template or variable
6162*67e74705SXin Li // template, declared in namespace scope.
6163*67e74705SXin Li if (IsVariableTemplateSpecialization) {
6164*67e74705SXin Li Diag(D.getDeclSpec().getConceptSpecLoc(),
6165*67e74705SXin Li diag::err_concept_specified_specialization)
6166*67e74705SXin Li << (IsPartialSpecialization ? 2 : 1);
6167*67e74705SXin Li }
6168*67e74705SXin Li
6169*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6170*67e74705SXin Li // following restrictions:
6171*67e74705SXin Li // - The declared type shall have the type bool.
6172*67e74705SXin Li if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6173*67e74705SXin Li !NewVD->isInvalidDecl()) {
6174*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6175*67e74705SXin Li NewVD->setInvalidDecl(true);
6176*67e74705SXin Li }
6177*67e74705SXin Li }
6178*67e74705SXin Li }
6179*67e74705SXin Li
6180*67e74705SXin Li if (D.getDeclSpec().isInlineSpecified()) {
6181*67e74705SXin Li if (CurContext->isFunctionOrMethod()) {
6182*67e74705SXin Li // 'inline' is not allowed on block scope variable declaration.
6183*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(),
6184*67e74705SXin Li diag::err_inline_declaration_block_scope) << Name
6185*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6186*67e74705SXin Li } else {
6187*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(),
6188*67e74705SXin Li getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6189*67e74705SXin Li : diag::ext_inline_variable);
6190*67e74705SXin Li NewVD->setInlineSpecified();
6191*67e74705SXin Li }
6192*67e74705SXin Li }
6193*67e74705SXin Li
6194*67e74705SXin Li // Set the lexical context. If the declarator has a C++ scope specifier, the
6195*67e74705SXin Li // lexical context will be different from the semantic context.
6196*67e74705SXin Li NewVD->setLexicalDeclContext(CurContext);
6197*67e74705SXin Li if (NewTemplate)
6198*67e74705SXin Li NewTemplate->setLexicalDeclContext(CurContext);
6199*67e74705SXin Li
6200*67e74705SXin Li if (IsLocalExternDecl)
6201*67e74705SXin Li NewVD->setLocalExternDecl();
6202*67e74705SXin Li
6203*67e74705SXin Li bool EmitTLSUnsupportedError = false;
6204*67e74705SXin Li if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6205*67e74705SXin Li // C++11 [dcl.stc]p4:
6206*67e74705SXin Li // When thread_local is applied to a variable of block scope the
6207*67e74705SXin Li // storage-class-specifier static is implied if it does not appear
6208*67e74705SXin Li // explicitly.
6209*67e74705SXin Li // Core issue: 'static' is not implied if the variable is declared
6210*67e74705SXin Li // 'extern'.
6211*67e74705SXin Li if (NewVD->hasLocalStorage() &&
6212*67e74705SXin Li (SCSpec != DeclSpec::SCS_unspecified ||
6213*67e74705SXin Li TSCS != DeclSpec::TSCS_thread_local ||
6214*67e74705SXin Li !DC->isFunctionOrMethod()))
6215*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6216*67e74705SXin Li diag::err_thread_non_global)
6217*67e74705SXin Li << DeclSpec::getSpecifierName(TSCS);
6218*67e74705SXin Li else if (!Context.getTargetInfo().isTLSSupported()) {
6219*67e74705SXin Li if (getLangOpts().CUDA) {
6220*67e74705SXin Li // Postpone error emission until we've collected attributes required to
6221*67e74705SXin Li // figure out whether it's a host or device variable and whether the
6222*67e74705SXin Li // error should be ignored.
6223*67e74705SXin Li EmitTLSUnsupportedError = true;
6224*67e74705SXin Li // We still need to mark the variable as TLS so it shows up in AST with
6225*67e74705SXin Li // proper storage class for other tools to use even if we're not going
6226*67e74705SXin Li // to emit any code for it.
6227*67e74705SXin Li NewVD->setTSCSpec(TSCS);
6228*67e74705SXin Li } else
6229*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6230*67e74705SXin Li diag::err_thread_unsupported);
6231*67e74705SXin Li } else
6232*67e74705SXin Li NewVD->setTSCSpec(TSCS);
6233*67e74705SXin Li }
6234*67e74705SXin Li
6235*67e74705SXin Li // C99 6.7.4p3
6236*67e74705SXin Li // An inline definition of a function with external linkage shall
6237*67e74705SXin Li // not contain a definition of a modifiable object with static or
6238*67e74705SXin Li // thread storage duration...
6239*67e74705SXin Li // We only apply this when the function is required to be defined
6240*67e74705SXin Li // elsewhere, i.e. when the function is not 'extern inline'. Note
6241*67e74705SXin Li // that a local variable with thread storage duration still has to
6242*67e74705SXin Li // be marked 'static'. Also note that it's possible to get these
6243*67e74705SXin Li // semantics in C++ using __attribute__((gnu_inline)).
6244*67e74705SXin Li if (SC == SC_Static && S->getFnParent() != nullptr &&
6245*67e74705SXin Li !NewVD->getType().isConstQualified()) {
6246*67e74705SXin Li FunctionDecl *CurFD = getCurFunctionDecl();
6247*67e74705SXin Li if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6248*67e74705SXin Li Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6249*67e74705SXin Li diag::warn_static_local_in_extern_inline);
6250*67e74705SXin Li MaybeSuggestAddingStaticToDecl(CurFD);
6251*67e74705SXin Li }
6252*67e74705SXin Li }
6253*67e74705SXin Li
6254*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified()) {
6255*67e74705SXin Li if (IsVariableTemplateSpecialization)
6256*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6257*67e74705SXin Li << (IsPartialSpecialization ? 1 : 0)
6258*67e74705SXin Li << FixItHint::CreateRemoval(
6259*67e74705SXin Li D.getDeclSpec().getModulePrivateSpecLoc());
6260*67e74705SXin Li else if (IsExplicitSpecialization)
6261*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6262*67e74705SXin Li << 2
6263*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6264*67e74705SXin Li else if (NewVD->hasLocalStorage())
6265*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_module_private_local)
6266*67e74705SXin Li << 0 << NewVD->getDeclName()
6267*67e74705SXin Li << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6268*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6269*67e74705SXin Li else {
6270*67e74705SXin Li NewVD->setModulePrivate();
6271*67e74705SXin Li if (NewTemplate)
6272*67e74705SXin Li NewTemplate->setModulePrivate();
6273*67e74705SXin Li }
6274*67e74705SXin Li }
6275*67e74705SXin Li
6276*67e74705SXin Li // Handle attributes prior to checking for duplicates in MergeVarDecl
6277*67e74705SXin Li ProcessDeclAttributes(S, NewVD, D);
6278*67e74705SXin Li
6279*67e74705SXin Li if (getLangOpts().CUDA) {
6280*67e74705SXin Li if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6281*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6282*67e74705SXin Li diag::err_thread_unsupported);
6283*67e74705SXin Li // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6284*67e74705SXin Li // storage [duration]."
6285*67e74705SXin Li if (SC == SC_None && S->getFnParent() != nullptr &&
6286*67e74705SXin Li (NewVD->hasAttr<CUDASharedAttr>() ||
6287*67e74705SXin Li NewVD->hasAttr<CUDAConstantAttr>())) {
6288*67e74705SXin Li NewVD->setStorageClass(SC_Static);
6289*67e74705SXin Li }
6290*67e74705SXin Li }
6291*67e74705SXin Li
6292*67e74705SXin Li // Ensure that dllimport globals without explicit storage class are treated as
6293*67e74705SXin Li // extern. The storage class is set above using parsed attributes. Now we can
6294*67e74705SXin Li // check the VarDecl itself.
6295*67e74705SXin Li assert(!NewVD->hasAttr<DLLImportAttr>() ||
6296*67e74705SXin Li NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6297*67e74705SXin Li NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6298*67e74705SXin Li
6299*67e74705SXin Li // In auto-retain/release, infer strong retension for variables of
6300*67e74705SXin Li // retainable type.
6301*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6302*67e74705SXin Li NewVD->setInvalidDecl();
6303*67e74705SXin Li
6304*67e74705SXin Li // Handle GNU asm-label extension (encoded as an attribute).
6305*67e74705SXin Li if (Expr *E = (Expr*)D.getAsmLabel()) {
6306*67e74705SXin Li // The parser guarantees this is a string.
6307*67e74705SXin Li StringLiteral *SE = cast<StringLiteral>(E);
6308*67e74705SXin Li StringRef Label = SE->getString();
6309*67e74705SXin Li if (S->getFnParent() != nullptr) {
6310*67e74705SXin Li switch (SC) {
6311*67e74705SXin Li case SC_None:
6312*67e74705SXin Li case SC_Auto:
6313*67e74705SXin Li Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6314*67e74705SXin Li break;
6315*67e74705SXin Li case SC_Register:
6316*67e74705SXin Li // Local Named register
6317*67e74705SXin Li if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6318*67e74705SXin Li DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6319*67e74705SXin Li Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6320*67e74705SXin Li break;
6321*67e74705SXin Li case SC_Static:
6322*67e74705SXin Li case SC_Extern:
6323*67e74705SXin Li case SC_PrivateExtern:
6324*67e74705SXin Li break;
6325*67e74705SXin Li }
6326*67e74705SXin Li } else if (SC == SC_Register) {
6327*67e74705SXin Li // Global Named register
6328*67e74705SXin Li if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6329*67e74705SXin Li const auto &TI = Context.getTargetInfo();
6330*67e74705SXin Li bool HasSizeMismatch;
6331*67e74705SXin Li
6332*67e74705SXin Li if (!TI.isValidGCCRegisterName(Label))
6333*67e74705SXin Li Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6334*67e74705SXin Li else if (!TI.validateGlobalRegisterVariable(Label,
6335*67e74705SXin Li Context.getTypeSize(R),
6336*67e74705SXin Li HasSizeMismatch))
6337*67e74705SXin Li Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6338*67e74705SXin Li else if (HasSizeMismatch)
6339*67e74705SXin Li Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6340*67e74705SXin Li }
6341*67e74705SXin Li
6342*67e74705SXin Li if (!R->isIntegralType(Context) && !R->isPointerType()) {
6343*67e74705SXin Li Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6344*67e74705SXin Li NewVD->setInvalidDecl(true);
6345*67e74705SXin Li }
6346*67e74705SXin Li }
6347*67e74705SXin Li
6348*67e74705SXin Li NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6349*67e74705SXin Li Context, Label, 0));
6350*67e74705SXin Li } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6351*67e74705SXin Li llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6352*67e74705SXin Li ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6353*67e74705SXin Li if (I != ExtnameUndeclaredIdentifiers.end()) {
6354*67e74705SXin Li if (isDeclExternC(NewVD)) {
6355*67e74705SXin Li NewVD->addAttr(I->second);
6356*67e74705SXin Li ExtnameUndeclaredIdentifiers.erase(I);
6357*67e74705SXin Li } else
6358*67e74705SXin Li Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6359*67e74705SXin Li << /*Variable*/1 << NewVD;
6360*67e74705SXin Li }
6361*67e74705SXin Li }
6362*67e74705SXin Li
6363*67e74705SXin Li // Diagnose shadowed variables before filtering for scope.
6364*67e74705SXin Li if (D.getCXXScopeSpec().isEmpty())
6365*67e74705SXin Li CheckShadow(S, NewVD, Previous);
6366*67e74705SXin Li
6367*67e74705SXin Li // Don't consider existing declarations that are in a different
6368*67e74705SXin Li // scope and are out-of-semantic-context declarations (if the new
6369*67e74705SXin Li // declaration has linkage).
6370*67e74705SXin Li FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6371*67e74705SXin Li D.getCXXScopeSpec().isNotEmpty() ||
6372*67e74705SXin Li IsExplicitSpecialization ||
6373*67e74705SXin Li IsVariableTemplateSpecialization);
6374*67e74705SXin Li
6375*67e74705SXin Li // Check whether the previous declaration is in the same block scope. This
6376*67e74705SXin Li // affects whether we merge types with it, per C++11 [dcl.array]p3.
6377*67e74705SXin Li if (getLangOpts().CPlusPlus &&
6378*67e74705SXin Li NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6379*67e74705SXin Li NewVD->setPreviousDeclInSameBlockScope(
6380*67e74705SXin Li Previous.isSingleResult() && !Previous.isShadowed() &&
6381*67e74705SXin Li isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6382*67e74705SXin Li
6383*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
6384*67e74705SXin Li D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6385*67e74705SXin Li } else {
6386*67e74705SXin Li // If this is an explicit specialization of a static data member, check it.
6387*67e74705SXin Li if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6388*67e74705SXin Li CheckMemberSpecialization(NewVD, Previous))
6389*67e74705SXin Li NewVD->setInvalidDecl();
6390*67e74705SXin Li
6391*67e74705SXin Li // Merge the decl with the existing one if appropriate.
6392*67e74705SXin Li if (!Previous.empty()) {
6393*67e74705SXin Li if (Previous.isSingleResult() &&
6394*67e74705SXin Li isa<FieldDecl>(Previous.getFoundDecl()) &&
6395*67e74705SXin Li D.getCXXScopeSpec().isSet()) {
6396*67e74705SXin Li // The user tried to define a non-static data member
6397*67e74705SXin Li // out-of-line (C++ [dcl.meaning]p1).
6398*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6399*67e74705SXin Li << D.getCXXScopeSpec().getRange();
6400*67e74705SXin Li Previous.clear();
6401*67e74705SXin Li NewVD->setInvalidDecl();
6402*67e74705SXin Li }
6403*67e74705SXin Li } else if (D.getCXXScopeSpec().isSet()) {
6404*67e74705SXin Li // No previous declaration in the qualifying scope.
6405*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_no_member)
6406*67e74705SXin Li << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6407*67e74705SXin Li << D.getCXXScopeSpec().getRange();
6408*67e74705SXin Li NewVD->setInvalidDecl();
6409*67e74705SXin Li }
6410*67e74705SXin Li
6411*67e74705SXin Li if (!IsVariableTemplateSpecialization)
6412*67e74705SXin Li D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6413*67e74705SXin Li
6414*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6415*67e74705SXin Li // an explicit specialization (14.8.3) or a partial specialization of a
6416*67e74705SXin Li // concept definition.
6417*67e74705SXin Li if (IsVariableTemplateSpecialization &&
6418*67e74705SXin Li !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6419*67e74705SXin Li Previous.isSingleResult()) {
6420*67e74705SXin Li NamedDecl *PreviousDecl = Previous.getFoundDecl();
6421*67e74705SXin Li if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6422*67e74705SXin Li if (VarTmpl->isConcept()) {
6423*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_concept_specialized)
6424*67e74705SXin Li << 1 /*variable*/
6425*67e74705SXin Li << (IsPartialSpecialization ? 2 /*partially specialized*/
6426*67e74705SXin Li : 1 /*explicitly specialized*/);
6427*67e74705SXin Li Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6428*67e74705SXin Li NewVD->setInvalidDecl();
6429*67e74705SXin Li }
6430*67e74705SXin Li }
6431*67e74705SXin Li }
6432*67e74705SXin Li
6433*67e74705SXin Li if (NewTemplate) {
6434*67e74705SXin Li VarTemplateDecl *PrevVarTemplate =
6435*67e74705SXin Li NewVD->getPreviousDecl()
6436*67e74705SXin Li ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6437*67e74705SXin Li : nullptr;
6438*67e74705SXin Li
6439*67e74705SXin Li // Check the template parameter list of this declaration, possibly
6440*67e74705SXin Li // merging in the template parameter list from the previous variable
6441*67e74705SXin Li // template declaration.
6442*67e74705SXin Li if (CheckTemplateParameterList(
6443*67e74705SXin Li TemplateParams,
6444*67e74705SXin Li PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6445*67e74705SXin Li : nullptr,
6446*67e74705SXin Li (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6447*67e74705SXin Li DC->isDependentContext())
6448*67e74705SXin Li ? TPC_ClassTemplateMember
6449*67e74705SXin Li : TPC_VarTemplate))
6450*67e74705SXin Li NewVD->setInvalidDecl();
6451*67e74705SXin Li
6452*67e74705SXin Li // If we are providing an explicit specialization of a static variable
6453*67e74705SXin Li // template, make a note of that.
6454*67e74705SXin Li if (PrevVarTemplate &&
6455*67e74705SXin Li PrevVarTemplate->getInstantiatedFromMemberTemplate())
6456*67e74705SXin Li PrevVarTemplate->setMemberSpecialization();
6457*67e74705SXin Li }
6458*67e74705SXin Li }
6459*67e74705SXin Li
6460*67e74705SXin Li ProcessPragmaWeak(S, NewVD);
6461*67e74705SXin Li
6462*67e74705SXin Li // If this is the first declaration of an extern C variable, update
6463*67e74705SXin Li // the map of such variables.
6464*67e74705SXin Li if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6465*67e74705SXin Li isIncompleteDeclExternC(*this, NewVD))
6466*67e74705SXin Li RegisterLocallyScopedExternCDecl(NewVD, S);
6467*67e74705SXin Li
6468*67e74705SXin Li if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6469*67e74705SXin Li Decl *ManglingContextDecl;
6470*67e74705SXin Li if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6471*67e74705SXin Li NewVD->getDeclContext(), ManglingContextDecl)) {
6472*67e74705SXin Li Context.setManglingNumber(
6473*67e74705SXin Li NewVD, MCtx->getManglingNumber(
6474*67e74705SXin Li NewVD, getMSManglingNumber(getLangOpts(), S)));
6475*67e74705SXin Li Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6476*67e74705SXin Li }
6477*67e74705SXin Li }
6478*67e74705SXin Li
6479*67e74705SXin Li // Special handling of variable named 'main'.
6480*67e74705SXin Li if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6481*67e74705SXin Li NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6482*67e74705SXin Li !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6483*67e74705SXin Li
6484*67e74705SXin Li // C++ [basic.start.main]p3
6485*67e74705SXin Li // A program that declares a variable main at global scope is ill-formed.
6486*67e74705SXin Li if (getLangOpts().CPlusPlus)
6487*67e74705SXin Li Diag(D.getLocStart(), diag::err_main_global_variable);
6488*67e74705SXin Li
6489*67e74705SXin Li // In C, and external-linkage variable named main results in undefined
6490*67e74705SXin Li // behavior.
6491*67e74705SXin Li else if (NewVD->hasExternalFormalLinkage())
6492*67e74705SXin Li Diag(D.getLocStart(), diag::warn_main_redefined);
6493*67e74705SXin Li }
6494*67e74705SXin Li
6495*67e74705SXin Li if (D.isRedeclaration() && !Previous.empty()) {
6496*67e74705SXin Li checkDLLAttributeRedeclaration(
6497*67e74705SXin Li *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6498*67e74705SXin Li IsExplicitSpecialization, D.isFunctionDefinition());
6499*67e74705SXin Li }
6500*67e74705SXin Li
6501*67e74705SXin Li if (NewTemplate) {
6502*67e74705SXin Li if (NewVD->isInvalidDecl())
6503*67e74705SXin Li NewTemplate->setInvalidDecl();
6504*67e74705SXin Li ActOnDocumentableDecl(NewTemplate);
6505*67e74705SXin Li return NewTemplate;
6506*67e74705SXin Li }
6507*67e74705SXin Li
6508*67e74705SXin Li return NewVD;
6509*67e74705SXin Li }
6510*67e74705SXin Li
6511*67e74705SXin Li /// Enum describing the %select options in diag::warn_decl_shadow.
6512*67e74705SXin Li enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6513*67e74705SXin Li
6514*67e74705SXin Li /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)6515*67e74705SXin Li static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6516*67e74705SXin Li const DeclContext *OldDC) {
6517*67e74705SXin Li if (isa<RecordDecl>(OldDC))
6518*67e74705SXin Li return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6519*67e74705SXin Li return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6520*67e74705SXin Li }
6521*67e74705SXin Li
6522*67e74705SXin Li /// \brief Diagnose variable or built-in function shadowing. Implements
6523*67e74705SXin Li /// -Wshadow.
6524*67e74705SXin Li ///
6525*67e74705SXin Li /// This method is called whenever a VarDecl is added to a "useful"
6526*67e74705SXin Li /// scope.
6527*67e74705SXin Li ///
6528*67e74705SXin Li /// \param S the scope in which the shadowing name is being declared
6529*67e74705SXin Li /// \param R the lookup of the name
6530*67e74705SXin Li ///
CheckShadow(Scope * S,VarDecl * D,const LookupResult & R)6531*67e74705SXin Li void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6532*67e74705SXin Li // Return if warning is ignored.
6533*67e74705SXin Li if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6534*67e74705SXin Li return;
6535*67e74705SXin Li
6536*67e74705SXin Li // Don't diagnose declarations at file scope.
6537*67e74705SXin Li if (D->hasGlobalStorage())
6538*67e74705SXin Li return;
6539*67e74705SXin Li
6540*67e74705SXin Li DeclContext *NewDC = D->getDeclContext();
6541*67e74705SXin Li
6542*67e74705SXin Li // Only diagnose if we're shadowing an unambiguous field or variable.
6543*67e74705SXin Li if (R.getResultKind() != LookupResult::Found)
6544*67e74705SXin Li return;
6545*67e74705SXin Li
6546*67e74705SXin Li NamedDecl* ShadowedDecl = R.getFoundDecl();
6547*67e74705SXin Li if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6548*67e74705SXin Li return;
6549*67e74705SXin Li
6550*67e74705SXin Li if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6551*67e74705SXin Li // Fields are not shadowed by variables in C++ static methods.
6552*67e74705SXin Li if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6553*67e74705SXin Li if (MD->isStatic())
6554*67e74705SXin Li return;
6555*67e74705SXin Li
6556*67e74705SXin Li // Fields shadowed by constructor parameters are a special case. Usually
6557*67e74705SXin Li // the constructor initializes the field with the parameter.
6558*67e74705SXin Li if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6559*67e74705SXin Li // Remember that this was shadowed so we can either warn about its
6560*67e74705SXin Li // modification or its existence depending on warning settings.
6561*67e74705SXin Li D = D->getCanonicalDecl();
6562*67e74705SXin Li ShadowingDecls.insert({D, FD});
6563*67e74705SXin Li return;
6564*67e74705SXin Li }
6565*67e74705SXin Li }
6566*67e74705SXin Li
6567*67e74705SXin Li if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6568*67e74705SXin Li if (shadowedVar->isExternC()) {
6569*67e74705SXin Li // For shadowing external vars, make sure that we point to the global
6570*67e74705SXin Li // declaration, not a locally scoped extern declaration.
6571*67e74705SXin Li for (auto I : shadowedVar->redecls())
6572*67e74705SXin Li if (I->isFileVarDecl()) {
6573*67e74705SXin Li ShadowedDecl = I;
6574*67e74705SXin Li break;
6575*67e74705SXin Li }
6576*67e74705SXin Li }
6577*67e74705SXin Li
6578*67e74705SXin Li DeclContext *OldDC = ShadowedDecl->getDeclContext();
6579*67e74705SXin Li
6580*67e74705SXin Li // Only warn about certain kinds of shadowing for class members.
6581*67e74705SXin Li if (NewDC && NewDC->isRecord()) {
6582*67e74705SXin Li // In particular, don't warn about shadowing non-class members.
6583*67e74705SXin Li if (!OldDC->isRecord())
6584*67e74705SXin Li return;
6585*67e74705SXin Li
6586*67e74705SXin Li // TODO: should we warn about static data members shadowing
6587*67e74705SXin Li // static data members from base classes?
6588*67e74705SXin Li
6589*67e74705SXin Li // TODO: don't diagnose for inaccessible shadowed members.
6590*67e74705SXin Li // This is hard to do perfectly because we might friend the
6591*67e74705SXin Li // shadowing context, but that's just a false negative.
6592*67e74705SXin Li }
6593*67e74705SXin Li
6594*67e74705SXin Li
6595*67e74705SXin Li DeclarationName Name = R.getLookupName();
6596*67e74705SXin Li
6597*67e74705SXin Li // Emit warning and note.
6598*67e74705SXin Li if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6599*67e74705SXin Li return;
6600*67e74705SXin Li ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6601*67e74705SXin Li Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6602*67e74705SXin Li Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6603*67e74705SXin Li }
6604*67e74705SXin Li
6605*67e74705SXin Li /// \brief Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)6606*67e74705SXin Li void Sema::CheckShadow(Scope *S, VarDecl *D) {
6607*67e74705SXin Li if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6608*67e74705SXin Li return;
6609*67e74705SXin Li
6610*67e74705SXin Li LookupResult R(*this, D->getDeclName(), D->getLocation(),
6611*67e74705SXin Li Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6612*67e74705SXin Li LookupName(R, S);
6613*67e74705SXin Li CheckShadow(S, D, R);
6614*67e74705SXin Li }
6615*67e74705SXin Li
6616*67e74705SXin Li /// Check if 'E', which is an expression that is about to be modified, refers
6617*67e74705SXin Li /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)6618*67e74705SXin Li void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6619*67e74705SXin Li // Quickly ignore expressions that can't be shadowing ctor parameters.
6620*67e74705SXin Li if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6621*67e74705SXin Li return;
6622*67e74705SXin Li E = E->IgnoreParenImpCasts();
6623*67e74705SXin Li auto *DRE = dyn_cast<DeclRefExpr>(E);
6624*67e74705SXin Li if (!DRE)
6625*67e74705SXin Li return;
6626*67e74705SXin Li const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6627*67e74705SXin Li auto I = ShadowingDecls.find(D);
6628*67e74705SXin Li if (I == ShadowingDecls.end())
6629*67e74705SXin Li return;
6630*67e74705SXin Li const NamedDecl *ShadowedDecl = I->second;
6631*67e74705SXin Li const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6632*67e74705SXin Li Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6633*67e74705SXin Li Diag(D->getLocation(), diag::note_var_declared_here) << D;
6634*67e74705SXin Li Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6635*67e74705SXin Li
6636*67e74705SXin Li // Avoid issuing multiple warnings about the same decl.
6637*67e74705SXin Li ShadowingDecls.erase(I);
6638*67e74705SXin Li }
6639*67e74705SXin Li
6640*67e74705SXin Li /// Check for conflict between this global or extern "C" declaration and
6641*67e74705SXin Li /// previous global or extern "C" declarations. This is only used in C++.
6642*67e74705SXin Li template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)6643*67e74705SXin Li static bool checkGlobalOrExternCConflict(
6644*67e74705SXin Li Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6645*67e74705SXin Li assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6646*67e74705SXin Li NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6647*67e74705SXin Li
6648*67e74705SXin Li if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6649*67e74705SXin Li // The common case: this global doesn't conflict with any extern "C"
6650*67e74705SXin Li // declaration.
6651*67e74705SXin Li return false;
6652*67e74705SXin Li }
6653*67e74705SXin Li
6654*67e74705SXin Li if (Prev) {
6655*67e74705SXin Li if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6656*67e74705SXin Li // Both the old and new declarations have C language linkage. This is a
6657*67e74705SXin Li // redeclaration.
6658*67e74705SXin Li Previous.clear();
6659*67e74705SXin Li Previous.addDecl(Prev);
6660*67e74705SXin Li return true;
6661*67e74705SXin Li }
6662*67e74705SXin Li
6663*67e74705SXin Li // This is a global, non-extern "C" declaration, and there is a previous
6664*67e74705SXin Li // non-global extern "C" declaration. Diagnose if this is a variable
6665*67e74705SXin Li // declaration.
6666*67e74705SXin Li if (!isa<VarDecl>(ND))
6667*67e74705SXin Li return false;
6668*67e74705SXin Li } else {
6669*67e74705SXin Li // The declaration is extern "C". Check for any declaration in the
6670*67e74705SXin Li // translation unit which might conflict.
6671*67e74705SXin Li if (IsGlobal) {
6672*67e74705SXin Li // We have already performed the lookup into the translation unit.
6673*67e74705SXin Li IsGlobal = false;
6674*67e74705SXin Li for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6675*67e74705SXin Li I != E; ++I) {
6676*67e74705SXin Li if (isa<VarDecl>(*I)) {
6677*67e74705SXin Li Prev = *I;
6678*67e74705SXin Li break;
6679*67e74705SXin Li }
6680*67e74705SXin Li }
6681*67e74705SXin Li } else {
6682*67e74705SXin Li DeclContext::lookup_result R =
6683*67e74705SXin Li S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6684*67e74705SXin Li for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6685*67e74705SXin Li I != E; ++I) {
6686*67e74705SXin Li if (isa<VarDecl>(*I)) {
6687*67e74705SXin Li Prev = *I;
6688*67e74705SXin Li break;
6689*67e74705SXin Li }
6690*67e74705SXin Li // FIXME: If we have any other entity with this name in global scope,
6691*67e74705SXin Li // the declaration is ill-formed, but that is a defect: it breaks the
6692*67e74705SXin Li // 'stat' hack, for instance. Only variables can have mangled name
6693*67e74705SXin Li // clashes with extern "C" declarations, so only they deserve a
6694*67e74705SXin Li // diagnostic.
6695*67e74705SXin Li }
6696*67e74705SXin Li }
6697*67e74705SXin Li
6698*67e74705SXin Li if (!Prev)
6699*67e74705SXin Li return false;
6700*67e74705SXin Li }
6701*67e74705SXin Li
6702*67e74705SXin Li // Use the first declaration's location to ensure we point at something which
6703*67e74705SXin Li // is lexically inside an extern "C" linkage-spec.
6704*67e74705SXin Li assert(Prev && "should have found a previous declaration to diagnose");
6705*67e74705SXin Li if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6706*67e74705SXin Li Prev = FD->getFirstDecl();
6707*67e74705SXin Li else
6708*67e74705SXin Li Prev = cast<VarDecl>(Prev)->getFirstDecl();
6709*67e74705SXin Li
6710*67e74705SXin Li S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6711*67e74705SXin Li << IsGlobal << ND;
6712*67e74705SXin Li S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6713*67e74705SXin Li << IsGlobal;
6714*67e74705SXin Li return false;
6715*67e74705SXin Li }
6716*67e74705SXin Li
6717*67e74705SXin Li /// Apply special rules for handling extern "C" declarations. Returns \c true
6718*67e74705SXin Li /// if we have found that this is a redeclaration of some prior entity.
6719*67e74705SXin Li ///
6720*67e74705SXin Li /// Per C++ [dcl.link]p6:
6721*67e74705SXin Li /// Two declarations [for a function or variable] with C language linkage
6722*67e74705SXin Li /// with the same name that appear in different scopes refer to the same
6723*67e74705SXin Li /// [entity]. An entity with C language linkage shall not be declared with
6724*67e74705SXin Li /// the same name as an entity in global scope.
6725*67e74705SXin Li template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)6726*67e74705SXin Li static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6727*67e74705SXin Li LookupResult &Previous) {
6728*67e74705SXin Li if (!S.getLangOpts().CPlusPlus) {
6729*67e74705SXin Li // In C, when declaring a global variable, look for a corresponding 'extern'
6730*67e74705SXin Li // variable declared in function scope. We don't need this in C++, because
6731*67e74705SXin Li // we find local extern decls in the surrounding file-scope DeclContext.
6732*67e74705SXin Li if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6733*67e74705SXin Li if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6734*67e74705SXin Li Previous.clear();
6735*67e74705SXin Li Previous.addDecl(Prev);
6736*67e74705SXin Li return true;
6737*67e74705SXin Li }
6738*67e74705SXin Li }
6739*67e74705SXin Li return false;
6740*67e74705SXin Li }
6741*67e74705SXin Li
6742*67e74705SXin Li // A declaration in the translation unit can conflict with an extern "C"
6743*67e74705SXin Li // declaration.
6744*67e74705SXin Li if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6745*67e74705SXin Li return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6746*67e74705SXin Li
6747*67e74705SXin Li // An extern "C" declaration can conflict with a declaration in the
6748*67e74705SXin Li // translation unit or can be a redeclaration of an extern "C" declaration
6749*67e74705SXin Li // in another scope.
6750*67e74705SXin Li if (isIncompleteDeclExternC(S,ND))
6751*67e74705SXin Li return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6752*67e74705SXin Li
6753*67e74705SXin Li // Neither global nor extern "C": nothing to do.
6754*67e74705SXin Li return false;
6755*67e74705SXin Li }
6756*67e74705SXin Li
CheckVariableDeclarationType(VarDecl * NewVD)6757*67e74705SXin Li void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6758*67e74705SXin Li // If the decl is already known invalid, don't check it.
6759*67e74705SXin Li if (NewVD->isInvalidDecl())
6760*67e74705SXin Li return;
6761*67e74705SXin Li
6762*67e74705SXin Li TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6763*67e74705SXin Li QualType T = TInfo->getType();
6764*67e74705SXin Li
6765*67e74705SXin Li // Defer checking an 'auto' type until its initializer is attached.
6766*67e74705SXin Li if (T->isUndeducedType())
6767*67e74705SXin Li return;
6768*67e74705SXin Li
6769*67e74705SXin Li if (NewVD->hasAttrs())
6770*67e74705SXin Li CheckAlignasUnderalignment(NewVD);
6771*67e74705SXin Li
6772*67e74705SXin Li if (T->isObjCObjectType()) {
6773*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6774*67e74705SXin Li << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6775*67e74705SXin Li T = Context.getObjCObjectPointerType(T);
6776*67e74705SXin Li NewVD->setType(T);
6777*67e74705SXin Li }
6778*67e74705SXin Li
6779*67e74705SXin Li // Emit an error if an address space was applied to decl with local storage.
6780*67e74705SXin Li // This includes arrays of objects with address space qualifiers, but not
6781*67e74705SXin Li // automatic variables that point to other address spaces.
6782*67e74705SXin Li // ISO/IEC TR 18037 S5.1.2
6783*67e74705SXin Li if (!getLangOpts().OpenCL
6784*67e74705SXin Li && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6785*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6786*67e74705SXin Li NewVD->setInvalidDecl();
6787*67e74705SXin Li return;
6788*67e74705SXin Li }
6789*67e74705SXin Li
6790*67e74705SXin Li // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6791*67e74705SXin Li // scope.
6792*67e74705SXin Li if (getLangOpts().OpenCLVersion == 120 &&
6793*67e74705SXin Li !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6794*67e74705SXin Li NewVD->isStaticLocal()) {
6795*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_static_function_scope);
6796*67e74705SXin Li NewVD->setInvalidDecl();
6797*67e74705SXin Li return;
6798*67e74705SXin Li }
6799*67e74705SXin Li
6800*67e74705SXin Li if (getLangOpts().OpenCL) {
6801*67e74705SXin Li // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6802*67e74705SXin Li if (NewVD->hasAttr<BlocksAttr>()) {
6803*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6804*67e74705SXin Li return;
6805*67e74705SXin Li }
6806*67e74705SXin Li
6807*67e74705SXin Li if (T->isBlockPointerType()) {
6808*67e74705SXin Li // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6809*67e74705SXin Li // can't use 'extern' storage class.
6810*67e74705SXin Li if (!T.isConstQualified()) {
6811*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6812*67e74705SXin Li << 0 /*const*/;
6813*67e74705SXin Li NewVD->setInvalidDecl();
6814*67e74705SXin Li return;
6815*67e74705SXin Li }
6816*67e74705SXin Li if (NewVD->hasExternalStorage()) {
6817*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6818*67e74705SXin Li NewVD->setInvalidDecl();
6819*67e74705SXin Li return;
6820*67e74705SXin Li }
6821*67e74705SXin Li // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6822*67e74705SXin Li // TODO: this check is not enough as it doesn't diagnose the typedef
6823*67e74705SXin Li const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6824*67e74705SXin Li const FunctionProtoType *FTy =
6825*67e74705SXin Li BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6826*67e74705SXin Li if (FTy && FTy->isVariadic()) {
6827*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6828*67e74705SXin Li << T << NewVD->getSourceRange();
6829*67e74705SXin Li NewVD->setInvalidDecl();
6830*67e74705SXin Li return;
6831*67e74705SXin Li }
6832*67e74705SXin Li }
6833*67e74705SXin Li // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6834*67e74705SXin Li // __constant address space.
6835*67e74705SXin Li // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6836*67e74705SXin Li // variables inside a function can also be declared in the global
6837*67e74705SXin Li // address space.
6838*67e74705SXin Li if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6839*67e74705SXin Li NewVD->hasExternalStorage()) {
6840*67e74705SXin Li if (!T->isSamplerT() &&
6841*67e74705SXin Li !(T.getAddressSpace() == LangAS::opencl_constant ||
6842*67e74705SXin Li (T.getAddressSpace() == LangAS::opencl_global &&
6843*67e74705SXin Li getLangOpts().OpenCLVersion == 200))) {
6844*67e74705SXin Li int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6845*67e74705SXin Li if (getLangOpts().OpenCLVersion == 200)
6846*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6847*67e74705SXin Li << Scope << "global or constant";
6848*67e74705SXin Li else
6849*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6850*67e74705SXin Li << Scope << "constant";
6851*67e74705SXin Li NewVD->setInvalidDecl();
6852*67e74705SXin Li return;
6853*67e74705SXin Li }
6854*67e74705SXin Li } else {
6855*67e74705SXin Li if (T.getAddressSpace() == LangAS::opencl_global) {
6856*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6857*67e74705SXin Li << 1 /*is any function*/ << "global";
6858*67e74705SXin Li NewVD->setInvalidDecl();
6859*67e74705SXin Li return;
6860*67e74705SXin Li }
6861*67e74705SXin Li // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6862*67e74705SXin Li // in functions.
6863*67e74705SXin Li if (T.getAddressSpace() == LangAS::opencl_constant ||
6864*67e74705SXin Li T.getAddressSpace() == LangAS::opencl_local) {
6865*67e74705SXin Li FunctionDecl *FD = getCurFunctionDecl();
6866*67e74705SXin Li if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6867*67e74705SXin Li if (T.getAddressSpace() == LangAS::opencl_constant)
6868*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6869*67e74705SXin Li << 0 /*non-kernel only*/ << "constant";
6870*67e74705SXin Li else
6871*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6872*67e74705SXin Li << 0 /*non-kernel only*/ << "local";
6873*67e74705SXin Li NewVD->setInvalidDecl();
6874*67e74705SXin Li return;
6875*67e74705SXin Li }
6876*67e74705SXin Li }
6877*67e74705SXin Li }
6878*67e74705SXin Li }
6879*67e74705SXin Li
6880*67e74705SXin Li if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6881*67e74705SXin Li && !NewVD->hasAttr<BlocksAttr>()) {
6882*67e74705SXin Li if (getLangOpts().getGC() != LangOptions::NonGC)
6883*67e74705SXin Li Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6884*67e74705SXin Li else {
6885*67e74705SXin Li assert(!getLangOpts().ObjCAutoRefCount);
6886*67e74705SXin Li Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6887*67e74705SXin Li }
6888*67e74705SXin Li }
6889*67e74705SXin Li
6890*67e74705SXin Li bool isVM = T->isVariablyModifiedType();
6891*67e74705SXin Li if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6892*67e74705SXin Li NewVD->hasAttr<BlocksAttr>())
6893*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
6894*67e74705SXin Li
6895*67e74705SXin Li if ((isVM && NewVD->hasLinkage()) ||
6896*67e74705SXin Li (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6897*67e74705SXin Li bool SizeIsNegative;
6898*67e74705SXin Li llvm::APSInt Oversized;
6899*67e74705SXin Li TypeSourceInfo *FixedTInfo =
6900*67e74705SXin Li TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6901*67e74705SXin Li SizeIsNegative, Oversized);
6902*67e74705SXin Li if (!FixedTInfo && T->isVariableArrayType()) {
6903*67e74705SXin Li const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6904*67e74705SXin Li // FIXME: This won't give the correct result for
6905*67e74705SXin Li // int a[10][n];
6906*67e74705SXin Li SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6907*67e74705SXin Li
6908*67e74705SXin Li if (NewVD->isFileVarDecl())
6909*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6910*67e74705SXin Li << SizeRange;
6911*67e74705SXin Li else if (NewVD->isStaticLocal())
6912*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6913*67e74705SXin Li << SizeRange;
6914*67e74705SXin Li else
6915*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6916*67e74705SXin Li << SizeRange;
6917*67e74705SXin Li NewVD->setInvalidDecl();
6918*67e74705SXin Li return;
6919*67e74705SXin Li }
6920*67e74705SXin Li
6921*67e74705SXin Li if (!FixedTInfo) {
6922*67e74705SXin Li if (NewVD->isFileVarDecl())
6923*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6924*67e74705SXin Li else
6925*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6926*67e74705SXin Li NewVD->setInvalidDecl();
6927*67e74705SXin Li return;
6928*67e74705SXin Li }
6929*67e74705SXin Li
6930*67e74705SXin Li Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6931*67e74705SXin Li NewVD->setType(FixedTInfo->getType());
6932*67e74705SXin Li NewVD->setTypeSourceInfo(FixedTInfo);
6933*67e74705SXin Li }
6934*67e74705SXin Li
6935*67e74705SXin Li if (T->isVoidType()) {
6936*67e74705SXin Li // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6937*67e74705SXin Li // of objects and functions.
6938*67e74705SXin Li if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6939*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6940*67e74705SXin Li << T;
6941*67e74705SXin Li NewVD->setInvalidDecl();
6942*67e74705SXin Li return;
6943*67e74705SXin Li }
6944*67e74705SXin Li }
6945*67e74705SXin Li
6946*67e74705SXin Li if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6947*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6948*67e74705SXin Li NewVD->setInvalidDecl();
6949*67e74705SXin Li return;
6950*67e74705SXin Li }
6951*67e74705SXin Li
6952*67e74705SXin Li if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6953*67e74705SXin Li Diag(NewVD->getLocation(), diag::err_block_on_vm);
6954*67e74705SXin Li NewVD->setInvalidDecl();
6955*67e74705SXin Li return;
6956*67e74705SXin Li }
6957*67e74705SXin Li
6958*67e74705SXin Li if (NewVD->isConstexpr() && !T->isDependentType() &&
6959*67e74705SXin Li RequireLiteralType(NewVD->getLocation(), T,
6960*67e74705SXin Li diag::err_constexpr_var_non_literal)) {
6961*67e74705SXin Li NewVD->setInvalidDecl();
6962*67e74705SXin Li return;
6963*67e74705SXin Li }
6964*67e74705SXin Li }
6965*67e74705SXin Li
6966*67e74705SXin Li /// \brief Perform semantic checking on a newly-created variable
6967*67e74705SXin Li /// declaration.
6968*67e74705SXin Li ///
6969*67e74705SXin Li /// This routine performs all of the type-checking required for a
6970*67e74705SXin Li /// variable declaration once it has been built. It is used both to
6971*67e74705SXin Li /// check variables after they have been parsed and their declarators
6972*67e74705SXin Li /// have been translated into a declaration, and to check variables
6973*67e74705SXin Li /// that have been instantiated from a template.
6974*67e74705SXin Li ///
6975*67e74705SXin Li /// Sets NewVD->isInvalidDecl() if an error was encountered.
6976*67e74705SXin Li ///
6977*67e74705SXin Li /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)6978*67e74705SXin Li bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6979*67e74705SXin Li CheckVariableDeclarationType(NewVD);
6980*67e74705SXin Li
6981*67e74705SXin Li // If the decl is already known invalid, don't check it.
6982*67e74705SXin Li if (NewVD->isInvalidDecl())
6983*67e74705SXin Li return false;
6984*67e74705SXin Li
6985*67e74705SXin Li // If we did not find anything by this name, look for a non-visible
6986*67e74705SXin Li // extern "C" declaration with the same name.
6987*67e74705SXin Li if (Previous.empty() &&
6988*67e74705SXin Li checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6989*67e74705SXin Li Previous.setShadowed();
6990*67e74705SXin Li
6991*67e74705SXin Li if (!Previous.empty()) {
6992*67e74705SXin Li MergeVarDecl(NewVD, Previous);
6993*67e74705SXin Li return true;
6994*67e74705SXin Li }
6995*67e74705SXin Li return false;
6996*67e74705SXin Li }
6997*67e74705SXin Li
6998*67e74705SXin Li namespace {
6999*67e74705SXin Li struct FindOverriddenMethod {
7000*67e74705SXin Li Sema *S;
7001*67e74705SXin Li CXXMethodDecl *Method;
7002*67e74705SXin Li
7003*67e74705SXin Li /// Member lookup function that determines whether a given C++
7004*67e74705SXin Li /// method overrides a method in a base class, to be used with
7005*67e74705SXin Li /// CXXRecordDecl::lookupInBases().
operator ()__anon7a8358650511::FindOverriddenMethod7006*67e74705SXin Li bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7007*67e74705SXin Li RecordDecl *BaseRecord =
7008*67e74705SXin Li Specifier->getType()->getAs<RecordType>()->getDecl();
7009*67e74705SXin Li
7010*67e74705SXin Li DeclarationName Name = Method->getDeclName();
7011*67e74705SXin Li
7012*67e74705SXin Li // FIXME: Do we care about other names here too?
7013*67e74705SXin Li if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7014*67e74705SXin Li // We really want to find the base class destructor here.
7015*67e74705SXin Li QualType T = S->Context.getTypeDeclType(BaseRecord);
7016*67e74705SXin Li CanQualType CT = S->Context.getCanonicalType(T);
7017*67e74705SXin Li
7018*67e74705SXin Li Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7019*67e74705SXin Li }
7020*67e74705SXin Li
7021*67e74705SXin Li for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7022*67e74705SXin Li Path.Decls = Path.Decls.slice(1)) {
7023*67e74705SXin Li NamedDecl *D = Path.Decls.front();
7024*67e74705SXin Li if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7025*67e74705SXin Li if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7026*67e74705SXin Li return true;
7027*67e74705SXin Li }
7028*67e74705SXin Li }
7029*67e74705SXin Li
7030*67e74705SXin Li return false;
7031*67e74705SXin Li }
7032*67e74705SXin Li };
7033*67e74705SXin Li
7034*67e74705SXin Li enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7035*67e74705SXin Li } // end anonymous namespace
7036*67e74705SXin Li
7037*67e74705SXin Li /// \brief Report an error regarding overriding, along with any relevant
7038*67e74705SXin Li /// overriden methods.
7039*67e74705SXin Li ///
7040*67e74705SXin Li /// \param DiagID the primary error to report.
7041*67e74705SXin Li /// \param MD the overriding method.
7042*67e74705SXin Li /// \param OEK which overrides to include as notes.
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,OverrideErrorKind OEK=OEK_All)7043*67e74705SXin Li static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7044*67e74705SXin Li OverrideErrorKind OEK = OEK_All) {
7045*67e74705SXin Li S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7046*67e74705SXin Li for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7047*67e74705SXin Li E = MD->end_overridden_methods();
7048*67e74705SXin Li I != E; ++I) {
7049*67e74705SXin Li // This check (& the OEK parameter) could be replaced by a predicate, but
7050*67e74705SXin Li // without lambdas that would be overkill. This is still nicer than writing
7051*67e74705SXin Li // out the diag loop 3 times.
7052*67e74705SXin Li if ((OEK == OEK_All) ||
7053*67e74705SXin Li (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7054*67e74705SXin Li (OEK == OEK_Deleted && (*I)->isDeleted()))
7055*67e74705SXin Li S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7056*67e74705SXin Li }
7057*67e74705SXin Li }
7058*67e74705SXin Li
7059*67e74705SXin Li /// AddOverriddenMethods - See if a method overrides any in the base classes,
7060*67e74705SXin Li /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)7061*67e74705SXin Li bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7062*67e74705SXin Li // Look for methods in base classes that this method might override.
7063*67e74705SXin Li CXXBasePaths Paths;
7064*67e74705SXin Li FindOverriddenMethod FOM;
7065*67e74705SXin Li FOM.Method = MD;
7066*67e74705SXin Li FOM.S = this;
7067*67e74705SXin Li bool hasDeletedOverridenMethods = false;
7068*67e74705SXin Li bool hasNonDeletedOverridenMethods = false;
7069*67e74705SXin Li bool AddedAny = false;
7070*67e74705SXin Li if (DC->lookupInBases(FOM, Paths)) {
7071*67e74705SXin Li for (auto *I : Paths.found_decls()) {
7072*67e74705SXin Li if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7073*67e74705SXin Li MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7074*67e74705SXin Li if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7075*67e74705SXin Li !CheckOverridingFunctionAttributes(MD, OldMD) &&
7076*67e74705SXin Li !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7077*67e74705SXin Li !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7078*67e74705SXin Li hasDeletedOverridenMethods |= OldMD->isDeleted();
7079*67e74705SXin Li hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7080*67e74705SXin Li AddedAny = true;
7081*67e74705SXin Li }
7082*67e74705SXin Li }
7083*67e74705SXin Li }
7084*67e74705SXin Li }
7085*67e74705SXin Li
7086*67e74705SXin Li if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7087*67e74705SXin Li ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7088*67e74705SXin Li }
7089*67e74705SXin Li if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7090*67e74705SXin Li ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7091*67e74705SXin Li }
7092*67e74705SXin Li
7093*67e74705SXin Li return AddedAny;
7094*67e74705SXin Li }
7095*67e74705SXin Li
7096*67e74705SXin Li namespace {
7097*67e74705SXin Li // Struct for holding all of the extra arguments needed by
7098*67e74705SXin Li // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7099*67e74705SXin Li struct ActOnFDArgs {
7100*67e74705SXin Li Scope *S;
7101*67e74705SXin Li Declarator &D;
7102*67e74705SXin Li MultiTemplateParamsArg TemplateParamLists;
7103*67e74705SXin Li bool AddToScope;
7104*67e74705SXin Li };
7105*67e74705SXin Li } // end anonymous namespace
7106*67e74705SXin Li
7107*67e74705SXin Li namespace {
7108*67e74705SXin Li
7109*67e74705SXin Li // Callback to only accept typo corrections that have a non-zero edit distance.
7110*67e74705SXin Li // Also only accept corrections that have the same parent decl.
7111*67e74705SXin Li class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7112*67e74705SXin Li public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)7113*67e74705SXin Li DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7114*67e74705SXin Li CXXRecordDecl *Parent)
7115*67e74705SXin Li : Context(Context), OriginalFD(TypoFD),
7116*67e74705SXin Li ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7117*67e74705SXin Li
ValidateCandidate(const TypoCorrection & candidate)7118*67e74705SXin Li bool ValidateCandidate(const TypoCorrection &candidate) override {
7119*67e74705SXin Li if (candidate.getEditDistance() == 0)
7120*67e74705SXin Li return false;
7121*67e74705SXin Li
7122*67e74705SXin Li SmallVector<unsigned, 1> MismatchedParams;
7123*67e74705SXin Li for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7124*67e74705SXin Li CDeclEnd = candidate.end();
7125*67e74705SXin Li CDecl != CDeclEnd; ++CDecl) {
7126*67e74705SXin Li FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7127*67e74705SXin Li
7128*67e74705SXin Li if (FD && !FD->hasBody() &&
7129*67e74705SXin Li hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7130*67e74705SXin Li if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7131*67e74705SXin Li CXXRecordDecl *Parent = MD->getParent();
7132*67e74705SXin Li if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7133*67e74705SXin Li return true;
7134*67e74705SXin Li } else if (!ExpectedParent) {
7135*67e74705SXin Li return true;
7136*67e74705SXin Li }
7137*67e74705SXin Li }
7138*67e74705SXin Li }
7139*67e74705SXin Li
7140*67e74705SXin Li return false;
7141*67e74705SXin Li }
7142*67e74705SXin Li
7143*67e74705SXin Li private:
7144*67e74705SXin Li ASTContext &Context;
7145*67e74705SXin Li FunctionDecl *OriginalFD;
7146*67e74705SXin Li CXXRecordDecl *ExpectedParent;
7147*67e74705SXin Li };
7148*67e74705SXin Li
7149*67e74705SXin Li } // end anonymous namespace
7150*67e74705SXin Li
7151*67e74705SXin Li /// \brief Generate diagnostics for an invalid function redeclaration.
7152*67e74705SXin Li ///
7153*67e74705SXin Li /// This routine handles generating the diagnostic messages for an invalid
7154*67e74705SXin Li /// function redeclaration, including finding possible similar declarations
7155*67e74705SXin Li /// or performing typo correction if there are no previous declarations with
7156*67e74705SXin Li /// the same name.
7157*67e74705SXin Li ///
7158*67e74705SXin Li /// Returns a NamedDecl iff typo correction was performed and substituting in
7159*67e74705SXin Li /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)7160*67e74705SXin Li static NamedDecl *DiagnoseInvalidRedeclaration(
7161*67e74705SXin Li Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7162*67e74705SXin Li ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7163*67e74705SXin Li DeclarationName Name = NewFD->getDeclName();
7164*67e74705SXin Li DeclContext *NewDC = NewFD->getDeclContext();
7165*67e74705SXin Li SmallVector<unsigned, 1> MismatchedParams;
7166*67e74705SXin Li SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7167*67e74705SXin Li TypoCorrection Correction;
7168*67e74705SXin Li bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7169*67e74705SXin Li unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7170*67e74705SXin Li : diag::err_member_decl_does_not_match;
7171*67e74705SXin Li LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7172*67e74705SXin Li IsLocalFriend ? Sema::LookupLocalFriendName
7173*67e74705SXin Li : Sema::LookupOrdinaryName,
7174*67e74705SXin Li Sema::ForRedeclaration);
7175*67e74705SXin Li
7176*67e74705SXin Li NewFD->setInvalidDecl();
7177*67e74705SXin Li if (IsLocalFriend)
7178*67e74705SXin Li SemaRef.LookupName(Prev, S);
7179*67e74705SXin Li else
7180*67e74705SXin Li SemaRef.LookupQualifiedName(Prev, NewDC);
7181*67e74705SXin Li assert(!Prev.isAmbiguous() &&
7182*67e74705SXin Li "Cannot have an ambiguity in previous-declaration lookup");
7183*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7184*67e74705SXin Li if (!Prev.empty()) {
7185*67e74705SXin Li for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7186*67e74705SXin Li Func != FuncEnd; ++Func) {
7187*67e74705SXin Li FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7188*67e74705SXin Li if (FD &&
7189*67e74705SXin Li hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7190*67e74705SXin Li // Add 1 to the index so that 0 can mean the mismatch didn't
7191*67e74705SXin Li // involve a parameter
7192*67e74705SXin Li unsigned ParamNum =
7193*67e74705SXin Li MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7194*67e74705SXin Li NearMatches.push_back(std::make_pair(FD, ParamNum));
7195*67e74705SXin Li }
7196*67e74705SXin Li }
7197*67e74705SXin Li // If the qualified name lookup yielded nothing, try typo correction
7198*67e74705SXin Li } else if ((Correction = SemaRef.CorrectTypo(
7199*67e74705SXin Li Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7200*67e74705SXin Li &ExtraArgs.D.getCXXScopeSpec(),
7201*67e74705SXin Li llvm::make_unique<DifferentNameValidatorCCC>(
7202*67e74705SXin Li SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7203*67e74705SXin Li Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7204*67e74705SXin Li // Set up everything for the call to ActOnFunctionDeclarator
7205*67e74705SXin Li ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7206*67e74705SXin Li ExtraArgs.D.getIdentifierLoc());
7207*67e74705SXin Li Previous.clear();
7208*67e74705SXin Li Previous.setLookupName(Correction.getCorrection());
7209*67e74705SXin Li for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7210*67e74705SXin Li CDeclEnd = Correction.end();
7211*67e74705SXin Li CDecl != CDeclEnd; ++CDecl) {
7212*67e74705SXin Li FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7213*67e74705SXin Li if (FD && !FD->hasBody() &&
7214*67e74705SXin Li hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7215*67e74705SXin Li Previous.addDecl(FD);
7216*67e74705SXin Li }
7217*67e74705SXin Li }
7218*67e74705SXin Li bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7219*67e74705SXin Li
7220*67e74705SXin Li NamedDecl *Result;
7221*67e74705SXin Li // Retry building the function declaration with the new previous
7222*67e74705SXin Li // declarations, and with errors suppressed.
7223*67e74705SXin Li {
7224*67e74705SXin Li // Trap errors.
7225*67e74705SXin Li Sema::SFINAETrap Trap(SemaRef);
7226*67e74705SXin Li
7227*67e74705SXin Li // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7228*67e74705SXin Li // pieces need to verify the typo-corrected C++ declaration and hopefully
7229*67e74705SXin Li // eliminate the need for the parameter pack ExtraArgs.
7230*67e74705SXin Li Result = SemaRef.ActOnFunctionDeclarator(
7231*67e74705SXin Li ExtraArgs.S, ExtraArgs.D,
7232*67e74705SXin Li Correction.getCorrectionDecl()->getDeclContext(),
7233*67e74705SXin Li NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7234*67e74705SXin Li ExtraArgs.AddToScope);
7235*67e74705SXin Li
7236*67e74705SXin Li if (Trap.hasErrorOccurred())
7237*67e74705SXin Li Result = nullptr;
7238*67e74705SXin Li }
7239*67e74705SXin Li
7240*67e74705SXin Li if (Result) {
7241*67e74705SXin Li // Determine which correction we picked.
7242*67e74705SXin Li Decl *Canonical = Result->getCanonicalDecl();
7243*67e74705SXin Li for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7244*67e74705SXin Li I != E; ++I)
7245*67e74705SXin Li if ((*I)->getCanonicalDecl() == Canonical)
7246*67e74705SXin Li Correction.setCorrectionDecl(*I);
7247*67e74705SXin Li
7248*67e74705SXin Li SemaRef.diagnoseTypo(
7249*67e74705SXin Li Correction,
7250*67e74705SXin Li SemaRef.PDiag(IsLocalFriend
7251*67e74705SXin Li ? diag::err_no_matching_local_friend_suggest
7252*67e74705SXin Li : diag::err_member_decl_does_not_match_suggest)
7253*67e74705SXin Li << Name << NewDC << IsDefinition);
7254*67e74705SXin Li return Result;
7255*67e74705SXin Li }
7256*67e74705SXin Li
7257*67e74705SXin Li // Pretend the typo correction never occurred
7258*67e74705SXin Li ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7259*67e74705SXin Li ExtraArgs.D.getIdentifierLoc());
7260*67e74705SXin Li ExtraArgs.D.setRedeclaration(wasRedeclaration);
7261*67e74705SXin Li Previous.clear();
7262*67e74705SXin Li Previous.setLookupName(Name);
7263*67e74705SXin Li }
7264*67e74705SXin Li
7265*67e74705SXin Li SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7266*67e74705SXin Li << Name << NewDC << IsDefinition << NewFD->getLocation();
7267*67e74705SXin Li
7268*67e74705SXin Li bool NewFDisConst = false;
7269*67e74705SXin Li if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7270*67e74705SXin Li NewFDisConst = NewMD->isConst();
7271*67e74705SXin Li
7272*67e74705SXin Li for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7273*67e74705SXin Li NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7274*67e74705SXin Li NearMatch != NearMatchEnd; ++NearMatch) {
7275*67e74705SXin Li FunctionDecl *FD = NearMatch->first;
7276*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7277*67e74705SXin Li bool FDisConst = MD && MD->isConst();
7278*67e74705SXin Li bool IsMember = MD || !IsLocalFriend;
7279*67e74705SXin Li
7280*67e74705SXin Li // FIXME: These notes are poorly worded for the local friend case.
7281*67e74705SXin Li if (unsigned Idx = NearMatch->second) {
7282*67e74705SXin Li ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7283*67e74705SXin Li SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7284*67e74705SXin Li if (Loc.isInvalid()) Loc = FD->getLocation();
7285*67e74705SXin Li SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7286*67e74705SXin Li : diag::note_local_decl_close_param_match)
7287*67e74705SXin Li << Idx << FDParam->getType()
7288*67e74705SXin Li << NewFD->getParamDecl(Idx - 1)->getType();
7289*67e74705SXin Li } else if (FDisConst != NewFDisConst) {
7290*67e74705SXin Li SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7291*67e74705SXin Li << NewFDisConst << FD->getSourceRange().getEnd();
7292*67e74705SXin Li } else
7293*67e74705SXin Li SemaRef.Diag(FD->getLocation(),
7294*67e74705SXin Li IsMember ? diag::note_member_def_close_match
7295*67e74705SXin Li : diag::note_local_decl_close_match);
7296*67e74705SXin Li }
7297*67e74705SXin Li return nullptr;
7298*67e74705SXin Li }
7299*67e74705SXin Li
getFunctionStorageClass(Sema & SemaRef,Declarator & D)7300*67e74705SXin Li static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7301*67e74705SXin Li switch (D.getDeclSpec().getStorageClassSpec()) {
7302*67e74705SXin Li default: llvm_unreachable("Unknown storage class!");
7303*67e74705SXin Li case DeclSpec::SCS_auto:
7304*67e74705SXin Li case DeclSpec::SCS_register:
7305*67e74705SXin Li case DeclSpec::SCS_mutable:
7306*67e74705SXin Li SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7307*67e74705SXin Li diag::err_typecheck_sclass_func);
7308*67e74705SXin Li D.setInvalidType();
7309*67e74705SXin Li break;
7310*67e74705SXin Li case DeclSpec::SCS_unspecified: break;
7311*67e74705SXin Li case DeclSpec::SCS_extern:
7312*67e74705SXin Li if (D.getDeclSpec().isExternInLinkageSpec())
7313*67e74705SXin Li return SC_None;
7314*67e74705SXin Li return SC_Extern;
7315*67e74705SXin Li case DeclSpec::SCS_static: {
7316*67e74705SXin Li if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7317*67e74705SXin Li // C99 6.7.1p5:
7318*67e74705SXin Li // The declaration of an identifier for a function that has
7319*67e74705SXin Li // block scope shall have no explicit storage-class specifier
7320*67e74705SXin Li // other than extern
7321*67e74705SXin Li // See also (C++ [dcl.stc]p4).
7322*67e74705SXin Li SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7323*67e74705SXin Li diag::err_static_block_func);
7324*67e74705SXin Li break;
7325*67e74705SXin Li } else
7326*67e74705SXin Li return SC_Static;
7327*67e74705SXin Li }
7328*67e74705SXin Li case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7329*67e74705SXin Li }
7330*67e74705SXin Li
7331*67e74705SXin Li // No explicit storage class has already been returned
7332*67e74705SXin Li return SC_None;
7333*67e74705SXin Li }
7334*67e74705SXin Li
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)7335*67e74705SXin Li static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7336*67e74705SXin Li DeclContext *DC, QualType &R,
7337*67e74705SXin Li TypeSourceInfo *TInfo,
7338*67e74705SXin Li StorageClass SC,
7339*67e74705SXin Li bool &IsVirtualOkay) {
7340*67e74705SXin Li DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7341*67e74705SXin Li DeclarationName Name = NameInfo.getName();
7342*67e74705SXin Li
7343*67e74705SXin Li FunctionDecl *NewFD = nullptr;
7344*67e74705SXin Li bool isInline = D.getDeclSpec().isInlineSpecified();
7345*67e74705SXin Li
7346*67e74705SXin Li if (!SemaRef.getLangOpts().CPlusPlus) {
7347*67e74705SXin Li // Determine whether the function was written with a
7348*67e74705SXin Li // prototype. This true when:
7349*67e74705SXin Li // - there is a prototype in the declarator, or
7350*67e74705SXin Li // - the type R of the function is some kind of typedef or other reference
7351*67e74705SXin Li // to a type name (which eventually refers to a function type).
7352*67e74705SXin Li bool HasPrototype =
7353*67e74705SXin Li (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7354*67e74705SXin Li (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7355*67e74705SXin Li
7356*67e74705SXin Li NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7357*67e74705SXin Li D.getLocStart(), NameInfo, R,
7358*67e74705SXin Li TInfo, SC, isInline,
7359*67e74705SXin Li HasPrototype, false);
7360*67e74705SXin Li if (D.isInvalidType())
7361*67e74705SXin Li NewFD->setInvalidDecl();
7362*67e74705SXin Li
7363*67e74705SXin Li return NewFD;
7364*67e74705SXin Li }
7365*67e74705SXin Li
7366*67e74705SXin Li bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7367*67e74705SXin Li bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7368*67e74705SXin Li
7369*67e74705SXin Li // Check that the return type is not an abstract class type.
7370*67e74705SXin Li // For record types, this is done by the AbstractClassUsageDiagnoser once
7371*67e74705SXin Li // the class has been completely parsed.
7372*67e74705SXin Li if (!DC->isRecord() &&
7373*67e74705SXin Li SemaRef.RequireNonAbstractType(
7374*67e74705SXin Li D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7375*67e74705SXin Li diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7376*67e74705SXin Li D.setInvalidType();
7377*67e74705SXin Li
7378*67e74705SXin Li if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7379*67e74705SXin Li // This is a C++ constructor declaration.
7380*67e74705SXin Li assert(DC->isRecord() &&
7381*67e74705SXin Li "Constructors can only be declared in a member context");
7382*67e74705SXin Li
7383*67e74705SXin Li R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7384*67e74705SXin Li return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7385*67e74705SXin Li D.getLocStart(), NameInfo,
7386*67e74705SXin Li R, TInfo, isExplicit, isInline,
7387*67e74705SXin Li /*isImplicitlyDeclared=*/false,
7388*67e74705SXin Li isConstexpr);
7389*67e74705SXin Li
7390*67e74705SXin Li } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7391*67e74705SXin Li // This is a C++ destructor declaration.
7392*67e74705SXin Li if (DC->isRecord()) {
7393*67e74705SXin Li R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7394*67e74705SXin Li CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7395*67e74705SXin Li CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7396*67e74705SXin Li SemaRef.Context, Record,
7397*67e74705SXin Li D.getLocStart(),
7398*67e74705SXin Li NameInfo, R, TInfo, isInline,
7399*67e74705SXin Li /*isImplicitlyDeclared=*/false);
7400*67e74705SXin Li
7401*67e74705SXin Li // If the class is complete, then we now create the implicit exception
7402*67e74705SXin Li // specification. If the class is incomplete or dependent, we can't do
7403*67e74705SXin Li // it yet.
7404*67e74705SXin Li if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7405*67e74705SXin Li Record->getDefinition() && !Record->isBeingDefined() &&
7406*67e74705SXin Li R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7407*67e74705SXin Li SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7408*67e74705SXin Li }
7409*67e74705SXin Li
7410*67e74705SXin Li IsVirtualOkay = true;
7411*67e74705SXin Li return NewDD;
7412*67e74705SXin Li
7413*67e74705SXin Li } else {
7414*67e74705SXin Li SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7415*67e74705SXin Li D.setInvalidType();
7416*67e74705SXin Li
7417*67e74705SXin Li // Create a FunctionDecl to satisfy the function definition parsing
7418*67e74705SXin Li // code path.
7419*67e74705SXin Li return FunctionDecl::Create(SemaRef.Context, DC,
7420*67e74705SXin Li D.getLocStart(),
7421*67e74705SXin Li D.getIdentifierLoc(), Name, R, TInfo,
7422*67e74705SXin Li SC, isInline,
7423*67e74705SXin Li /*hasPrototype=*/true, isConstexpr);
7424*67e74705SXin Li }
7425*67e74705SXin Li
7426*67e74705SXin Li } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7427*67e74705SXin Li if (!DC->isRecord()) {
7428*67e74705SXin Li SemaRef.Diag(D.getIdentifierLoc(),
7429*67e74705SXin Li diag::err_conv_function_not_member);
7430*67e74705SXin Li return nullptr;
7431*67e74705SXin Li }
7432*67e74705SXin Li
7433*67e74705SXin Li SemaRef.CheckConversionDeclarator(D, R, SC);
7434*67e74705SXin Li IsVirtualOkay = true;
7435*67e74705SXin Li return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7436*67e74705SXin Li D.getLocStart(), NameInfo,
7437*67e74705SXin Li R, TInfo, isInline, isExplicit,
7438*67e74705SXin Li isConstexpr, SourceLocation());
7439*67e74705SXin Li
7440*67e74705SXin Li } else if (DC->isRecord()) {
7441*67e74705SXin Li // If the name of the function is the same as the name of the record,
7442*67e74705SXin Li // then this must be an invalid constructor that has a return type.
7443*67e74705SXin Li // (The parser checks for a return type and makes the declarator a
7444*67e74705SXin Li // constructor if it has no return type).
7445*67e74705SXin Li if (Name.getAsIdentifierInfo() &&
7446*67e74705SXin Li Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7447*67e74705SXin Li SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7448*67e74705SXin Li << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7449*67e74705SXin Li << SourceRange(D.getIdentifierLoc());
7450*67e74705SXin Li return nullptr;
7451*67e74705SXin Li }
7452*67e74705SXin Li
7453*67e74705SXin Li // This is a C++ method declaration.
7454*67e74705SXin Li CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7455*67e74705SXin Li cast<CXXRecordDecl>(DC),
7456*67e74705SXin Li D.getLocStart(), NameInfo, R,
7457*67e74705SXin Li TInfo, SC, isInline,
7458*67e74705SXin Li isConstexpr, SourceLocation());
7459*67e74705SXin Li IsVirtualOkay = !Ret->isStatic();
7460*67e74705SXin Li return Ret;
7461*67e74705SXin Li } else {
7462*67e74705SXin Li bool isFriend =
7463*67e74705SXin Li SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7464*67e74705SXin Li if (!isFriend && SemaRef.CurContext->isRecord())
7465*67e74705SXin Li return nullptr;
7466*67e74705SXin Li
7467*67e74705SXin Li // Determine whether the function was written with a
7468*67e74705SXin Li // prototype. This true when:
7469*67e74705SXin Li // - we're in C++ (where every function has a prototype),
7470*67e74705SXin Li return FunctionDecl::Create(SemaRef.Context, DC,
7471*67e74705SXin Li D.getLocStart(),
7472*67e74705SXin Li NameInfo, R, TInfo, SC, isInline,
7473*67e74705SXin Li true/*HasPrototype*/, isConstexpr);
7474*67e74705SXin Li }
7475*67e74705SXin Li }
7476*67e74705SXin Li
7477*67e74705SXin Li enum OpenCLParamType {
7478*67e74705SXin Li ValidKernelParam,
7479*67e74705SXin Li PtrPtrKernelParam,
7480*67e74705SXin Li PtrKernelParam,
7481*67e74705SXin Li PrivatePtrKernelParam,
7482*67e74705SXin Li InvalidKernelParam,
7483*67e74705SXin Li RecordKernelParam
7484*67e74705SXin Li };
7485*67e74705SXin Li
getOpenCLKernelParameterType(QualType PT)7486*67e74705SXin Li static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7487*67e74705SXin Li if (PT->isPointerType()) {
7488*67e74705SXin Li QualType PointeeType = PT->getPointeeType();
7489*67e74705SXin Li if (PointeeType->isPointerType())
7490*67e74705SXin Li return PtrPtrKernelParam;
7491*67e74705SXin Li return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7492*67e74705SXin Li : PtrKernelParam;
7493*67e74705SXin Li }
7494*67e74705SXin Li
7495*67e74705SXin Li // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7496*67e74705SXin Li // be used as builtin types.
7497*67e74705SXin Li
7498*67e74705SXin Li if (PT->isImageType())
7499*67e74705SXin Li return PtrKernelParam;
7500*67e74705SXin Li
7501*67e74705SXin Li if (PT->isBooleanType())
7502*67e74705SXin Li return InvalidKernelParam;
7503*67e74705SXin Li
7504*67e74705SXin Li if (PT->isEventT())
7505*67e74705SXin Li return InvalidKernelParam;
7506*67e74705SXin Li
7507*67e74705SXin Li if (PT->isHalfType())
7508*67e74705SXin Li return InvalidKernelParam;
7509*67e74705SXin Li
7510*67e74705SXin Li if (PT->isRecordType())
7511*67e74705SXin Li return RecordKernelParam;
7512*67e74705SXin Li
7513*67e74705SXin Li return ValidKernelParam;
7514*67e74705SXin Li }
7515*67e74705SXin Li
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)7516*67e74705SXin Li static void checkIsValidOpenCLKernelParameter(
7517*67e74705SXin Li Sema &S,
7518*67e74705SXin Li Declarator &D,
7519*67e74705SXin Li ParmVarDecl *Param,
7520*67e74705SXin Li llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7521*67e74705SXin Li QualType PT = Param->getType();
7522*67e74705SXin Li
7523*67e74705SXin Li // Cache the valid types we encounter to avoid rechecking structs that are
7524*67e74705SXin Li // used again
7525*67e74705SXin Li if (ValidTypes.count(PT.getTypePtr()))
7526*67e74705SXin Li return;
7527*67e74705SXin Li
7528*67e74705SXin Li switch (getOpenCLKernelParameterType(PT)) {
7529*67e74705SXin Li case PtrPtrKernelParam:
7530*67e74705SXin Li // OpenCL v1.2 s6.9.a:
7531*67e74705SXin Li // A kernel function argument cannot be declared as a
7532*67e74705SXin Li // pointer to a pointer type.
7533*67e74705SXin Li S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7534*67e74705SXin Li D.setInvalidType();
7535*67e74705SXin Li return;
7536*67e74705SXin Li
7537*67e74705SXin Li case PrivatePtrKernelParam:
7538*67e74705SXin Li // OpenCL v1.2 s6.9.a:
7539*67e74705SXin Li // A kernel function argument cannot be declared as a
7540*67e74705SXin Li // pointer to the private address space.
7541*67e74705SXin Li S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7542*67e74705SXin Li D.setInvalidType();
7543*67e74705SXin Li return;
7544*67e74705SXin Li
7545*67e74705SXin Li // OpenCL v1.2 s6.9.k:
7546*67e74705SXin Li // Arguments to kernel functions in a program cannot be declared with the
7547*67e74705SXin Li // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7548*67e74705SXin Li // uintptr_t or a struct and/or union that contain fields declared to be
7549*67e74705SXin Li // one of these built-in scalar types.
7550*67e74705SXin Li
7551*67e74705SXin Li case InvalidKernelParam:
7552*67e74705SXin Li // OpenCL v1.2 s6.8 n:
7553*67e74705SXin Li // A kernel function argument cannot be declared
7554*67e74705SXin Li // of event_t type.
7555*67e74705SXin Li S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7556*67e74705SXin Li D.setInvalidType();
7557*67e74705SXin Li return;
7558*67e74705SXin Li
7559*67e74705SXin Li case PtrKernelParam:
7560*67e74705SXin Li case ValidKernelParam:
7561*67e74705SXin Li ValidTypes.insert(PT.getTypePtr());
7562*67e74705SXin Li return;
7563*67e74705SXin Li
7564*67e74705SXin Li case RecordKernelParam:
7565*67e74705SXin Li break;
7566*67e74705SXin Li }
7567*67e74705SXin Li
7568*67e74705SXin Li // Track nested structs we will inspect
7569*67e74705SXin Li SmallVector<const Decl *, 4> VisitStack;
7570*67e74705SXin Li
7571*67e74705SXin Li // Track where we are in the nested structs. Items will migrate from
7572*67e74705SXin Li // VisitStack to HistoryStack as we do the DFS for bad field.
7573*67e74705SXin Li SmallVector<const FieldDecl *, 4> HistoryStack;
7574*67e74705SXin Li HistoryStack.push_back(nullptr);
7575*67e74705SXin Li
7576*67e74705SXin Li const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7577*67e74705SXin Li VisitStack.push_back(PD);
7578*67e74705SXin Li
7579*67e74705SXin Li assert(VisitStack.back() && "First decl null?");
7580*67e74705SXin Li
7581*67e74705SXin Li do {
7582*67e74705SXin Li const Decl *Next = VisitStack.pop_back_val();
7583*67e74705SXin Li if (!Next) {
7584*67e74705SXin Li assert(!HistoryStack.empty());
7585*67e74705SXin Li // Found a marker, we have gone up a level
7586*67e74705SXin Li if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7587*67e74705SXin Li ValidTypes.insert(Hist->getType().getTypePtr());
7588*67e74705SXin Li
7589*67e74705SXin Li continue;
7590*67e74705SXin Li }
7591*67e74705SXin Li
7592*67e74705SXin Li // Adds everything except the original parameter declaration (which is not a
7593*67e74705SXin Li // field itself) to the history stack.
7594*67e74705SXin Li const RecordDecl *RD;
7595*67e74705SXin Li if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7596*67e74705SXin Li HistoryStack.push_back(Field);
7597*67e74705SXin Li RD = Field->getType()->castAs<RecordType>()->getDecl();
7598*67e74705SXin Li } else {
7599*67e74705SXin Li RD = cast<RecordDecl>(Next);
7600*67e74705SXin Li }
7601*67e74705SXin Li
7602*67e74705SXin Li // Add a null marker so we know when we've gone back up a level
7603*67e74705SXin Li VisitStack.push_back(nullptr);
7604*67e74705SXin Li
7605*67e74705SXin Li for (const auto *FD : RD->fields()) {
7606*67e74705SXin Li QualType QT = FD->getType();
7607*67e74705SXin Li
7608*67e74705SXin Li if (ValidTypes.count(QT.getTypePtr()))
7609*67e74705SXin Li continue;
7610*67e74705SXin Li
7611*67e74705SXin Li OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7612*67e74705SXin Li if (ParamType == ValidKernelParam)
7613*67e74705SXin Li continue;
7614*67e74705SXin Li
7615*67e74705SXin Li if (ParamType == RecordKernelParam) {
7616*67e74705SXin Li VisitStack.push_back(FD);
7617*67e74705SXin Li continue;
7618*67e74705SXin Li }
7619*67e74705SXin Li
7620*67e74705SXin Li // OpenCL v1.2 s6.9.p:
7621*67e74705SXin Li // Arguments to kernel functions that are declared to be a struct or union
7622*67e74705SXin Li // do not allow OpenCL objects to be passed as elements of the struct or
7623*67e74705SXin Li // union.
7624*67e74705SXin Li if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7625*67e74705SXin Li ParamType == PrivatePtrKernelParam) {
7626*67e74705SXin Li S.Diag(Param->getLocation(),
7627*67e74705SXin Li diag::err_record_with_pointers_kernel_param)
7628*67e74705SXin Li << PT->isUnionType()
7629*67e74705SXin Li << PT;
7630*67e74705SXin Li } else {
7631*67e74705SXin Li S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7632*67e74705SXin Li }
7633*67e74705SXin Li
7634*67e74705SXin Li S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7635*67e74705SXin Li << PD->getDeclName();
7636*67e74705SXin Li
7637*67e74705SXin Li // We have an error, now let's go back up through history and show where
7638*67e74705SXin Li // the offending field came from
7639*67e74705SXin Li for (ArrayRef<const FieldDecl *>::const_iterator
7640*67e74705SXin Li I = HistoryStack.begin() + 1,
7641*67e74705SXin Li E = HistoryStack.end();
7642*67e74705SXin Li I != E; ++I) {
7643*67e74705SXin Li const FieldDecl *OuterField = *I;
7644*67e74705SXin Li S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7645*67e74705SXin Li << OuterField->getType();
7646*67e74705SXin Li }
7647*67e74705SXin Li
7648*67e74705SXin Li S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7649*67e74705SXin Li << QT->isPointerType()
7650*67e74705SXin Li << QT;
7651*67e74705SXin Li D.setInvalidType();
7652*67e74705SXin Li return;
7653*67e74705SXin Li }
7654*67e74705SXin Li } while (!VisitStack.empty());
7655*67e74705SXin Li }
7656*67e74705SXin Li
7657*67e74705SXin Li NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope)7658*67e74705SXin Li Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7659*67e74705SXin Li TypeSourceInfo *TInfo, LookupResult &Previous,
7660*67e74705SXin Li MultiTemplateParamsArg TemplateParamLists,
7661*67e74705SXin Li bool &AddToScope) {
7662*67e74705SXin Li QualType R = TInfo->getType();
7663*67e74705SXin Li
7664*67e74705SXin Li assert(R.getTypePtr()->isFunctionType());
7665*67e74705SXin Li
7666*67e74705SXin Li // TODO: consider using NameInfo for diagnostic.
7667*67e74705SXin Li DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7668*67e74705SXin Li DeclarationName Name = NameInfo.getName();
7669*67e74705SXin Li StorageClass SC = getFunctionStorageClass(*this, D);
7670*67e74705SXin Li
7671*67e74705SXin Li if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7672*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7673*67e74705SXin Li diag::err_invalid_thread)
7674*67e74705SXin Li << DeclSpec::getSpecifierName(TSCS);
7675*67e74705SXin Li
7676*67e74705SXin Li if (D.isFirstDeclarationOfMember())
7677*67e74705SXin Li adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7678*67e74705SXin Li D.getIdentifierLoc());
7679*67e74705SXin Li
7680*67e74705SXin Li bool isFriend = false;
7681*67e74705SXin Li FunctionTemplateDecl *FunctionTemplate = nullptr;
7682*67e74705SXin Li bool isExplicitSpecialization = false;
7683*67e74705SXin Li bool isFunctionTemplateSpecialization = false;
7684*67e74705SXin Li
7685*67e74705SXin Li bool isDependentClassScopeExplicitSpecialization = false;
7686*67e74705SXin Li bool HasExplicitTemplateArgs = false;
7687*67e74705SXin Li TemplateArgumentListInfo TemplateArgs;
7688*67e74705SXin Li
7689*67e74705SXin Li bool isVirtualOkay = false;
7690*67e74705SXin Li
7691*67e74705SXin Li DeclContext *OriginalDC = DC;
7692*67e74705SXin Li bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7693*67e74705SXin Li
7694*67e74705SXin Li FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7695*67e74705SXin Li isVirtualOkay);
7696*67e74705SXin Li if (!NewFD) return nullptr;
7697*67e74705SXin Li
7698*67e74705SXin Li if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7699*67e74705SXin Li NewFD->setTopLevelDeclInObjCContainer();
7700*67e74705SXin Li
7701*67e74705SXin Li // Set the lexical context. If this is a function-scope declaration, or has a
7702*67e74705SXin Li // C++ scope specifier, or is the object of a friend declaration, the lexical
7703*67e74705SXin Li // context will be different from the semantic context.
7704*67e74705SXin Li NewFD->setLexicalDeclContext(CurContext);
7705*67e74705SXin Li
7706*67e74705SXin Li if (IsLocalExternDecl)
7707*67e74705SXin Li NewFD->setLocalExternDecl();
7708*67e74705SXin Li
7709*67e74705SXin Li if (getLangOpts().CPlusPlus) {
7710*67e74705SXin Li bool isInline = D.getDeclSpec().isInlineSpecified();
7711*67e74705SXin Li bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7712*67e74705SXin Li bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7713*67e74705SXin Li bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7714*67e74705SXin Li bool isConcept = D.getDeclSpec().isConceptSpecified();
7715*67e74705SXin Li isFriend = D.getDeclSpec().isFriendSpecified();
7716*67e74705SXin Li if (isFriend && !isInline && D.isFunctionDefinition()) {
7717*67e74705SXin Li // C++ [class.friend]p5
7718*67e74705SXin Li // A function can be defined in a friend declaration of a
7719*67e74705SXin Li // class . . . . Such a function is implicitly inline.
7720*67e74705SXin Li NewFD->setImplicitlyInline();
7721*67e74705SXin Li }
7722*67e74705SXin Li
7723*67e74705SXin Li // If this is a method defined in an __interface, and is not a constructor
7724*67e74705SXin Li // or an overloaded operator, then set the pure flag (isVirtual will already
7725*67e74705SXin Li // return true).
7726*67e74705SXin Li if (const CXXRecordDecl *Parent =
7727*67e74705SXin Li dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7728*67e74705SXin Li if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7729*67e74705SXin Li NewFD->setPure(true);
7730*67e74705SXin Li
7731*67e74705SXin Li // C++ [class.union]p2
7732*67e74705SXin Li // A union can have member functions, but not virtual functions.
7733*67e74705SXin Li if (isVirtual && Parent->isUnion())
7734*67e74705SXin Li Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7735*67e74705SXin Li }
7736*67e74705SXin Li
7737*67e74705SXin Li SetNestedNameSpecifier(NewFD, D);
7738*67e74705SXin Li isExplicitSpecialization = false;
7739*67e74705SXin Li isFunctionTemplateSpecialization = false;
7740*67e74705SXin Li if (D.isInvalidType())
7741*67e74705SXin Li NewFD->setInvalidDecl();
7742*67e74705SXin Li
7743*67e74705SXin Li // Match up the template parameter lists with the scope specifier, then
7744*67e74705SXin Li // determine whether we have a template or a template specialization.
7745*67e74705SXin Li bool Invalid = false;
7746*67e74705SXin Li if (TemplateParameterList *TemplateParams =
7747*67e74705SXin Li MatchTemplateParametersToScopeSpecifier(
7748*67e74705SXin Li D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7749*67e74705SXin Li D.getCXXScopeSpec(),
7750*67e74705SXin Li D.getName().getKind() == UnqualifiedId::IK_TemplateId
7751*67e74705SXin Li ? D.getName().TemplateId
7752*67e74705SXin Li : nullptr,
7753*67e74705SXin Li TemplateParamLists, isFriend, isExplicitSpecialization,
7754*67e74705SXin Li Invalid)) {
7755*67e74705SXin Li if (TemplateParams->size() > 0) {
7756*67e74705SXin Li // This is a function template
7757*67e74705SXin Li
7758*67e74705SXin Li // Check that we can declare a template here.
7759*67e74705SXin Li if (CheckTemplateDeclScope(S, TemplateParams))
7760*67e74705SXin Li NewFD->setInvalidDecl();
7761*67e74705SXin Li
7762*67e74705SXin Li // A destructor cannot be a template.
7763*67e74705SXin Li if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7764*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_destructor_template);
7765*67e74705SXin Li NewFD->setInvalidDecl();
7766*67e74705SXin Li }
7767*67e74705SXin Li
7768*67e74705SXin Li // If we're adding a template to a dependent context, we may need to
7769*67e74705SXin Li // rebuilding some of the types used within the template parameter list,
7770*67e74705SXin Li // now that we know what the current instantiation is.
7771*67e74705SXin Li if (DC->isDependentContext()) {
7772*67e74705SXin Li ContextRAII SavedContext(*this, DC);
7773*67e74705SXin Li if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7774*67e74705SXin Li Invalid = true;
7775*67e74705SXin Li }
7776*67e74705SXin Li
7777*67e74705SXin Li FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7778*67e74705SXin Li NewFD->getLocation(),
7779*67e74705SXin Li Name, TemplateParams,
7780*67e74705SXin Li NewFD);
7781*67e74705SXin Li FunctionTemplate->setLexicalDeclContext(CurContext);
7782*67e74705SXin Li NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7783*67e74705SXin Li
7784*67e74705SXin Li // For source fidelity, store the other template param lists.
7785*67e74705SXin Li if (TemplateParamLists.size() > 1) {
7786*67e74705SXin Li NewFD->setTemplateParameterListsInfo(Context,
7787*67e74705SXin Li TemplateParamLists.drop_back(1));
7788*67e74705SXin Li }
7789*67e74705SXin Li } else {
7790*67e74705SXin Li // This is a function template specialization.
7791*67e74705SXin Li isFunctionTemplateSpecialization = true;
7792*67e74705SXin Li // For source fidelity, store all the template param lists.
7793*67e74705SXin Li if (TemplateParamLists.size() > 0)
7794*67e74705SXin Li NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7795*67e74705SXin Li
7796*67e74705SXin Li // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7797*67e74705SXin Li if (isFriend) {
7798*67e74705SXin Li // We want to remove the "template<>", found here.
7799*67e74705SXin Li SourceRange RemoveRange = TemplateParams->getSourceRange();
7800*67e74705SXin Li
7801*67e74705SXin Li // If we remove the template<> and the name is not a
7802*67e74705SXin Li // template-id, we're actually silently creating a problem:
7803*67e74705SXin Li // the friend declaration will refer to an untemplated decl,
7804*67e74705SXin Li // and clearly the user wants a template specialization. So
7805*67e74705SXin Li // we need to insert '<>' after the name.
7806*67e74705SXin Li SourceLocation InsertLoc;
7807*67e74705SXin Li if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7808*67e74705SXin Li InsertLoc = D.getName().getSourceRange().getEnd();
7809*67e74705SXin Li InsertLoc = getLocForEndOfToken(InsertLoc);
7810*67e74705SXin Li }
7811*67e74705SXin Li
7812*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7813*67e74705SXin Li << Name << RemoveRange
7814*67e74705SXin Li << FixItHint::CreateRemoval(RemoveRange)
7815*67e74705SXin Li << FixItHint::CreateInsertion(InsertLoc, "<>");
7816*67e74705SXin Li }
7817*67e74705SXin Li }
7818*67e74705SXin Li }
7819*67e74705SXin Li else {
7820*67e74705SXin Li // All template param lists were matched against the scope specifier:
7821*67e74705SXin Li // this is NOT (an explicit specialization of) a template.
7822*67e74705SXin Li if (TemplateParamLists.size() > 0)
7823*67e74705SXin Li // For source fidelity, store all the template param lists.
7824*67e74705SXin Li NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7825*67e74705SXin Li }
7826*67e74705SXin Li
7827*67e74705SXin Li if (Invalid) {
7828*67e74705SXin Li NewFD->setInvalidDecl();
7829*67e74705SXin Li if (FunctionTemplate)
7830*67e74705SXin Li FunctionTemplate->setInvalidDecl();
7831*67e74705SXin Li }
7832*67e74705SXin Li
7833*67e74705SXin Li // C++ [dcl.fct.spec]p5:
7834*67e74705SXin Li // The virtual specifier shall only be used in declarations of
7835*67e74705SXin Li // nonstatic class member functions that appear within a
7836*67e74705SXin Li // member-specification of a class declaration; see 10.3.
7837*67e74705SXin Li //
7838*67e74705SXin Li if (isVirtual && !NewFD->isInvalidDecl()) {
7839*67e74705SXin Li if (!isVirtualOkay) {
7840*67e74705SXin Li Diag(D.getDeclSpec().getVirtualSpecLoc(),
7841*67e74705SXin Li diag::err_virtual_non_function);
7842*67e74705SXin Li } else if (!CurContext->isRecord()) {
7843*67e74705SXin Li // 'virtual' was specified outside of the class.
7844*67e74705SXin Li Diag(D.getDeclSpec().getVirtualSpecLoc(),
7845*67e74705SXin Li diag::err_virtual_out_of_class)
7846*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7847*67e74705SXin Li } else if (NewFD->getDescribedFunctionTemplate()) {
7848*67e74705SXin Li // C++ [temp.mem]p3:
7849*67e74705SXin Li // A member function template shall not be virtual.
7850*67e74705SXin Li Diag(D.getDeclSpec().getVirtualSpecLoc(),
7851*67e74705SXin Li diag::err_virtual_member_function_template)
7852*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7853*67e74705SXin Li } else {
7854*67e74705SXin Li // Okay: Add virtual to the method.
7855*67e74705SXin Li NewFD->setVirtualAsWritten(true);
7856*67e74705SXin Li }
7857*67e74705SXin Li
7858*67e74705SXin Li if (getLangOpts().CPlusPlus14 &&
7859*67e74705SXin Li NewFD->getReturnType()->isUndeducedType())
7860*67e74705SXin Li Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7861*67e74705SXin Li }
7862*67e74705SXin Li
7863*67e74705SXin Li if (getLangOpts().CPlusPlus14 &&
7864*67e74705SXin Li (NewFD->isDependentContext() ||
7865*67e74705SXin Li (isFriend && CurContext->isDependentContext())) &&
7866*67e74705SXin Li NewFD->getReturnType()->isUndeducedType()) {
7867*67e74705SXin Li // If the function template is referenced directly (for instance, as a
7868*67e74705SXin Li // member of the current instantiation), pretend it has a dependent type.
7869*67e74705SXin Li // This is not really justified by the standard, but is the only sane
7870*67e74705SXin Li // thing to do.
7871*67e74705SXin Li // FIXME: For a friend function, we have not marked the function as being
7872*67e74705SXin Li // a friend yet, so 'isDependentContext' on the FD doesn't work.
7873*67e74705SXin Li const FunctionProtoType *FPT =
7874*67e74705SXin Li NewFD->getType()->castAs<FunctionProtoType>();
7875*67e74705SXin Li QualType Result =
7876*67e74705SXin Li SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7877*67e74705SXin Li NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7878*67e74705SXin Li FPT->getExtProtoInfo()));
7879*67e74705SXin Li }
7880*67e74705SXin Li
7881*67e74705SXin Li // C++ [dcl.fct.spec]p3:
7882*67e74705SXin Li // The inline specifier shall not appear on a block scope function
7883*67e74705SXin Li // declaration.
7884*67e74705SXin Li if (isInline && !NewFD->isInvalidDecl()) {
7885*67e74705SXin Li if (CurContext->isFunctionOrMethod()) {
7886*67e74705SXin Li // 'inline' is not allowed on block scope function declaration.
7887*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(),
7888*67e74705SXin Li diag::err_inline_declaration_block_scope) << Name
7889*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7890*67e74705SXin Li }
7891*67e74705SXin Li }
7892*67e74705SXin Li
7893*67e74705SXin Li // C++ [dcl.fct.spec]p6:
7894*67e74705SXin Li // The explicit specifier shall be used only in the declaration of a
7895*67e74705SXin Li // constructor or conversion function within its class definition;
7896*67e74705SXin Li // see 12.3.1 and 12.3.2.
7897*67e74705SXin Li if (isExplicit && !NewFD->isInvalidDecl()) {
7898*67e74705SXin Li if (!CurContext->isRecord()) {
7899*67e74705SXin Li // 'explicit' was specified outside of the class.
7900*67e74705SXin Li Diag(D.getDeclSpec().getExplicitSpecLoc(),
7901*67e74705SXin Li diag::err_explicit_out_of_class)
7902*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7903*67e74705SXin Li } else if (!isa<CXXConstructorDecl>(NewFD) &&
7904*67e74705SXin Li !isa<CXXConversionDecl>(NewFD)) {
7905*67e74705SXin Li // 'explicit' was specified on a function that wasn't a constructor
7906*67e74705SXin Li // or conversion function.
7907*67e74705SXin Li Diag(D.getDeclSpec().getExplicitSpecLoc(),
7908*67e74705SXin Li diag::err_explicit_non_ctor_or_conv_function)
7909*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7910*67e74705SXin Li }
7911*67e74705SXin Li }
7912*67e74705SXin Li
7913*67e74705SXin Li if (isConstexpr) {
7914*67e74705SXin Li // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7915*67e74705SXin Li // are implicitly inline.
7916*67e74705SXin Li NewFD->setImplicitlyInline();
7917*67e74705SXin Li
7918*67e74705SXin Li // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7919*67e74705SXin Li // be either constructors or to return a literal type. Therefore,
7920*67e74705SXin Li // destructors cannot be declared constexpr.
7921*67e74705SXin Li if (isa<CXXDestructorDecl>(NewFD))
7922*67e74705SXin Li Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7923*67e74705SXin Li }
7924*67e74705SXin Li
7925*67e74705SXin Li if (isConcept) {
7926*67e74705SXin Li // This is a function concept.
7927*67e74705SXin Li if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7928*67e74705SXin Li FTD->setConcept();
7929*67e74705SXin Li
7930*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7931*67e74705SXin Li // applied only to the definition of a function template [...]
7932*67e74705SXin Li if (!D.isFunctionDefinition()) {
7933*67e74705SXin Li Diag(D.getDeclSpec().getConceptSpecLoc(),
7934*67e74705SXin Li diag::err_function_concept_not_defined);
7935*67e74705SXin Li NewFD->setInvalidDecl();
7936*67e74705SXin Li }
7937*67e74705SXin Li
7938*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7939*67e74705SXin Li // have no exception-specification and is treated as if it were specified
7940*67e74705SXin Li // with noexcept(true) (15.4). [...]
7941*67e74705SXin Li if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7942*67e74705SXin Li if (FPT->hasExceptionSpec()) {
7943*67e74705SXin Li SourceRange Range;
7944*67e74705SXin Li if (D.isFunctionDeclarator())
7945*67e74705SXin Li Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7946*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7947*67e74705SXin Li << FixItHint::CreateRemoval(Range);
7948*67e74705SXin Li NewFD->setInvalidDecl();
7949*67e74705SXin Li } else {
7950*67e74705SXin Li Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7951*67e74705SXin Li }
7952*67e74705SXin Li
7953*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7954*67e74705SXin Li // following restrictions:
7955*67e74705SXin Li // - The declared return type shall have the type bool.
7956*67e74705SXin Li if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7957*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7958*67e74705SXin Li NewFD->setInvalidDecl();
7959*67e74705SXin Li }
7960*67e74705SXin Li
7961*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7962*67e74705SXin Li // following restrictions:
7963*67e74705SXin Li // - The declaration's parameter list shall be equivalent to an empty
7964*67e74705SXin Li // parameter list.
7965*67e74705SXin Li if (FPT->getNumParams() > 0 || FPT->isVariadic())
7966*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7967*67e74705SXin Li }
7968*67e74705SXin Li
7969*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7970*67e74705SXin Li // implicity defined to be a constexpr declaration (implicitly inline)
7971*67e74705SXin Li NewFD->setImplicitlyInline();
7972*67e74705SXin Li
7973*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7974*67e74705SXin Li // be declared with the thread_local, inline, friend, or constexpr
7975*67e74705SXin Li // specifiers, [...]
7976*67e74705SXin Li if (isInline) {
7977*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(),
7978*67e74705SXin Li diag::err_concept_decl_invalid_specifiers)
7979*67e74705SXin Li << 1 << 1;
7980*67e74705SXin Li NewFD->setInvalidDecl(true);
7981*67e74705SXin Li }
7982*67e74705SXin Li
7983*67e74705SXin Li if (isFriend) {
7984*67e74705SXin Li Diag(D.getDeclSpec().getFriendSpecLoc(),
7985*67e74705SXin Li diag::err_concept_decl_invalid_specifiers)
7986*67e74705SXin Li << 1 << 2;
7987*67e74705SXin Li NewFD->setInvalidDecl(true);
7988*67e74705SXin Li }
7989*67e74705SXin Li
7990*67e74705SXin Li if (isConstexpr) {
7991*67e74705SXin Li Diag(D.getDeclSpec().getConstexprSpecLoc(),
7992*67e74705SXin Li diag::err_concept_decl_invalid_specifiers)
7993*67e74705SXin Li << 1 << 3;
7994*67e74705SXin Li NewFD->setInvalidDecl(true);
7995*67e74705SXin Li }
7996*67e74705SXin Li
7997*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7998*67e74705SXin Li // applied only to the definition of a function template or variable
7999*67e74705SXin Li // template, declared in namespace scope.
8000*67e74705SXin Li if (isFunctionTemplateSpecialization) {
8001*67e74705SXin Li Diag(D.getDeclSpec().getConceptSpecLoc(),
8002*67e74705SXin Li diag::err_concept_specified_specialization) << 1;
8003*67e74705SXin Li NewFD->setInvalidDecl(true);
8004*67e74705SXin Li return NewFD;
8005*67e74705SXin Li }
8006*67e74705SXin Li }
8007*67e74705SXin Li
8008*67e74705SXin Li // If __module_private__ was specified, mark the function accordingly.
8009*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified()) {
8010*67e74705SXin Li if (isFunctionTemplateSpecialization) {
8011*67e74705SXin Li SourceLocation ModulePrivateLoc
8012*67e74705SXin Li = D.getDeclSpec().getModulePrivateSpecLoc();
8013*67e74705SXin Li Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8014*67e74705SXin Li << 0
8015*67e74705SXin Li << FixItHint::CreateRemoval(ModulePrivateLoc);
8016*67e74705SXin Li } else {
8017*67e74705SXin Li NewFD->setModulePrivate();
8018*67e74705SXin Li if (FunctionTemplate)
8019*67e74705SXin Li FunctionTemplate->setModulePrivate();
8020*67e74705SXin Li }
8021*67e74705SXin Li }
8022*67e74705SXin Li
8023*67e74705SXin Li if (isFriend) {
8024*67e74705SXin Li if (FunctionTemplate) {
8025*67e74705SXin Li FunctionTemplate->setObjectOfFriendDecl();
8026*67e74705SXin Li FunctionTemplate->setAccess(AS_public);
8027*67e74705SXin Li }
8028*67e74705SXin Li NewFD->setObjectOfFriendDecl();
8029*67e74705SXin Li NewFD->setAccess(AS_public);
8030*67e74705SXin Li }
8031*67e74705SXin Li
8032*67e74705SXin Li // If a function is defined as defaulted or deleted, mark it as such now.
8033*67e74705SXin Li // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8034*67e74705SXin Li // definition kind to FDK_Definition.
8035*67e74705SXin Li switch (D.getFunctionDefinitionKind()) {
8036*67e74705SXin Li case FDK_Declaration:
8037*67e74705SXin Li case FDK_Definition:
8038*67e74705SXin Li break;
8039*67e74705SXin Li
8040*67e74705SXin Li case FDK_Defaulted:
8041*67e74705SXin Li NewFD->setDefaulted();
8042*67e74705SXin Li break;
8043*67e74705SXin Li
8044*67e74705SXin Li case FDK_Deleted:
8045*67e74705SXin Li NewFD->setDeletedAsWritten();
8046*67e74705SXin Li break;
8047*67e74705SXin Li }
8048*67e74705SXin Li
8049*67e74705SXin Li if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8050*67e74705SXin Li D.isFunctionDefinition()) {
8051*67e74705SXin Li // C++ [class.mfct]p2:
8052*67e74705SXin Li // A member function may be defined (8.4) in its class definition, in
8053*67e74705SXin Li // which case it is an inline member function (7.1.2)
8054*67e74705SXin Li NewFD->setImplicitlyInline();
8055*67e74705SXin Li }
8056*67e74705SXin Li
8057*67e74705SXin Li if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8058*67e74705SXin Li !CurContext->isRecord()) {
8059*67e74705SXin Li // C++ [class.static]p1:
8060*67e74705SXin Li // A data or function member of a class may be declared static
8061*67e74705SXin Li // in a class definition, in which case it is a static member of
8062*67e74705SXin Li // the class.
8063*67e74705SXin Li
8064*67e74705SXin Li // Complain about the 'static' specifier if it's on an out-of-line
8065*67e74705SXin Li // member function definition.
8066*67e74705SXin Li Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8067*67e74705SXin Li diag::err_static_out_of_line)
8068*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8069*67e74705SXin Li }
8070*67e74705SXin Li
8071*67e74705SXin Li // C++11 [except.spec]p15:
8072*67e74705SXin Li // A deallocation function with no exception-specification is treated
8073*67e74705SXin Li // as if it were specified with noexcept(true).
8074*67e74705SXin Li const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8075*67e74705SXin Li if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8076*67e74705SXin Li Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8077*67e74705SXin Li getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8078*67e74705SXin Li NewFD->setType(Context.getFunctionType(
8079*67e74705SXin Li FPT->getReturnType(), FPT->getParamTypes(),
8080*67e74705SXin Li FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8081*67e74705SXin Li }
8082*67e74705SXin Li
8083*67e74705SXin Li // Filter out previous declarations that don't match the scope.
8084*67e74705SXin Li FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8085*67e74705SXin Li D.getCXXScopeSpec().isNotEmpty() ||
8086*67e74705SXin Li isExplicitSpecialization ||
8087*67e74705SXin Li isFunctionTemplateSpecialization);
8088*67e74705SXin Li
8089*67e74705SXin Li // Handle GNU asm-label extension (encoded as an attribute).
8090*67e74705SXin Li if (Expr *E = (Expr*) D.getAsmLabel()) {
8091*67e74705SXin Li // The parser guarantees this is a string.
8092*67e74705SXin Li StringLiteral *SE = cast<StringLiteral>(E);
8093*67e74705SXin Li NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8094*67e74705SXin Li SE->getString(), 0));
8095*67e74705SXin Li } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8096*67e74705SXin Li llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8097*67e74705SXin Li ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8098*67e74705SXin Li if (I != ExtnameUndeclaredIdentifiers.end()) {
8099*67e74705SXin Li if (isDeclExternC(NewFD)) {
8100*67e74705SXin Li NewFD->addAttr(I->second);
8101*67e74705SXin Li ExtnameUndeclaredIdentifiers.erase(I);
8102*67e74705SXin Li } else
8103*67e74705SXin Li Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8104*67e74705SXin Li << /*Variable*/0 << NewFD;
8105*67e74705SXin Li }
8106*67e74705SXin Li }
8107*67e74705SXin Li
8108*67e74705SXin Li // Copy the parameter declarations from the declarator D to the function
8109*67e74705SXin Li // declaration NewFD, if they are available. First scavenge them into Params.
8110*67e74705SXin Li SmallVector<ParmVarDecl*, 16> Params;
8111*67e74705SXin Li if (D.isFunctionDeclarator()) {
8112*67e74705SXin Li DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8113*67e74705SXin Li
8114*67e74705SXin Li // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8115*67e74705SXin Li // function that takes no arguments, not a function that takes a
8116*67e74705SXin Li // single void argument.
8117*67e74705SXin Li // We let through "const void" here because Sema::GetTypeForDeclarator
8118*67e74705SXin Li // already checks for that case.
8119*67e74705SXin Li if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8120*67e74705SXin Li for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8121*67e74705SXin Li ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8122*67e74705SXin Li assert(Param->getDeclContext() != NewFD && "Was set before ?");
8123*67e74705SXin Li Param->setDeclContext(NewFD);
8124*67e74705SXin Li Params.push_back(Param);
8125*67e74705SXin Li
8126*67e74705SXin Li if (Param->isInvalidDecl())
8127*67e74705SXin Li NewFD->setInvalidDecl();
8128*67e74705SXin Li }
8129*67e74705SXin Li }
8130*67e74705SXin Li } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8131*67e74705SXin Li // When we're declaring a function with a typedef, typeof, etc as in the
8132*67e74705SXin Li // following example, we'll need to synthesize (unnamed)
8133*67e74705SXin Li // parameters for use in the declaration.
8134*67e74705SXin Li //
8135*67e74705SXin Li // @code
8136*67e74705SXin Li // typedef void fn(int);
8137*67e74705SXin Li // fn f;
8138*67e74705SXin Li // @endcode
8139*67e74705SXin Li
8140*67e74705SXin Li // Synthesize a parameter for each argument type.
8141*67e74705SXin Li for (const auto &AI : FT->param_types()) {
8142*67e74705SXin Li ParmVarDecl *Param =
8143*67e74705SXin Li BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8144*67e74705SXin Li Param->setScopeInfo(0, Params.size());
8145*67e74705SXin Li Params.push_back(Param);
8146*67e74705SXin Li }
8147*67e74705SXin Li } else {
8148*67e74705SXin Li assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8149*67e74705SXin Li "Should not need args for typedef of non-prototype fn");
8150*67e74705SXin Li }
8151*67e74705SXin Li
8152*67e74705SXin Li // Finally, we know we have the right number of parameters, install them.
8153*67e74705SXin Li NewFD->setParams(Params);
8154*67e74705SXin Li
8155*67e74705SXin Li // Find all anonymous symbols defined during the declaration of this function
8156*67e74705SXin Li // and add to NewFD. This lets us track decls such 'enum Y' in:
8157*67e74705SXin Li //
8158*67e74705SXin Li // void f(enum Y {AA} x) {}
8159*67e74705SXin Li //
8160*67e74705SXin Li // which would otherwise incorrectly end up in the translation unit scope.
8161*67e74705SXin Li NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8162*67e74705SXin Li DeclsInPrototypeScope.clear();
8163*67e74705SXin Li
8164*67e74705SXin Li if (D.getDeclSpec().isNoreturnSpecified())
8165*67e74705SXin Li NewFD->addAttr(
8166*67e74705SXin Li ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8167*67e74705SXin Li Context, 0));
8168*67e74705SXin Li
8169*67e74705SXin Li // Functions returning a variably modified type violate C99 6.7.5.2p2
8170*67e74705SXin Li // because all functions have linkage.
8171*67e74705SXin Li if (!NewFD->isInvalidDecl() &&
8172*67e74705SXin Li NewFD->getReturnType()->isVariablyModifiedType()) {
8173*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8174*67e74705SXin Li NewFD->setInvalidDecl();
8175*67e74705SXin Li }
8176*67e74705SXin Li
8177*67e74705SXin Li // Apply an implicit SectionAttr if #pragma code_seg is active.
8178*67e74705SXin Li if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8179*67e74705SXin Li !NewFD->hasAttr<SectionAttr>()) {
8180*67e74705SXin Li NewFD->addAttr(
8181*67e74705SXin Li SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8182*67e74705SXin Li CodeSegStack.CurrentValue->getString(),
8183*67e74705SXin Li CodeSegStack.CurrentPragmaLocation));
8184*67e74705SXin Li if (UnifySection(CodeSegStack.CurrentValue->getString(),
8185*67e74705SXin Li ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8186*67e74705SXin Li ASTContext::PSF_Read,
8187*67e74705SXin Li NewFD))
8188*67e74705SXin Li NewFD->dropAttr<SectionAttr>();
8189*67e74705SXin Li }
8190*67e74705SXin Li
8191*67e74705SXin Li // Handle attributes.
8192*67e74705SXin Li ProcessDeclAttributes(S, NewFD, D);
8193*67e74705SXin Li
8194*67e74705SXin Li if (getLangOpts().CUDA)
8195*67e74705SXin Li maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8196*67e74705SXin Li
8197*67e74705SXin Li if (getLangOpts().OpenCL) {
8198*67e74705SXin Li // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8199*67e74705SXin Li // type declaration will generate a compilation error.
8200*67e74705SXin Li unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8201*67e74705SXin Li if (AddressSpace == LangAS::opencl_local ||
8202*67e74705SXin Li AddressSpace == LangAS::opencl_global ||
8203*67e74705SXin Li AddressSpace == LangAS::opencl_constant) {
8204*67e74705SXin Li Diag(NewFD->getLocation(),
8205*67e74705SXin Li diag::err_opencl_return_value_with_address_space);
8206*67e74705SXin Li NewFD->setInvalidDecl();
8207*67e74705SXin Li }
8208*67e74705SXin Li }
8209*67e74705SXin Li
8210*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
8211*67e74705SXin Li // Perform semantic checking on the function declaration.
8212*67e74705SXin Li bool isExplicitSpecialization=false;
8213*67e74705SXin Li if (!NewFD->isInvalidDecl() && NewFD->isMain())
8214*67e74705SXin Li CheckMain(NewFD, D.getDeclSpec());
8215*67e74705SXin Li
8216*67e74705SXin Li if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8217*67e74705SXin Li CheckMSVCRTEntryPoint(NewFD);
8218*67e74705SXin Li
8219*67e74705SXin Li if (!NewFD->isInvalidDecl())
8220*67e74705SXin Li D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8221*67e74705SXin Li isExplicitSpecialization));
8222*67e74705SXin Li else if (!Previous.empty())
8223*67e74705SXin Li // Recover gracefully from an invalid redeclaration.
8224*67e74705SXin Li D.setRedeclaration(true);
8225*67e74705SXin Li assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8226*67e74705SXin Li Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8227*67e74705SXin Li "previous declaration set still overloaded");
8228*67e74705SXin Li
8229*67e74705SXin Li // Diagnose no-prototype function declarations with calling conventions that
8230*67e74705SXin Li // don't support variadic calls. Only do this in C and do it after merging
8231*67e74705SXin Li // possibly prototyped redeclarations.
8232*67e74705SXin Li const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8233*67e74705SXin Li if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8234*67e74705SXin Li CallingConv CC = FT->getExtInfo().getCC();
8235*67e74705SXin Li if (!supportsVariadicCall(CC)) {
8236*67e74705SXin Li // Windows system headers sometimes accidentally use stdcall without
8237*67e74705SXin Li // (void) parameters, so we relax this to a warning.
8238*67e74705SXin Li int DiagID =
8239*67e74705SXin Li CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8240*67e74705SXin Li Diag(NewFD->getLocation(), DiagID)
8241*67e74705SXin Li << FunctionType::getNameForCallConv(CC);
8242*67e74705SXin Li }
8243*67e74705SXin Li }
8244*67e74705SXin Li } else {
8245*67e74705SXin Li // C++11 [replacement.functions]p3:
8246*67e74705SXin Li // The program's definitions shall not be specified as inline.
8247*67e74705SXin Li //
8248*67e74705SXin Li // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8249*67e74705SXin Li //
8250*67e74705SXin Li // Suppress the diagnostic if the function is __attribute__((used)), since
8251*67e74705SXin Li // that forces an external definition to be emitted.
8252*67e74705SXin Li if (D.getDeclSpec().isInlineSpecified() &&
8253*67e74705SXin Li NewFD->isReplaceableGlobalAllocationFunction() &&
8254*67e74705SXin Li !NewFD->hasAttr<UsedAttr>())
8255*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(),
8256*67e74705SXin Li diag::ext_operator_new_delete_declared_inline)
8257*67e74705SXin Li << NewFD->getDeclName();
8258*67e74705SXin Li
8259*67e74705SXin Li // If the declarator is a template-id, translate the parser's template
8260*67e74705SXin Li // argument list into our AST format.
8261*67e74705SXin Li if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8262*67e74705SXin Li TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8263*67e74705SXin Li TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8264*67e74705SXin Li TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8265*67e74705SXin Li ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8266*67e74705SXin Li TemplateId->NumArgs);
8267*67e74705SXin Li translateTemplateArguments(TemplateArgsPtr,
8268*67e74705SXin Li TemplateArgs);
8269*67e74705SXin Li
8270*67e74705SXin Li HasExplicitTemplateArgs = true;
8271*67e74705SXin Li
8272*67e74705SXin Li if (NewFD->isInvalidDecl()) {
8273*67e74705SXin Li HasExplicitTemplateArgs = false;
8274*67e74705SXin Li } else if (FunctionTemplate) {
8275*67e74705SXin Li // Function template with explicit template arguments.
8276*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8277*67e74705SXin Li << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8278*67e74705SXin Li
8279*67e74705SXin Li HasExplicitTemplateArgs = false;
8280*67e74705SXin Li } else {
8281*67e74705SXin Li assert((isFunctionTemplateSpecialization ||
8282*67e74705SXin Li D.getDeclSpec().isFriendSpecified()) &&
8283*67e74705SXin Li "should have a 'template<>' for this decl");
8284*67e74705SXin Li // "friend void foo<>(int);" is an implicit specialization decl.
8285*67e74705SXin Li isFunctionTemplateSpecialization = true;
8286*67e74705SXin Li }
8287*67e74705SXin Li } else if (isFriend && isFunctionTemplateSpecialization) {
8288*67e74705SXin Li // This combination is only possible in a recovery case; the user
8289*67e74705SXin Li // wrote something like:
8290*67e74705SXin Li // template <> friend void foo(int);
8291*67e74705SXin Li // which we're recovering from as if the user had written:
8292*67e74705SXin Li // friend void foo<>(int);
8293*67e74705SXin Li // Go ahead and fake up a template id.
8294*67e74705SXin Li HasExplicitTemplateArgs = true;
8295*67e74705SXin Li TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8296*67e74705SXin Li TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8297*67e74705SXin Li }
8298*67e74705SXin Li
8299*67e74705SXin Li // If it's a friend (and only if it's a friend), it's possible
8300*67e74705SXin Li // that either the specialized function type or the specialized
8301*67e74705SXin Li // template is dependent, and therefore matching will fail. In
8302*67e74705SXin Li // this case, don't check the specialization yet.
8303*67e74705SXin Li bool InstantiationDependent = false;
8304*67e74705SXin Li if (isFunctionTemplateSpecialization && isFriend &&
8305*67e74705SXin Li (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8306*67e74705SXin Li TemplateSpecializationType::anyDependentTemplateArguments(
8307*67e74705SXin Li TemplateArgs,
8308*67e74705SXin Li InstantiationDependent))) {
8309*67e74705SXin Li assert(HasExplicitTemplateArgs &&
8310*67e74705SXin Li "friend function specialization without template args");
8311*67e74705SXin Li if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8312*67e74705SXin Li Previous))
8313*67e74705SXin Li NewFD->setInvalidDecl();
8314*67e74705SXin Li } else if (isFunctionTemplateSpecialization) {
8315*67e74705SXin Li if (CurContext->isDependentContext() && CurContext->isRecord()
8316*67e74705SXin Li && !isFriend) {
8317*67e74705SXin Li isDependentClassScopeExplicitSpecialization = true;
8318*67e74705SXin Li Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8319*67e74705SXin Li diag::ext_function_specialization_in_class :
8320*67e74705SXin Li diag::err_function_specialization_in_class)
8321*67e74705SXin Li << NewFD->getDeclName();
8322*67e74705SXin Li } else if (CheckFunctionTemplateSpecialization(NewFD,
8323*67e74705SXin Li (HasExplicitTemplateArgs ? &TemplateArgs
8324*67e74705SXin Li : nullptr),
8325*67e74705SXin Li Previous))
8326*67e74705SXin Li NewFD->setInvalidDecl();
8327*67e74705SXin Li
8328*67e74705SXin Li // C++ [dcl.stc]p1:
8329*67e74705SXin Li // A storage-class-specifier shall not be specified in an explicit
8330*67e74705SXin Li // specialization (14.7.3)
8331*67e74705SXin Li FunctionTemplateSpecializationInfo *Info =
8332*67e74705SXin Li NewFD->getTemplateSpecializationInfo();
8333*67e74705SXin Li if (Info && SC != SC_None) {
8334*67e74705SXin Li if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8335*67e74705SXin Li Diag(NewFD->getLocation(),
8336*67e74705SXin Li diag::err_explicit_specialization_inconsistent_storage_class)
8337*67e74705SXin Li << SC
8338*67e74705SXin Li << FixItHint::CreateRemoval(
8339*67e74705SXin Li D.getDeclSpec().getStorageClassSpecLoc());
8340*67e74705SXin Li
8341*67e74705SXin Li else
8342*67e74705SXin Li Diag(NewFD->getLocation(),
8343*67e74705SXin Li diag::ext_explicit_specialization_storage_class)
8344*67e74705SXin Li << FixItHint::CreateRemoval(
8345*67e74705SXin Li D.getDeclSpec().getStorageClassSpecLoc());
8346*67e74705SXin Li }
8347*67e74705SXin Li } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8348*67e74705SXin Li if (CheckMemberSpecialization(NewFD, Previous))
8349*67e74705SXin Li NewFD->setInvalidDecl();
8350*67e74705SXin Li }
8351*67e74705SXin Li
8352*67e74705SXin Li // Perform semantic checking on the function declaration.
8353*67e74705SXin Li if (!isDependentClassScopeExplicitSpecialization) {
8354*67e74705SXin Li if (!NewFD->isInvalidDecl() && NewFD->isMain())
8355*67e74705SXin Li CheckMain(NewFD, D.getDeclSpec());
8356*67e74705SXin Li
8357*67e74705SXin Li if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8358*67e74705SXin Li CheckMSVCRTEntryPoint(NewFD);
8359*67e74705SXin Li
8360*67e74705SXin Li if (!NewFD->isInvalidDecl())
8361*67e74705SXin Li D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8362*67e74705SXin Li isExplicitSpecialization));
8363*67e74705SXin Li else if (!Previous.empty())
8364*67e74705SXin Li // Recover gracefully from an invalid redeclaration.
8365*67e74705SXin Li D.setRedeclaration(true);
8366*67e74705SXin Li }
8367*67e74705SXin Li
8368*67e74705SXin Li assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8369*67e74705SXin Li Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8370*67e74705SXin Li "previous declaration set still overloaded");
8371*67e74705SXin Li
8372*67e74705SXin Li NamedDecl *PrincipalDecl = (FunctionTemplate
8373*67e74705SXin Li ? cast<NamedDecl>(FunctionTemplate)
8374*67e74705SXin Li : NewFD);
8375*67e74705SXin Li
8376*67e74705SXin Li if (isFriend && D.isRedeclaration()) {
8377*67e74705SXin Li AccessSpecifier Access = AS_public;
8378*67e74705SXin Li if (!NewFD->isInvalidDecl())
8379*67e74705SXin Li Access = NewFD->getPreviousDecl()->getAccess();
8380*67e74705SXin Li
8381*67e74705SXin Li NewFD->setAccess(Access);
8382*67e74705SXin Li if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8383*67e74705SXin Li }
8384*67e74705SXin Li
8385*67e74705SXin Li if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8386*67e74705SXin Li PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8387*67e74705SXin Li PrincipalDecl->setNonMemberOperator();
8388*67e74705SXin Li
8389*67e74705SXin Li // If we have a function template, check the template parameter
8390*67e74705SXin Li // list. This will check and merge default template arguments.
8391*67e74705SXin Li if (FunctionTemplate) {
8392*67e74705SXin Li FunctionTemplateDecl *PrevTemplate =
8393*67e74705SXin Li FunctionTemplate->getPreviousDecl();
8394*67e74705SXin Li CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8395*67e74705SXin Li PrevTemplate ? PrevTemplate->getTemplateParameters()
8396*67e74705SXin Li : nullptr,
8397*67e74705SXin Li D.getDeclSpec().isFriendSpecified()
8398*67e74705SXin Li ? (D.isFunctionDefinition()
8399*67e74705SXin Li ? TPC_FriendFunctionTemplateDefinition
8400*67e74705SXin Li : TPC_FriendFunctionTemplate)
8401*67e74705SXin Li : (D.getCXXScopeSpec().isSet() &&
8402*67e74705SXin Li DC && DC->isRecord() &&
8403*67e74705SXin Li DC->isDependentContext())
8404*67e74705SXin Li ? TPC_ClassTemplateMember
8405*67e74705SXin Li : TPC_FunctionTemplate);
8406*67e74705SXin Li }
8407*67e74705SXin Li
8408*67e74705SXin Li if (NewFD->isInvalidDecl()) {
8409*67e74705SXin Li // Ignore all the rest of this.
8410*67e74705SXin Li } else if (!D.isRedeclaration()) {
8411*67e74705SXin Li struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8412*67e74705SXin Li AddToScope };
8413*67e74705SXin Li // Fake up an access specifier if it's supposed to be a class member.
8414*67e74705SXin Li if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8415*67e74705SXin Li NewFD->setAccess(AS_public);
8416*67e74705SXin Li
8417*67e74705SXin Li // Qualified decls generally require a previous declaration.
8418*67e74705SXin Li if (D.getCXXScopeSpec().isSet()) {
8419*67e74705SXin Li // ...with the major exception of templated-scope or
8420*67e74705SXin Li // dependent-scope friend declarations.
8421*67e74705SXin Li
8422*67e74705SXin Li // TODO: we currently also suppress this check in dependent
8423*67e74705SXin Li // contexts because (1) the parameter depth will be off when
8424*67e74705SXin Li // matching friend templates and (2) we might actually be
8425*67e74705SXin Li // selecting a friend based on a dependent factor. But there
8426*67e74705SXin Li // are situations where these conditions don't apply and we
8427*67e74705SXin Li // can actually do this check immediately.
8428*67e74705SXin Li if (isFriend &&
8429*67e74705SXin Li (TemplateParamLists.size() ||
8430*67e74705SXin Li D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8431*67e74705SXin Li CurContext->isDependentContext())) {
8432*67e74705SXin Li // ignore these
8433*67e74705SXin Li } else {
8434*67e74705SXin Li // The user tried to provide an out-of-line definition for a
8435*67e74705SXin Li // function that is a member of a class or namespace, but there
8436*67e74705SXin Li // was no such member function declared (C++ [class.mfct]p2,
8437*67e74705SXin Li // C++ [namespace.memdef]p2). For example:
8438*67e74705SXin Li //
8439*67e74705SXin Li // class X {
8440*67e74705SXin Li // void f() const;
8441*67e74705SXin Li // };
8442*67e74705SXin Li //
8443*67e74705SXin Li // void X::f() { } // ill-formed
8444*67e74705SXin Li //
8445*67e74705SXin Li // Complain about this problem, and attempt to suggest close
8446*67e74705SXin Li // matches (e.g., those that differ only in cv-qualifiers and
8447*67e74705SXin Li // whether the parameter types are references).
8448*67e74705SXin Li
8449*67e74705SXin Li if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8450*67e74705SXin Li *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8451*67e74705SXin Li AddToScope = ExtraArgs.AddToScope;
8452*67e74705SXin Li return Result;
8453*67e74705SXin Li }
8454*67e74705SXin Li }
8455*67e74705SXin Li
8456*67e74705SXin Li // Unqualified local friend declarations are required to resolve
8457*67e74705SXin Li // to something.
8458*67e74705SXin Li } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8459*67e74705SXin Li if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8460*67e74705SXin Li *this, Previous, NewFD, ExtraArgs, true, S)) {
8461*67e74705SXin Li AddToScope = ExtraArgs.AddToScope;
8462*67e74705SXin Li return Result;
8463*67e74705SXin Li }
8464*67e74705SXin Li }
8465*67e74705SXin Li } else if (!D.isFunctionDefinition() &&
8466*67e74705SXin Li isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8467*67e74705SXin Li !isFriend && !isFunctionTemplateSpecialization &&
8468*67e74705SXin Li !isExplicitSpecialization) {
8469*67e74705SXin Li // An out-of-line member function declaration must also be a
8470*67e74705SXin Li // definition (C++ [class.mfct]p2).
8471*67e74705SXin Li // Note that this is not the case for explicit specializations of
8472*67e74705SXin Li // function templates or member functions of class templates, per
8473*67e74705SXin Li // C++ [temp.expl.spec]p2. We also allow these declarations as an
8474*67e74705SXin Li // extension for compatibility with old SWIG code which likes to
8475*67e74705SXin Li // generate them.
8476*67e74705SXin Li Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8477*67e74705SXin Li << D.getCXXScopeSpec().getRange();
8478*67e74705SXin Li }
8479*67e74705SXin Li }
8480*67e74705SXin Li
8481*67e74705SXin Li ProcessPragmaWeak(S, NewFD);
8482*67e74705SXin Li checkAttributesAfterMerging(*this, *NewFD);
8483*67e74705SXin Li
8484*67e74705SXin Li AddKnownFunctionAttributes(NewFD);
8485*67e74705SXin Li
8486*67e74705SXin Li if (NewFD->hasAttr<OverloadableAttr>() &&
8487*67e74705SXin Li !NewFD->getType()->getAs<FunctionProtoType>()) {
8488*67e74705SXin Li Diag(NewFD->getLocation(),
8489*67e74705SXin Li diag::err_attribute_overloadable_no_prototype)
8490*67e74705SXin Li << NewFD;
8491*67e74705SXin Li
8492*67e74705SXin Li // Turn this into a variadic function with no parameters.
8493*67e74705SXin Li const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8494*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI(
8495*67e74705SXin Li Context.getDefaultCallingConvention(true, false));
8496*67e74705SXin Li EPI.Variadic = true;
8497*67e74705SXin Li EPI.ExtInfo = FT->getExtInfo();
8498*67e74705SXin Li
8499*67e74705SXin Li QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8500*67e74705SXin Li NewFD->setType(R);
8501*67e74705SXin Li }
8502*67e74705SXin Li
8503*67e74705SXin Li // If there's a #pragma GCC visibility in scope, and this isn't a class
8504*67e74705SXin Li // member, set the visibility of this function.
8505*67e74705SXin Li if (!DC->isRecord() && NewFD->isExternallyVisible())
8506*67e74705SXin Li AddPushedVisibilityAttribute(NewFD);
8507*67e74705SXin Li
8508*67e74705SXin Li // If there's a #pragma clang arc_cf_code_audited in scope, consider
8509*67e74705SXin Li // marking the function.
8510*67e74705SXin Li AddCFAuditedAttribute(NewFD);
8511*67e74705SXin Li
8512*67e74705SXin Li // If this is a function definition, check if we have to apply optnone due to
8513*67e74705SXin Li // a pragma.
8514*67e74705SXin Li if(D.isFunctionDefinition())
8515*67e74705SXin Li AddRangeBasedOptnone(NewFD);
8516*67e74705SXin Li
8517*67e74705SXin Li // If this is the first declaration of an extern C variable, update
8518*67e74705SXin Li // the map of such variables.
8519*67e74705SXin Li if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8520*67e74705SXin Li isIncompleteDeclExternC(*this, NewFD))
8521*67e74705SXin Li RegisterLocallyScopedExternCDecl(NewFD, S);
8522*67e74705SXin Li
8523*67e74705SXin Li // Set this FunctionDecl's range up to the right paren.
8524*67e74705SXin Li NewFD->setRangeEnd(D.getSourceRange().getEnd());
8525*67e74705SXin Li
8526*67e74705SXin Li if (D.isRedeclaration() && !Previous.empty()) {
8527*67e74705SXin Li checkDLLAttributeRedeclaration(
8528*67e74705SXin Li *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8529*67e74705SXin Li isExplicitSpecialization || isFunctionTemplateSpecialization,
8530*67e74705SXin Li D.isFunctionDefinition());
8531*67e74705SXin Li }
8532*67e74705SXin Li
8533*67e74705SXin Li if (getLangOpts().CUDA) {
8534*67e74705SXin Li IdentifierInfo *II = NewFD->getIdentifier();
8535*67e74705SXin Li if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8536*67e74705SXin Li NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8537*67e74705SXin Li if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8538*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8539*67e74705SXin Li
8540*67e74705SXin Li Context.setcudaConfigureCallDecl(NewFD);
8541*67e74705SXin Li }
8542*67e74705SXin Li
8543*67e74705SXin Li // Variadic functions, other than a *declaration* of printf, are not allowed
8544*67e74705SXin Li // in device-side CUDA code, unless someone passed
8545*67e74705SXin Li // -fcuda-allow-variadic-functions.
8546*67e74705SXin Li if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8547*67e74705SXin Li (NewFD->hasAttr<CUDADeviceAttr>() ||
8548*67e74705SXin Li NewFD->hasAttr<CUDAGlobalAttr>()) &&
8549*67e74705SXin Li !(II && II->isStr("printf") && NewFD->isExternC() &&
8550*67e74705SXin Li !D.isFunctionDefinition())) {
8551*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8552*67e74705SXin Li }
8553*67e74705SXin Li }
8554*67e74705SXin Li
8555*67e74705SXin Li if (getLangOpts().CPlusPlus) {
8556*67e74705SXin Li if (FunctionTemplate) {
8557*67e74705SXin Li if (NewFD->isInvalidDecl())
8558*67e74705SXin Li FunctionTemplate->setInvalidDecl();
8559*67e74705SXin Li return FunctionTemplate;
8560*67e74705SXin Li }
8561*67e74705SXin Li }
8562*67e74705SXin Li
8563*67e74705SXin Li if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8564*67e74705SXin Li // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8565*67e74705SXin Li if ((getLangOpts().OpenCLVersion >= 120)
8566*67e74705SXin Li && (SC == SC_Static)) {
8567*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8568*67e74705SXin Li D.setInvalidType();
8569*67e74705SXin Li }
8570*67e74705SXin Li
8571*67e74705SXin Li // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8572*67e74705SXin Li if (!NewFD->getReturnType()->isVoidType()) {
8573*67e74705SXin Li SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8574*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8575*67e74705SXin Li << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8576*67e74705SXin Li : FixItHint());
8577*67e74705SXin Li D.setInvalidType();
8578*67e74705SXin Li }
8579*67e74705SXin Li
8580*67e74705SXin Li llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8581*67e74705SXin Li for (auto Param : NewFD->parameters())
8582*67e74705SXin Li checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8583*67e74705SXin Li }
8584*67e74705SXin Li for (const ParmVarDecl *Param : NewFD->parameters()) {
8585*67e74705SXin Li QualType PT = Param->getType();
8586*67e74705SXin Li
8587*67e74705SXin Li // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8588*67e74705SXin Li // types.
8589*67e74705SXin Li if (getLangOpts().OpenCLVersion >= 200) {
8590*67e74705SXin Li if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8591*67e74705SXin Li QualType ElemTy = PipeTy->getElementType();
8592*67e74705SXin Li if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8593*67e74705SXin Li Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8594*67e74705SXin Li D.setInvalidType();
8595*67e74705SXin Li }
8596*67e74705SXin Li }
8597*67e74705SXin Li }
8598*67e74705SXin Li }
8599*67e74705SXin Li
8600*67e74705SXin Li MarkUnusedFileScopedDecl(NewFD);
8601*67e74705SXin Li
8602*67e74705SXin Li // Here we have an function template explicit specialization at class scope.
8603*67e74705SXin Li // The actually specialization will be postponed to template instatiation
8604*67e74705SXin Li // time via the ClassScopeFunctionSpecializationDecl node.
8605*67e74705SXin Li if (isDependentClassScopeExplicitSpecialization) {
8606*67e74705SXin Li ClassScopeFunctionSpecializationDecl *NewSpec =
8607*67e74705SXin Li ClassScopeFunctionSpecializationDecl::Create(
8608*67e74705SXin Li Context, CurContext, SourceLocation(),
8609*67e74705SXin Li cast<CXXMethodDecl>(NewFD),
8610*67e74705SXin Li HasExplicitTemplateArgs, TemplateArgs);
8611*67e74705SXin Li CurContext->addDecl(NewSpec);
8612*67e74705SXin Li AddToScope = false;
8613*67e74705SXin Li }
8614*67e74705SXin Li
8615*67e74705SXin Li return NewFD;
8616*67e74705SXin Li }
8617*67e74705SXin Li
8618*67e74705SXin Li /// \brief Perform semantic checking of a new function declaration.
8619*67e74705SXin Li ///
8620*67e74705SXin Li /// Performs semantic analysis of the new function declaration
8621*67e74705SXin Li /// NewFD. This routine performs all semantic checking that does not
8622*67e74705SXin Li /// require the actual declarator involved in the declaration, and is
8623*67e74705SXin Li /// used both for the declaration of functions as they are parsed
8624*67e74705SXin Li /// (called via ActOnDeclarator) and for the declaration of functions
8625*67e74705SXin Li /// that have been instantiated via C++ template instantiation (called
8626*67e74705SXin Li /// via InstantiateDecl).
8627*67e74705SXin Li ///
8628*67e74705SXin Li /// \param IsExplicitSpecialization whether this new function declaration is
8629*67e74705SXin Li /// an explicit specialization of the previous declaration.
8630*67e74705SXin Li ///
8631*67e74705SXin Li /// This sets NewFD->isInvalidDecl() to true if there was an error.
8632*67e74705SXin Li ///
8633*67e74705SXin Li /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsExplicitSpecialization)8634*67e74705SXin Li bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8635*67e74705SXin Li LookupResult &Previous,
8636*67e74705SXin Li bool IsExplicitSpecialization) {
8637*67e74705SXin Li assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8638*67e74705SXin Li "Variably modified return types are not handled here");
8639*67e74705SXin Li
8640*67e74705SXin Li // Determine whether the type of this function should be merged with
8641*67e74705SXin Li // a previous visible declaration. This never happens for functions in C++,
8642*67e74705SXin Li // and always happens in C if the previous declaration was visible.
8643*67e74705SXin Li bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8644*67e74705SXin Li !Previous.isShadowed();
8645*67e74705SXin Li
8646*67e74705SXin Li bool Redeclaration = false;
8647*67e74705SXin Li NamedDecl *OldDecl = nullptr;
8648*67e74705SXin Li
8649*67e74705SXin Li // Merge or overload the declaration with an existing declaration of
8650*67e74705SXin Li // the same name, if appropriate.
8651*67e74705SXin Li if (!Previous.empty()) {
8652*67e74705SXin Li // Determine whether NewFD is an overload of PrevDecl or
8653*67e74705SXin Li // a declaration that requires merging. If it's an overload,
8654*67e74705SXin Li // there's no more work to do here; we'll just add the new
8655*67e74705SXin Li // function to the scope.
8656*67e74705SXin Li if (!AllowOverloadingOfFunction(Previous, Context)) {
8657*67e74705SXin Li NamedDecl *Candidate = Previous.getRepresentativeDecl();
8658*67e74705SXin Li if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8659*67e74705SXin Li Redeclaration = true;
8660*67e74705SXin Li OldDecl = Candidate;
8661*67e74705SXin Li }
8662*67e74705SXin Li } else {
8663*67e74705SXin Li switch (CheckOverload(S, NewFD, Previous, OldDecl,
8664*67e74705SXin Li /*NewIsUsingDecl*/ false)) {
8665*67e74705SXin Li case Ovl_Match:
8666*67e74705SXin Li Redeclaration = true;
8667*67e74705SXin Li break;
8668*67e74705SXin Li
8669*67e74705SXin Li case Ovl_NonFunction:
8670*67e74705SXin Li Redeclaration = true;
8671*67e74705SXin Li break;
8672*67e74705SXin Li
8673*67e74705SXin Li case Ovl_Overload:
8674*67e74705SXin Li Redeclaration = false;
8675*67e74705SXin Li break;
8676*67e74705SXin Li }
8677*67e74705SXin Li
8678*67e74705SXin Li if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8679*67e74705SXin Li // If a function name is overloadable in C, then every function
8680*67e74705SXin Li // with that name must be marked "overloadable".
8681*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8682*67e74705SXin Li << Redeclaration << NewFD;
8683*67e74705SXin Li NamedDecl *OverloadedDecl = nullptr;
8684*67e74705SXin Li if (Redeclaration)
8685*67e74705SXin Li OverloadedDecl = OldDecl;
8686*67e74705SXin Li else if (!Previous.empty())
8687*67e74705SXin Li OverloadedDecl = Previous.getRepresentativeDecl();
8688*67e74705SXin Li if (OverloadedDecl)
8689*67e74705SXin Li Diag(OverloadedDecl->getLocation(),
8690*67e74705SXin Li diag::note_attribute_overloadable_prev_overload);
8691*67e74705SXin Li NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8692*67e74705SXin Li }
8693*67e74705SXin Li }
8694*67e74705SXin Li }
8695*67e74705SXin Li
8696*67e74705SXin Li // Check for a previous extern "C" declaration with this name.
8697*67e74705SXin Li if (!Redeclaration &&
8698*67e74705SXin Li checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8699*67e74705SXin Li if (!Previous.empty()) {
8700*67e74705SXin Li // This is an extern "C" declaration with the same name as a previous
8701*67e74705SXin Li // declaration, and thus redeclares that entity...
8702*67e74705SXin Li Redeclaration = true;
8703*67e74705SXin Li OldDecl = Previous.getFoundDecl();
8704*67e74705SXin Li MergeTypeWithPrevious = false;
8705*67e74705SXin Li
8706*67e74705SXin Li // ... except in the presence of __attribute__((overloadable)).
8707*67e74705SXin Li if (OldDecl->hasAttr<OverloadableAttr>()) {
8708*67e74705SXin Li if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8709*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8710*67e74705SXin Li << Redeclaration << NewFD;
8711*67e74705SXin Li Diag(Previous.getFoundDecl()->getLocation(),
8712*67e74705SXin Li diag::note_attribute_overloadable_prev_overload);
8713*67e74705SXin Li NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8714*67e74705SXin Li }
8715*67e74705SXin Li if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8716*67e74705SXin Li Redeclaration = false;
8717*67e74705SXin Li OldDecl = nullptr;
8718*67e74705SXin Li }
8719*67e74705SXin Li }
8720*67e74705SXin Li }
8721*67e74705SXin Li }
8722*67e74705SXin Li
8723*67e74705SXin Li // C++11 [dcl.constexpr]p8:
8724*67e74705SXin Li // A constexpr specifier for a non-static member function that is not
8725*67e74705SXin Li // a constructor declares that member function to be const.
8726*67e74705SXin Li //
8727*67e74705SXin Li // This needs to be delayed until we know whether this is an out-of-line
8728*67e74705SXin Li // definition of a static member function.
8729*67e74705SXin Li //
8730*67e74705SXin Li // This rule is not present in C++1y, so we produce a backwards
8731*67e74705SXin Li // compatibility warning whenever it happens in C++11.
8732*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8733*67e74705SXin Li if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8734*67e74705SXin Li !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8735*67e74705SXin Li (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8736*67e74705SXin Li CXXMethodDecl *OldMD = nullptr;
8737*67e74705SXin Li if (OldDecl)
8738*67e74705SXin Li OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8739*67e74705SXin Li if (!OldMD || !OldMD->isStatic()) {
8740*67e74705SXin Li const FunctionProtoType *FPT =
8741*67e74705SXin Li MD->getType()->castAs<FunctionProtoType>();
8742*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8743*67e74705SXin Li EPI.TypeQuals |= Qualifiers::Const;
8744*67e74705SXin Li MD->setType(Context.getFunctionType(FPT->getReturnType(),
8745*67e74705SXin Li FPT->getParamTypes(), EPI));
8746*67e74705SXin Li
8747*67e74705SXin Li // Warn that we did this, if we're not performing template instantiation.
8748*67e74705SXin Li // In that case, we'll have warned already when the template was defined.
8749*67e74705SXin Li if (ActiveTemplateInstantiations.empty()) {
8750*67e74705SXin Li SourceLocation AddConstLoc;
8751*67e74705SXin Li if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8752*67e74705SXin Li .IgnoreParens().getAs<FunctionTypeLoc>())
8753*67e74705SXin Li AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8754*67e74705SXin Li
8755*67e74705SXin Li Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8756*67e74705SXin Li << FixItHint::CreateInsertion(AddConstLoc, " const");
8757*67e74705SXin Li }
8758*67e74705SXin Li }
8759*67e74705SXin Li }
8760*67e74705SXin Li
8761*67e74705SXin Li if (Redeclaration) {
8762*67e74705SXin Li // NewFD and OldDecl represent declarations that need to be
8763*67e74705SXin Li // merged.
8764*67e74705SXin Li if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8765*67e74705SXin Li NewFD->setInvalidDecl();
8766*67e74705SXin Li return Redeclaration;
8767*67e74705SXin Li }
8768*67e74705SXin Li
8769*67e74705SXin Li Previous.clear();
8770*67e74705SXin Li Previous.addDecl(OldDecl);
8771*67e74705SXin Li
8772*67e74705SXin Li if (FunctionTemplateDecl *OldTemplateDecl
8773*67e74705SXin Li = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8774*67e74705SXin Li NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8775*67e74705SXin Li FunctionTemplateDecl *NewTemplateDecl
8776*67e74705SXin Li = NewFD->getDescribedFunctionTemplate();
8777*67e74705SXin Li assert(NewTemplateDecl && "Template/non-template mismatch");
8778*67e74705SXin Li if (CXXMethodDecl *Method
8779*67e74705SXin Li = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8780*67e74705SXin Li Method->setAccess(OldTemplateDecl->getAccess());
8781*67e74705SXin Li NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8782*67e74705SXin Li }
8783*67e74705SXin Li
8784*67e74705SXin Li // If this is an explicit specialization of a member that is a function
8785*67e74705SXin Li // template, mark it as a member specialization.
8786*67e74705SXin Li if (IsExplicitSpecialization &&
8787*67e74705SXin Li NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8788*67e74705SXin Li NewTemplateDecl->setMemberSpecialization();
8789*67e74705SXin Li assert(OldTemplateDecl->isMemberSpecialization());
8790*67e74705SXin Li // Explicit specializations of a member template do not inherit deleted
8791*67e74705SXin Li // status from the parent member template that they are specializing.
8792*67e74705SXin Li if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8793*67e74705SXin Li FunctionDecl *const OldTemplatedDecl =
8794*67e74705SXin Li OldTemplateDecl->getTemplatedDecl();
8795*67e74705SXin Li assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8796*67e74705SXin Li OldTemplatedDecl->setDeletedAsWritten(false);
8797*67e74705SXin Li }
8798*67e74705SXin Li }
8799*67e74705SXin Li
8800*67e74705SXin Li } else {
8801*67e74705SXin Li // This needs to happen first so that 'inline' propagates.
8802*67e74705SXin Li NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8803*67e74705SXin Li
8804*67e74705SXin Li if (isa<CXXMethodDecl>(NewFD))
8805*67e74705SXin Li NewFD->setAccess(OldDecl->getAccess());
8806*67e74705SXin Li }
8807*67e74705SXin Li }
8808*67e74705SXin Li
8809*67e74705SXin Li // Semantic checking for this function declaration (in isolation).
8810*67e74705SXin Li
8811*67e74705SXin Li if (getLangOpts().CPlusPlus) {
8812*67e74705SXin Li // C++-specific checks.
8813*67e74705SXin Li if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8814*67e74705SXin Li CheckConstructor(Constructor);
8815*67e74705SXin Li } else if (CXXDestructorDecl *Destructor =
8816*67e74705SXin Li dyn_cast<CXXDestructorDecl>(NewFD)) {
8817*67e74705SXin Li CXXRecordDecl *Record = Destructor->getParent();
8818*67e74705SXin Li QualType ClassType = Context.getTypeDeclType(Record);
8819*67e74705SXin Li
8820*67e74705SXin Li // FIXME: Shouldn't we be able to perform this check even when the class
8821*67e74705SXin Li // type is dependent? Both gcc and edg can handle that.
8822*67e74705SXin Li if (!ClassType->isDependentType()) {
8823*67e74705SXin Li DeclarationName Name
8824*67e74705SXin Li = Context.DeclarationNames.getCXXDestructorName(
8825*67e74705SXin Li Context.getCanonicalType(ClassType));
8826*67e74705SXin Li if (NewFD->getDeclName() != Name) {
8827*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_destructor_name);
8828*67e74705SXin Li NewFD->setInvalidDecl();
8829*67e74705SXin Li return Redeclaration;
8830*67e74705SXin Li }
8831*67e74705SXin Li }
8832*67e74705SXin Li } else if (CXXConversionDecl *Conversion
8833*67e74705SXin Li = dyn_cast<CXXConversionDecl>(NewFD)) {
8834*67e74705SXin Li ActOnConversionDeclarator(Conversion);
8835*67e74705SXin Li }
8836*67e74705SXin Li
8837*67e74705SXin Li // Find any virtual functions that this function overrides.
8838*67e74705SXin Li if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8839*67e74705SXin Li if (!Method->isFunctionTemplateSpecialization() &&
8840*67e74705SXin Li !Method->getDescribedFunctionTemplate() &&
8841*67e74705SXin Li Method->isCanonicalDecl()) {
8842*67e74705SXin Li if (AddOverriddenMethods(Method->getParent(), Method)) {
8843*67e74705SXin Li // If the function was marked as "static", we have a problem.
8844*67e74705SXin Li if (NewFD->getStorageClass() == SC_Static) {
8845*67e74705SXin Li ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8846*67e74705SXin Li }
8847*67e74705SXin Li }
8848*67e74705SXin Li }
8849*67e74705SXin Li
8850*67e74705SXin Li if (Method->isStatic())
8851*67e74705SXin Li checkThisInStaticMemberFunctionType(Method);
8852*67e74705SXin Li }
8853*67e74705SXin Li
8854*67e74705SXin Li // Extra checking for C++ overloaded operators (C++ [over.oper]).
8855*67e74705SXin Li if (NewFD->isOverloadedOperator() &&
8856*67e74705SXin Li CheckOverloadedOperatorDeclaration(NewFD)) {
8857*67e74705SXin Li NewFD->setInvalidDecl();
8858*67e74705SXin Li return Redeclaration;
8859*67e74705SXin Li }
8860*67e74705SXin Li
8861*67e74705SXin Li // Extra checking for C++0x literal operators (C++0x [over.literal]).
8862*67e74705SXin Li if (NewFD->getLiteralIdentifier() &&
8863*67e74705SXin Li CheckLiteralOperatorDeclaration(NewFD)) {
8864*67e74705SXin Li NewFD->setInvalidDecl();
8865*67e74705SXin Li return Redeclaration;
8866*67e74705SXin Li }
8867*67e74705SXin Li
8868*67e74705SXin Li // In C++, check default arguments now that we have merged decls. Unless
8869*67e74705SXin Li // the lexical context is the class, because in this case this is done
8870*67e74705SXin Li // during delayed parsing anyway.
8871*67e74705SXin Li if (!CurContext->isRecord())
8872*67e74705SXin Li CheckCXXDefaultArguments(NewFD);
8873*67e74705SXin Li
8874*67e74705SXin Li // If this function declares a builtin function, check the type of this
8875*67e74705SXin Li // declaration against the expected type for the builtin.
8876*67e74705SXin Li if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8877*67e74705SXin Li ASTContext::GetBuiltinTypeError Error;
8878*67e74705SXin Li LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8879*67e74705SXin Li QualType T = Context.GetBuiltinType(BuiltinID, Error);
8880*67e74705SXin Li if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8881*67e74705SXin Li // The type of this function differs from the type of the builtin,
8882*67e74705SXin Li // so forget about the builtin entirely.
8883*67e74705SXin Li Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8884*67e74705SXin Li }
8885*67e74705SXin Li }
8886*67e74705SXin Li
8887*67e74705SXin Li // If this function is declared as being extern "C", then check to see if
8888*67e74705SXin Li // the function returns a UDT (class, struct, or union type) that is not C
8889*67e74705SXin Li // compatible, and if it does, warn the user.
8890*67e74705SXin Li // But, issue any diagnostic on the first declaration only.
8891*67e74705SXin Li if (Previous.empty() && NewFD->isExternC()) {
8892*67e74705SXin Li QualType R = NewFD->getReturnType();
8893*67e74705SXin Li if (R->isIncompleteType() && !R->isVoidType())
8894*67e74705SXin Li Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8895*67e74705SXin Li << NewFD << R;
8896*67e74705SXin Li else if (!R.isPODType(Context) && !R->isVoidType() &&
8897*67e74705SXin Li !R->isObjCObjectPointerType())
8898*67e74705SXin Li Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8899*67e74705SXin Li }
8900*67e74705SXin Li }
8901*67e74705SXin Li return Redeclaration;
8902*67e74705SXin Li }
8903*67e74705SXin Li
CheckMain(FunctionDecl * FD,const DeclSpec & DS)8904*67e74705SXin Li void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8905*67e74705SXin Li // C++11 [basic.start.main]p3:
8906*67e74705SXin Li // A program that [...] declares main to be inline, static or
8907*67e74705SXin Li // constexpr is ill-formed.
8908*67e74705SXin Li // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8909*67e74705SXin Li // appear in a declaration of main.
8910*67e74705SXin Li // static main is not an error under C99, but we should warn about it.
8911*67e74705SXin Li // We accept _Noreturn main as an extension.
8912*67e74705SXin Li if (FD->getStorageClass() == SC_Static)
8913*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8914*67e74705SXin Li ? diag::err_static_main : diag::warn_static_main)
8915*67e74705SXin Li << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8916*67e74705SXin Li if (FD->isInlineSpecified())
8917*67e74705SXin Li Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8918*67e74705SXin Li << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8919*67e74705SXin Li if (DS.isNoreturnSpecified()) {
8920*67e74705SXin Li SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8921*67e74705SXin Li SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8922*67e74705SXin Li Diag(NoreturnLoc, diag::ext_noreturn_main);
8923*67e74705SXin Li Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8924*67e74705SXin Li << FixItHint::CreateRemoval(NoreturnRange);
8925*67e74705SXin Li }
8926*67e74705SXin Li if (FD->isConstexpr()) {
8927*67e74705SXin Li Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8928*67e74705SXin Li << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8929*67e74705SXin Li FD->setConstexpr(false);
8930*67e74705SXin Li }
8931*67e74705SXin Li
8932*67e74705SXin Li if (getLangOpts().OpenCL) {
8933*67e74705SXin Li Diag(FD->getLocation(), diag::err_opencl_no_main)
8934*67e74705SXin Li << FD->hasAttr<OpenCLKernelAttr>();
8935*67e74705SXin Li FD->setInvalidDecl();
8936*67e74705SXin Li return;
8937*67e74705SXin Li }
8938*67e74705SXin Li
8939*67e74705SXin Li QualType T = FD->getType();
8940*67e74705SXin Li assert(T->isFunctionType() && "function decl is not of function type");
8941*67e74705SXin Li const FunctionType* FT = T->castAs<FunctionType>();
8942*67e74705SXin Li
8943*67e74705SXin Li if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8944*67e74705SXin Li // In C with GNU extensions we allow main() to have non-integer return
8945*67e74705SXin Li // type, but we should warn about the extension, and we disable the
8946*67e74705SXin Li // implicit-return-zero rule.
8947*67e74705SXin Li
8948*67e74705SXin Li // GCC in C mode accepts qualified 'int'.
8949*67e74705SXin Li if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8950*67e74705SXin Li FD->setHasImplicitReturnZero(true);
8951*67e74705SXin Li else {
8952*67e74705SXin Li Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8953*67e74705SXin Li SourceRange RTRange = FD->getReturnTypeSourceRange();
8954*67e74705SXin Li if (RTRange.isValid())
8955*67e74705SXin Li Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8956*67e74705SXin Li << FixItHint::CreateReplacement(RTRange, "int");
8957*67e74705SXin Li }
8958*67e74705SXin Li } else {
8959*67e74705SXin Li // In C and C++, main magically returns 0 if you fall off the end;
8960*67e74705SXin Li // set the flag which tells us that.
8961*67e74705SXin Li // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8962*67e74705SXin Li
8963*67e74705SXin Li // All the standards say that main() should return 'int'.
8964*67e74705SXin Li if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8965*67e74705SXin Li FD->setHasImplicitReturnZero(true);
8966*67e74705SXin Li else {
8967*67e74705SXin Li // Otherwise, this is just a flat-out error.
8968*67e74705SXin Li SourceRange RTRange = FD->getReturnTypeSourceRange();
8969*67e74705SXin Li Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8970*67e74705SXin Li << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8971*67e74705SXin Li : FixItHint());
8972*67e74705SXin Li FD->setInvalidDecl(true);
8973*67e74705SXin Li }
8974*67e74705SXin Li }
8975*67e74705SXin Li
8976*67e74705SXin Li // Treat protoless main() as nullary.
8977*67e74705SXin Li if (isa<FunctionNoProtoType>(FT)) return;
8978*67e74705SXin Li
8979*67e74705SXin Li const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8980*67e74705SXin Li unsigned nparams = FTP->getNumParams();
8981*67e74705SXin Li assert(FD->getNumParams() == nparams);
8982*67e74705SXin Li
8983*67e74705SXin Li bool HasExtraParameters = (nparams > 3);
8984*67e74705SXin Li
8985*67e74705SXin Li if (FTP->isVariadic()) {
8986*67e74705SXin Li Diag(FD->getLocation(), diag::ext_variadic_main);
8987*67e74705SXin Li // FIXME: if we had information about the location of the ellipsis, we
8988*67e74705SXin Li // could add a FixIt hint to remove it as a parameter.
8989*67e74705SXin Li }
8990*67e74705SXin Li
8991*67e74705SXin Li // Darwin passes an undocumented fourth argument of type char**. If
8992*67e74705SXin Li // other platforms start sprouting these, the logic below will start
8993*67e74705SXin Li // getting shifty.
8994*67e74705SXin Li if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8995*67e74705SXin Li HasExtraParameters = false;
8996*67e74705SXin Li
8997*67e74705SXin Li if (HasExtraParameters) {
8998*67e74705SXin Li Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8999*67e74705SXin Li FD->setInvalidDecl(true);
9000*67e74705SXin Li nparams = 3;
9001*67e74705SXin Li }
9002*67e74705SXin Li
9003*67e74705SXin Li // FIXME: a lot of the following diagnostics would be improved
9004*67e74705SXin Li // if we had some location information about types.
9005*67e74705SXin Li
9006*67e74705SXin Li QualType CharPP =
9007*67e74705SXin Li Context.getPointerType(Context.getPointerType(Context.CharTy));
9008*67e74705SXin Li QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9009*67e74705SXin Li
9010*67e74705SXin Li for (unsigned i = 0; i < nparams; ++i) {
9011*67e74705SXin Li QualType AT = FTP->getParamType(i);
9012*67e74705SXin Li
9013*67e74705SXin Li bool mismatch = true;
9014*67e74705SXin Li
9015*67e74705SXin Li if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9016*67e74705SXin Li mismatch = false;
9017*67e74705SXin Li else if (Expected[i] == CharPP) {
9018*67e74705SXin Li // As an extension, the following forms are okay:
9019*67e74705SXin Li // char const **
9020*67e74705SXin Li // char const * const *
9021*67e74705SXin Li // char * const *
9022*67e74705SXin Li
9023*67e74705SXin Li QualifierCollector qs;
9024*67e74705SXin Li const PointerType* PT;
9025*67e74705SXin Li if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9026*67e74705SXin Li (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9027*67e74705SXin Li Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9028*67e74705SXin Li Context.CharTy)) {
9029*67e74705SXin Li qs.removeConst();
9030*67e74705SXin Li mismatch = !qs.empty();
9031*67e74705SXin Li }
9032*67e74705SXin Li }
9033*67e74705SXin Li
9034*67e74705SXin Li if (mismatch) {
9035*67e74705SXin Li Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9036*67e74705SXin Li // TODO: suggest replacing given type with expected type
9037*67e74705SXin Li FD->setInvalidDecl(true);
9038*67e74705SXin Li }
9039*67e74705SXin Li }
9040*67e74705SXin Li
9041*67e74705SXin Li if (nparams == 1 && !FD->isInvalidDecl()) {
9042*67e74705SXin Li Diag(FD->getLocation(), diag::warn_main_one_arg);
9043*67e74705SXin Li }
9044*67e74705SXin Li
9045*67e74705SXin Li if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9046*67e74705SXin Li Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9047*67e74705SXin Li FD->setInvalidDecl();
9048*67e74705SXin Li }
9049*67e74705SXin Li }
9050*67e74705SXin Li
CheckMSVCRTEntryPoint(FunctionDecl * FD)9051*67e74705SXin Li void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9052*67e74705SXin Li QualType T = FD->getType();
9053*67e74705SXin Li assert(T->isFunctionType() && "function decl is not of function type");
9054*67e74705SXin Li const FunctionType *FT = T->castAs<FunctionType>();
9055*67e74705SXin Li
9056*67e74705SXin Li // Set an implicit return of 'zero' if the function can return some integral,
9057*67e74705SXin Li // enumeration, pointer or nullptr type.
9058*67e74705SXin Li if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9059*67e74705SXin Li FT->getReturnType()->isAnyPointerType() ||
9060*67e74705SXin Li FT->getReturnType()->isNullPtrType())
9061*67e74705SXin Li // DllMain is exempt because a return value of zero means it failed.
9062*67e74705SXin Li if (FD->getName() != "DllMain")
9063*67e74705SXin Li FD->setHasImplicitReturnZero(true);
9064*67e74705SXin Li
9065*67e74705SXin Li if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9066*67e74705SXin Li Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9067*67e74705SXin Li FD->setInvalidDecl();
9068*67e74705SXin Li }
9069*67e74705SXin Li }
9070*67e74705SXin Li
CheckForConstantInitializer(Expr * Init,QualType DclT)9071*67e74705SXin Li bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9072*67e74705SXin Li // FIXME: Need strict checking. In C89, we need to check for
9073*67e74705SXin Li // any assignment, increment, decrement, function-calls, or
9074*67e74705SXin Li // commas outside of a sizeof. In C99, it's the same list,
9075*67e74705SXin Li // except that the aforementioned are allowed in unevaluated
9076*67e74705SXin Li // expressions. Everything else falls under the
9077*67e74705SXin Li // "may accept other forms of constant expressions" exception.
9078*67e74705SXin Li // (We never end up here for C++, so the constant expression
9079*67e74705SXin Li // rules there don't matter.)
9080*67e74705SXin Li const Expr *Culprit;
9081*67e74705SXin Li if (Init->isConstantInitializer(Context, false, &Culprit))
9082*67e74705SXin Li return false;
9083*67e74705SXin Li Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9084*67e74705SXin Li << Culprit->getSourceRange();
9085*67e74705SXin Li return true;
9086*67e74705SXin Li }
9087*67e74705SXin Li
9088*67e74705SXin Li namespace {
9089*67e74705SXin Li // Visits an initialization expression to see if OrigDecl is evaluated in
9090*67e74705SXin Li // its own initialization and throws a warning if it does.
9091*67e74705SXin Li class SelfReferenceChecker
9092*67e74705SXin Li : public EvaluatedExprVisitor<SelfReferenceChecker> {
9093*67e74705SXin Li Sema &S;
9094*67e74705SXin Li Decl *OrigDecl;
9095*67e74705SXin Li bool isRecordType;
9096*67e74705SXin Li bool isPODType;
9097*67e74705SXin Li bool isReferenceType;
9098*67e74705SXin Li
9099*67e74705SXin Li bool isInitList;
9100*67e74705SXin Li llvm::SmallVector<unsigned, 4> InitFieldIndex;
9101*67e74705SXin Li
9102*67e74705SXin Li public:
9103*67e74705SXin Li typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9104*67e74705SXin Li
SelfReferenceChecker(Sema & S,Decl * OrigDecl)9105*67e74705SXin Li SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9106*67e74705SXin Li S(S), OrigDecl(OrigDecl) {
9107*67e74705SXin Li isPODType = false;
9108*67e74705SXin Li isRecordType = false;
9109*67e74705SXin Li isReferenceType = false;
9110*67e74705SXin Li isInitList = false;
9111*67e74705SXin Li if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9112*67e74705SXin Li isPODType = VD->getType().isPODType(S.Context);
9113*67e74705SXin Li isRecordType = VD->getType()->isRecordType();
9114*67e74705SXin Li isReferenceType = VD->getType()->isReferenceType();
9115*67e74705SXin Li }
9116*67e74705SXin Li }
9117*67e74705SXin Li
9118*67e74705SXin Li // For most expressions, just call the visitor. For initializer lists,
9119*67e74705SXin Li // track the index of the field being initialized since fields are
9120*67e74705SXin Li // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)9121*67e74705SXin Li void CheckExpr(Expr *E) {
9122*67e74705SXin Li InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9123*67e74705SXin Li if (!InitList) {
9124*67e74705SXin Li Visit(E);
9125*67e74705SXin Li return;
9126*67e74705SXin Li }
9127*67e74705SXin Li
9128*67e74705SXin Li // Track and increment the index here.
9129*67e74705SXin Li isInitList = true;
9130*67e74705SXin Li InitFieldIndex.push_back(0);
9131*67e74705SXin Li for (auto Child : InitList->children()) {
9132*67e74705SXin Li CheckExpr(cast<Expr>(Child));
9133*67e74705SXin Li ++InitFieldIndex.back();
9134*67e74705SXin Li }
9135*67e74705SXin Li InitFieldIndex.pop_back();
9136*67e74705SXin Li }
9137*67e74705SXin Li
9138*67e74705SXin Li // Returns true if MemberExpr is checked and no futher checking is needed.
9139*67e74705SXin Li // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)9140*67e74705SXin Li bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9141*67e74705SXin Li llvm::SmallVector<FieldDecl*, 4> Fields;
9142*67e74705SXin Li Expr *Base = E;
9143*67e74705SXin Li bool ReferenceField = false;
9144*67e74705SXin Li
9145*67e74705SXin Li // Get the field memebers used.
9146*67e74705SXin Li while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9147*67e74705SXin Li FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9148*67e74705SXin Li if (!FD)
9149*67e74705SXin Li return false;
9150*67e74705SXin Li Fields.push_back(FD);
9151*67e74705SXin Li if (FD->getType()->isReferenceType())
9152*67e74705SXin Li ReferenceField = true;
9153*67e74705SXin Li Base = ME->getBase()->IgnoreParenImpCasts();
9154*67e74705SXin Li }
9155*67e74705SXin Li
9156*67e74705SXin Li // Keep checking only if the base Decl is the same.
9157*67e74705SXin Li DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9158*67e74705SXin Li if (!DRE || DRE->getDecl() != OrigDecl)
9159*67e74705SXin Li return false;
9160*67e74705SXin Li
9161*67e74705SXin Li // A reference field can be bound to an unininitialized field.
9162*67e74705SXin Li if (CheckReference && !ReferenceField)
9163*67e74705SXin Li return true;
9164*67e74705SXin Li
9165*67e74705SXin Li // Convert FieldDecls to their index number.
9166*67e74705SXin Li llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9167*67e74705SXin Li for (const FieldDecl *I : llvm::reverse(Fields))
9168*67e74705SXin Li UsedFieldIndex.push_back(I->getFieldIndex());
9169*67e74705SXin Li
9170*67e74705SXin Li // See if a warning is needed by checking the first difference in index
9171*67e74705SXin Li // numbers. If field being used has index less than the field being
9172*67e74705SXin Li // initialized, then the use is safe.
9173*67e74705SXin Li for (auto UsedIter = UsedFieldIndex.begin(),
9174*67e74705SXin Li UsedEnd = UsedFieldIndex.end(),
9175*67e74705SXin Li OrigIter = InitFieldIndex.begin(),
9176*67e74705SXin Li OrigEnd = InitFieldIndex.end();
9177*67e74705SXin Li UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9178*67e74705SXin Li if (*UsedIter < *OrigIter)
9179*67e74705SXin Li return true;
9180*67e74705SXin Li if (*UsedIter > *OrigIter)
9181*67e74705SXin Li break;
9182*67e74705SXin Li }
9183*67e74705SXin Li
9184*67e74705SXin Li // TODO: Add a different warning which will print the field names.
9185*67e74705SXin Li HandleDeclRefExpr(DRE);
9186*67e74705SXin Li return true;
9187*67e74705SXin Li }
9188*67e74705SXin Li
9189*67e74705SXin Li // For most expressions, the cast is directly above the DeclRefExpr.
9190*67e74705SXin Li // For conditional operators, the cast can be outside the conditional
9191*67e74705SXin Li // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)9192*67e74705SXin Li void HandleValue(Expr *E) {
9193*67e74705SXin Li E = E->IgnoreParens();
9194*67e74705SXin Li if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9195*67e74705SXin Li HandleDeclRefExpr(DRE);
9196*67e74705SXin Li return;
9197*67e74705SXin Li }
9198*67e74705SXin Li
9199*67e74705SXin Li if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9200*67e74705SXin Li Visit(CO->getCond());
9201*67e74705SXin Li HandleValue(CO->getTrueExpr());
9202*67e74705SXin Li HandleValue(CO->getFalseExpr());
9203*67e74705SXin Li return;
9204*67e74705SXin Li }
9205*67e74705SXin Li
9206*67e74705SXin Li if (BinaryConditionalOperator *BCO =
9207*67e74705SXin Li dyn_cast<BinaryConditionalOperator>(E)) {
9208*67e74705SXin Li Visit(BCO->getCond());
9209*67e74705SXin Li HandleValue(BCO->getFalseExpr());
9210*67e74705SXin Li return;
9211*67e74705SXin Li }
9212*67e74705SXin Li
9213*67e74705SXin Li if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9214*67e74705SXin Li HandleValue(OVE->getSourceExpr());
9215*67e74705SXin Li return;
9216*67e74705SXin Li }
9217*67e74705SXin Li
9218*67e74705SXin Li if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9219*67e74705SXin Li if (BO->getOpcode() == BO_Comma) {
9220*67e74705SXin Li Visit(BO->getLHS());
9221*67e74705SXin Li HandleValue(BO->getRHS());
9222*67e74705SXin Li return;
9223*67e74705SXin Li }
9224*67e74705SXin Li }
9225*67e74705SXin Li
9226*67e74705SXin Li if (isa<MemberExpr>(E)) {
9227*67e74705SXin Li if (isInitList) {
9228*67e74705SXin Li if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9229*67e74705SXin Li false /*CheckReference*/))
9230*67e74705SXin Li return;
9231*67e74705SXin Li }
9232*67e74705SXin Li
9233*67e74705SXin Li Expr *Base = E->IgnoreParenImpCasts();
9234*67e74705SXin Li while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9235*67e74705SXin Li // Check for static member variables and don't warn on them.
9236*67e74705SXin Li if (!isa<FieldDecl>(ME->getMemberDecl()))
9237*67e74705SXin Li return;
9238*67e74705SXin Li Base = ME->getBase()->IgnoreParenImpCasts();
9239*67e74705SXin Li }
9240*67e74705SXin Li if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9241*67e74705SXin Li HandleDeclRefExpr(DRE);
9242*67e74705SXin Li return;
9243*67e74705SXin Li }
9244*67e74705SXin Li
9245*67e74705SXin Li Visit(E);
9246*67e74705SXin Li }
9247*67e74705SXin Li
9248*67e74705SXin Li // Reference types not handled in HandleValue are handled here since all
9249*67e74705SXin Li // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)9250*67e74705SXin Li void VisitDeclRefExpr(DeclRefExpr *E) {
9251*67e74705SXin Li if (isReferenceType)
9252*67e74705SXin Li HandleDeclRefExpr(E);
9253*67e74705SXin Li }
9254*67e74705SXin Li
VisitImplicitCastExpr(ImplicitCastExpr * E)9255*67e74705SXin Li void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9256*67e74705SXin Li if (E->getCastKind() == CK_LValueToRValue) {
9257*67e74705SXin Li HandleValue(E->getSubExpr());
9258*67e74705SXin Li return;
9259*67e74705SXin Li }
9260*67e74705SXin Li
9261*67e74705SXin Li Inherited::VisitImplicitCastExpr(E);
9262*67e74705SXin Li }
9263*67e74705SXin Li
VisitMemberExpr(MemberExpr * E)9264*67e74705SXin Li void VisitMemberExpr(MemberExpr *E) {
9265*67e74705SXin Li if (isInitList) {
9266*67e74705SXin Li if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9267*67e74705SXin Li return;
9268*67e74705SXin Li }
9269*67e74705SXin Li
9270*67e74705SXin Li // Don't warn on arrays since they can be treated as pointers.
9271*67e74705SXin Li if (E->getType()->canDecayToPointerType()) return;
9272*67e74705SXin Li
9273*67e74705SXin Li // Warn when a non-static method call is followed by non-static member
9274*67e74705SXin Li // field accesses, which is followed by a DeclRefExpr.
9275*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9276*67e74705SXin Li bool Warn = (MD && !MD->isStatic());
9277*67e74705SXin Li Expr *Base = E->getBase()->IgnoreParenImpCasts();
9278*67e74705SXin Li while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9279*67e74705SXin Li if (!isa<FieldDecl>(ME->getMemberDecl()))
9280*67e74705SXin Li Warn = false;
9281*67e74705SXin Li Base = ME->getBase()->IgnoreParenImpCasts();
9282*67e74705SXin Li }
9283*67e74705SXin Li
9284*67e74705SXin Li if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9285*67e74705SXin Li if (Warn)
9286*67e74705SXin Li HandleDeclRefExpr(DRE);
9287*67e74705SXin Li return;
9288*67e74705SXin Li }
9289*67e74705SXin Li
9290*67e74705SXin Li // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9291*67e74705SXin Li // Visit that expression.
9292*67e74705SXin Li Visit(Base);
9293*67e74705SXin Li }
9294*67e74705SXin Li
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)9295*67e74705SXin Li void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9296*67e74705SXin Li Expr *Callee = E->getCallee();
9297*67e74705SXin Li
9298*67e74705SXin Li if (isa<UnresolvedLookupExpr>(Callee))
9299*67e74705SXin Li return Inherited::VisitCXXOperatorCallExpr(E);
9300*67e74705SXin Li
9301*67e74705SXin Li Visit(Callee);
9302*67e74705SXin Li for (auto Arg: E->arguments())
9303*67e74705SXin Li HandleValue(Arg->IgnoreParenImpCasts());
9304*67e74705SXin Li }
9305*67e74705SXin Li
VisitUnaryOperator(UnaryOperator * E)9306*67e74705SXin Li void VisitUnaryOperator(UnaryOperator *E) {
9307*67e74705SXin Li // For POD record types, addresses of its own members are well-defined.
9308*67e74705SXin Li if (E->getOpcode() == UO_AddrOf && isRecordType &&
9309*67e74705SXin Li isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9310*67e74705SXin Li if (!isPODType)
9311*67e74705SXin Li HandleValue(E->getSubExpr());
9312*67e74705SXin Li return;
9313*67e74705SXin Li }
9314*67e74705SXin Li
9315*67e74705SXin Li if (E->isIncrementDecrementOp()) {
9316*67e74705SXin Li HandleValue(E->getSubExpr());
9317*67e74705SXin Li return;
9318*67e74705SXin Li }
9319*67e74705SXin Li
9320*67e74705SXin Li Inherited::VisitUnaryOperator(E);
9321*67e74705SXin Li }
9322*67e74705SXin Li
VisitObjCMessageExpr(ObjCMessageExpr * E)9323*67e74705SXin Li void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9324*67e74705SXin Li
VisitCXXConstructExpr(CXXConstructExpr * E)9325*67e74705SXin Li void VisitCXXConstructExpr(CXXConstructExpr *E) {
9326*67e74705SXin Li if (E->getConstructor()->isCopyConstructor()) {
9327*67e74705SXin Li Expr *ArgExpr = E->getArg(0);
9328*67e74705SXin Li if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9329*67e74705SXin Li if (ILE->getNumInits() == 1)
9330*67e74705SXin Li ArgExpr = ILE->getInit(0);
9331*67e74705SXin Li if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9332*67e74705SXin Li if (ICE->getCastKind() == CK_NoOp)
9333*67e74705SXin Li ArgExpr = ICE->getSubExpr();
9334*67e74705SXin Li HandleValue(ArgExpr);
9335*67e74705SXin Li return;
9336*67e74705SXin Li }
9337*67e74705SXin Li Inherited::VisitCXXConstructExpr(E);
9338*67e74705SXin Li }
9339*67e74705SXin Li
VisitCallExpr(CallExpr * E)9340*67e74705SXin Li void VisitCallExpr(CallExpr *E) {
9341*67e74705SXin Li // Treat std::move as a use.
9342*67e74705SXin Li if (E->getNumArgs() == 1) {
9343*67e74705SXin Li if (FunctionDecl *FD = E->getDirectCallee()) {
9344*67e74705SXin Li if (FD->isInStdNamespace() && FD->getIdentifier() &&
9345*67e74705SXin Li FD->getIdentifier()->isStr("move")) {
9346*67e74705SXin Li HandleValue(E->getArg(0));
9347*67e74705SXin Li return;
9348*67e74705SXin Li }
9349*67e74705SXin Li }
9350*67e74705SXin Li }
9351*67e74705SXin Li
9352*67e74705SXin Li Inherited::VisitCallExpr(E);
9353*67e74705SXin Li }
9354*67e74705SXin Li
VisitBinaryOperator(BinaryOperator * E)9355*67e74705SXin Li void VisitBinaryOperator(BinaryOperator *E) {
9356*67e74705SXin Li if (E->isCompoundAssignmentOp()) {
9357*67e74705SXin Li HandleValue(E->getLHS());
9358*67e74705SXin Li Visit(E->getRHS());
9359*67e74705SXin Li return;
9360*67e74705SXin Li }
9361*67e74705SXin Li
9362*67e74705SXin Li Inherited::VisitBinaryOperator(E);
9363*67e74705SXin Li }
9364*67e74705SXin Li
9365*67e74705SXin Li // A custom visitor for BinaryConditionalOperator is needed because the
9366*67e74705SXin Li // regular visitor would check the condition and true expression separately
9367*67e74705SXin Li // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)9368*67e74705SXin Li void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9369*67e74705SXin Li Visit(E->getCond());
9370*67e74705SXin Li Visit(E->getFalseExpr());
9371*67e74705SXin Li }
9372*67e74705SXin Li
HandleDeclRefExpr(DeclRefExpr * DRE)9373*67e74705SXin Li void HandleDeclRefExpr(DeclRefExpr *DRE) {
9374*67e74705SXin Li Decl* ReferenceDecl = DRE->getDecl();
9375*67e74705SXin Li if (OrigDecl != ReferenceDecl) return;
9376*67e74705SXin Li unsigned diag;
9377*67e74705SXin Li if (isReferenceType) {
9378*67e74705SXin Li diag = diag::warn_uninit_self_reference_in_reference_init;
9379*67e74705SXin Li } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9380*67e74705SXin Li diag = diag::warn_static_self_reference_in_init;
9381*67e74705SXin Li } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9382*67e74705SXin Li isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9383*67e74705SXin Li DRE->getDecl()->getType()->isRecordType()) {
9384*67e74705SXin Li diag = diag::warn_uninit_self_reference_in_init;
9385*67e74705SXin Li } else {
9386*67e74705SXin Li // Local variables will be handled by the CFG analysis.
9387*67e74705SXin Li return;
9388*67e74705SXin Li }
9389*67e74705SXin Li
9390*67e74705SXin Li S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9391*67e74705SXin Li S.PDiag(diag)
9392*67e74705SXin Li << DRE->getNameInfo().getName()
9393*67e74705SXin Li << OrigDecl->getLocation()
9394*67e74705SXin Li << DRE->getSourceRange());
9395*67e74705SXin Li }
9396*67e74705SXin Li };
9397*67e74705SXin Li
9398*67e74705SXin Li /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)9399*67e74705SXin Li static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9400*67e74705SXin Li bool DirectInit) {
9401*67e74705SXin Li // Parameters arguments are occassionially constructed with itself,
9402*67e74705SXin Li // for instance, in recursive functions. Skip them.
9403*67e74705SXin Li if (isa<ParmVarDecl>(OrigDecl))
9404*67e74705SXin Li return;
9405*67e74705SXin Li
9406*67e74705SXin Li E = E->IgnoreParens();
9407*67e74705SXin Li
9408*67e74705SXin Li // Skip checking T a = a where T is not a record or reference type.
9409*67e74705SXin Li // Doing so is a way to silence uninitialized warnings.
9410*67e74705SXin Li if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9411*67e74705SXin Li if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9412*67e74705SXin Li if (ICE->getCastKind() == CK_LValueToRValue)
9413*67e74705SXin Li if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9414*67e74705SXin Li if (DRE->getDecl() == OrigDecl)
9415*67e74705SXin Li return;
9416*67e74705SXin Li
9417*67e74705SXin Li SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9418*67e74705SXin Li }
9419*67e74705SXin Li } // end anonymous namespace
9420*67e74705SXin Li
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)9421*67e74705SXin Li QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9422*67e74705SXin Li DeclarationName Name, QualType Type,
9423*67e74705SXin Li TypeSourceInfo *TSI,
9424*67e74705SXin Li SourceRange Range, bool DirectInit,
9425*67e74705SXin Li Expr *Init) {
9426*67e74705SXin Li bool IsInitCapture = !VDecl;
9427*67e74705SXin Li assert((!VDecl || !VDecl->isInitCapture()) &&
9428*67e74705SXin Li "init captures are expected to be deduced prior to initialization");
9429*67e74705SXin Li
9430*67e74705SXin Li ArrayRef<Expr *> DeduceInits = Init;
9431*67e74705SXin Li if (DirectInit) {
9432*67e74705SXin Li if (auto *PL = dyn_cast<ParenListExpr>(Init))
9433*67e74705SXin Li DeduceInits = PL->exprs();
9434*67e74705SXin Li else if (auto *IL = dyn_cast<InitListExpr>(Init))
9435*67e74705SXin Li DeduceInits = IL->inits();
9436*67e74705SXin Li }
9437*67e74705SXin Li
9438*67e74705SXin Li // Deduction only works if we have exactly one source expression.
9439*67e74705SXin Li if (DeduceInits.empty()) {
9440*67e74705SXin Li // It isn't possible to write this directly, but it is possible to
9441*67e74705SXin Li // end up in this situation with "auto x(some_pack...);"
9442*67e74705SXin Li Diag(Init->getLocStart(), IsInitCapture
9443*67e74705SXin Li ? diag::err_init_capture_no_expression
9444*67e74705SXin Li : diag::err_auto_var_init_no_expression)
9445*67e74705SXin Li << Name << Type << Range;
9446*67e74705SXin Li return QualType();
9447*67e74705SXin Li }
9448*67e74705SXin Li
9449*67e74705SXin Li if (DeduceInits.size() > 1) {
9450*67e74705SXin Li Diag(DeduceInits[1]->getLocStart(),
9451*67e74705SXin Li IsInitCapture ? diag::err_init_capture_multiple_expressions
9452*67e74705SXin Li : diag::err_auto_var_init_multiple_expressions)
9453*67e74705SXin Li << Name << Type << Range;
9454*67e74705SXin Li return QualType();
9455*67e74705SXin Li }
9456*67e74705SXin Li
9457*67e74705SXin Li Expr *DeduceInit = DeduceInits[0];
9458*67e74705SXin Li if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9459*67e74705SXin Li Diag(Init->getLocStart(), IsInitCapture
9460*67e74705SXin Li ? diag::err_init_capture_paren_braces
9461*67e74705SXin Li : diag::err_auto_var_init_paren_braces)
9462*67e74705SXin Li << isa<InitListExpr>(Init) << Name << Type << Range;
9463*67e74705SXin Li return QualType();
9464*67e74705SXin Li }
9465*67e74705SXin Li
9466*67e74705SXin Li // Expressions default to 'id' when we're in a debugger.
9467*67e74705SXin Li bool DefaultedAnyToId = false;
9468*67e74705SXin Li if (getLangOpts().DebuggerCastResultToId &&
9469*67e74705SXin Li Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9470*67e74705SXin Li ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9471*67e74705SXin Li if (Result.isInvalid()) {
9472*67e74705SXin Li return QualType();
9473*67e74705SXin Li }
9474*67e74705SXin Li Init = Result.get();
9475*67e74705SXin Li DefaultedAnyToId = true;
9476*67e74705SXin Li }
9477*67e74705SXin Li
9478*67e74705SXin Li QualType DeducedType;
9479*67e74705SXin Li if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9480*67e74705SXin Li if (!IsInitCapture)
9481*67e74705SXin Li DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9482*67e74705SXin Li else if (isa<InitListExpr>(Init))
9483*67e74705SXin Li Diag(Range.getBegin(),
9484*67e74705SXin Li diag::err_init_capture_deduction_failure_from_init_list)
9485*67e74705SXin Li << Name
9486*67e74705SXin Li << (DeduceInit->getType().isNull() ? TSI->getType()
9487*67e74705SXin Li : DeduceInit->getType())
9488*67e74705SXin Li << DeduceInit->getSourceRange();
9489*67e74705SXin Li else
9490*67e74705SXin Li Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9491*67e74705SXin Li << Name << TSI->getType()
9492*67e74705SXin Li << (DeduceInit->getType().isNull() ? TSI->getType()
9493*67e74705SXin Li : DeduceInit->getType())
9494*67e74705SXin Li << DeduceInit->getSourceRange();
9495*67e74705SXin Li }
9496*67e74705SXin Li
9497*67e74705SXin Li // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9498*67e74705SXin Li // 'id' instead of a specific object type prevents most of our usual
9499*67e74705SXin Li // checks.
9500*67e74705SXin Li // We only want to warn outside of template instantiations, though:
9501*67e74705SXin Li // inside a template, the 'id' could have come from a parameter.
9502*67e74705SXin Li if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9503*67e74705SXin Li !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9504*67e74705SXin Li SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9505*67e74705SXin Li Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9506*67e74705SXin Li }
9507*67e74705SXin Li
9508*67e74705SXin Li return DeducedType;
9509*67e74705SXin Li }
9510*67e74705SXin Li
9511*67e74705SXin Li /// AddInitializerToDecl - Adds the initializer Init to the
9512*67e74705SXin Li /// declaration dcl. If DirectInit is true, this is C++ direct
9513*67e74705SXin Li /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit,bool TypeMayContainAuto)9514*67e74705SXin Li void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9515*67e74705SXin Li bool DirectInit, bool TypeMayContainAuto) {
9516*67e74705SXin Li // If there is no declaration, there was an error parsing it. Just ignore
9517*67e74705SXin Li // the initializer.
9518*67e74705SXin Li if (!RealDecl || RealDecl->isInvalidDecl()) {
9519*67e74705SXin Li CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9520*67e74705SXin Li return;
9521*67e74705SXin Li }
9522*67e74705SXin Li
9523*67e74705SXin Li if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9524*67e74705SXin Li // Pure-specifiers are handled in ActOnPureSpecifier.
9525*67e74705SXin Li Diag(Method->getLocation(), diag::err_member_function_initialization)
9526*67e74705SXin Li << Method->getDeclName() << Init->getSourceRange();
9527*67e74705SXin Li Method->setInvalidDecl();
9528*67e74705SXin Li return;
9529*67e74705SXin Li }
9530*67e74705SXin Li
9531*67e74705SXin Li VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9532*67e74705SXin Li if (!VDecl) {
9533*67e74705SXin Li assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9534*67e74705SXin Li Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9535*67e74705SXin Li RealDecl->setInvalidDecl();
9536*67e74705SXin Li return;
9537*67e74705SXin Li }
9538*67e74705SXin Li
9539*67e74705SXin Li // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9540*67e74705SXin Li if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9541*67e74705SXin Li // Attempt typo correction early so that the type of the init expression can
9542*67e74705SXin Li // be deduced based on the chosen correction if the original init contains a
9543*67e74705SXin Li // TypoExpr.
9544*67e74705SXin Li ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9545*67e74705SXin Li if (!Res.isUsable()) {
9546*67e74705SXin Li RealDecl->setInvalidDecl();
9547*67e74705SXin Li return;
9548*67e74705SXin Li }
9549*67e74705SXin Li Init = Res.get();
9550*67e74705SXin Li
9551*67e74705SXin Li QualType DeducedType = deduceVarTypeFromInitializer(
9552*67e74705SXin Li VDecl, VDecl->getDeclName(), VDecl->getType(),
9553*67e74705SXin Li VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9554*67e74705SXin Li if (DeducedType.isNull()) {
9555*67e74705SXin Li RealDecl->setInvalidDecl();
9556*67e74705SXin Li return;
9557*67e74705SXin Li }
9558*67e74705SXin Li
9559*67e74705SXin Li VDecl->setType(DeducedType);
9560*67e74705SXin Li assert(VDecl->isLinkageValid());
9561*67e74705SXin Li
9562*67e74705SXin Li // In ARC, infer lifetime.
9563*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9564*67e74705SXin Li VDecl->setInvalidDecl();
9565*67e74705SXin Li
9566*67e74705SXin Li // If this is a redeclaration, check that the type we just deduced matches
9567*67e74705SXin Li // the previously declared type.
9568*67e74705SXin Li if (VarDecl *Old = VDecl->getPreviousDecl()) {
9569*67e74705SXin Li // We never need to merge the type, because we cannot form an incomplete
9570*67e74705SXin Li // array of auto, nor deduce such a type.
9571*67e74705SXin Li MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9572*67e74705SXin Li }
9573*67e74705SXin Li
9574*67e74705SXin Li // Check the deduced type is valid for a variable declaration.
9575*67e74705SXin Li CheckVariableDeclarationType(VDecl);
9576*67e74705SXin Li if (VDecl->isInvalidDecl())
9577*67e74705SXin Li return;
9578*67e74705SXin Li }
9579*67e74705SXin Li
9580*67e74705SXin Li // dllimport cannot be used on variable definitions.
9581*67e74705SXin Li if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9582*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9583*67e74705SXin Li VDecl->setInvalidDecl();
9584*67e74705SXin Li return;
9585*67e74705SXin Li }
9586*67e74705SXin Li
9587*67e74705SXin Li if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9588*67e74705SXin Li // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9589*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9590*67e74705SXin Li VDecl->setInvalidDecl();
9591*67e74705SXin Li return;
9592*67e74705SXin Li }
9593*67e74705SXin Li
9594*67e74705SXin Li if (!VDecl->getType()->isDependentType()) {
9595*67e74705SXin Li // A definition must end up with a complete type, which means it must be
9596*67e74705SXin Li // complete with the restriction that an array type might be completed by
9597*67e74705SXin Li // the initializer; note that later code assumes this restriction.
9598*67e74705SXin Li QualType BaseDeclType = VDecl->getType();
9599*67e74705SXin Li if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9600*67e74705SXin Li BaseDeclType = Array->getElementType();
9601*67e74705SXin Li if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9602*67e74705SXin Li diag::err_typecheck_decl_incomplete_type)) {
9603*67e74705SXin Li RealDecl->setInvalidDecl();
9604*67e74705SXin Li return;
9605*67e74705SXin Li }
9606*67e74705SXin Li
9607*67e74705SXin Li // The variable can not have an abstract class type.
9608*67e74705SXin Li if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9609*67e74705SXin Li diag::err_abstract_type_in_decl,
9610*67e74705SXin Li AbstractVariableType))
9611*67e74705SXin Li VDecl->setInvalidDecl();
9612*67e74705SXin Li }
9613*67e74705SXin Li
9614*67e74705SXin Li VarDecl *Def;
9615*67e74705SXin Li if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9616*67e74705SXin Li NamedDecl *Hidden = nullptr;
9617*67e74705SXin Li if (!hasVisibleDefinition(Def, &Hidden) &&
9618*67e74705SXin Li (VDecl->getFormalLinkage() == InternalLinkage ||
9619*67e74705SXin Li VDecl->getDescribedVarTemplate() ||
9620*67e74705SXin Li VDecl->getNumTemplateParameterLists() ||
9621*67e74705SXin Li VDecl->getDeclContext()->isDependentContext())) {
9622*67e74705SXin Li // The previous definition is hidden, and multiple definitions are
9623*67e74705SXin Li // permitted (in separate TUs). Form another definition of it.
9624*67e74705SXin Li } else {
9625*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_redefinition)
9626*67e74705SXin Li << VDecl->getDeclName();
9627*67e74705SXin Li Diag(Def->getLocation(), diag::note_previous_definition);
9628*67e74705SXin Li VDecl->setInvalidDecl();
9629*67e74705SXin Li return;
9630*67e74705SXin Li }
9631*67e74705SXin Li }
9632*67e74705SXin Li
9633*67e74705SXin Li if (getLangOpts().CPlusPlus) {
9634*67e74705SXin Li // C++ [class.static.data]p4
9635*67e74705SXin Li // If a static data member is of const integral or const
9636*67e74705SXin Li // enumeration type, its declaration in the class definition can
9637*67e74705SXin Li // specify a constant-initializer which shall be an integral
9638*67e74705SXin Li // constant expression (5.19). In that case, the member can appear
9639*67e74705SXin Li // in integral constant expressions. The member shall still be
9640*67e74705SXin Li // defined in a namespace scope if it is used in the program and the
9641*67e74705SXin Li // namespace scope definition shall not contain an initializer.
9642*67e74705SXin Li //
9643*67e74705SXin Li // We already performed a redefinition check above, but for static
9644*67e74705SXin Li // data members we also need to check whether there was an in-class
9645*67e74705SXin Li // declaration with an initializer.
9646*67e74705SXin Li if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9647*67e74705SXin Li Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9648*67e74705SXin Li << VDecl->getDeclName();
9649*67e74705SXin Li Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9650*67e74705SXin Li diag::note_previous_initializer)
9651*67e74705SXin Li << 0;
9652*67e74705SXin Li return;
9653*67e74705SXin Li }
9654*67e74705SXin Li
9655*67e74705SXin Li if (VDecl->hasLocalStorage())
9656*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
9657*67e74705SXin Li
9658*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9659*67e74705SXin Li VDecl->setInvalidDecl();
9660*67e74705SXin Li return;
9661*67e74705SXin Li }
9662*67e74705SXin Li }
9663*67e74705SXin Li
9664*67e74705SXin Li // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9665*67e74705SXin Li // a kernel function cannot be initialized."
9666*67e74705SXin Li if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9667*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_local_cant_init);
9668*67e74705SXin Li VDecl->setInvalidDecl();
9669*67e74705SXin Li return;
9670*67e74705SXin Li }
9671*67e74705SXin Li
9672*67e74705SXin Li // Get the decls type and save a reference for later, since
9673*67e74705SXin Li // CheckInitializerTypes may change it.
9674*67e74705SXin Li QualType DclT = VDecl->getType(), SavT = DclT;
9675*67e74705SXin Li
9676*67e74705SXin Li // Expressions default to 'id' when we're in a debugger
9677*67e74705SXin Li // and we are assigning it to a variable of Objective-C pointer type.
9678*67e74705SXin Li if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9679*67e74705SXin Li Init->getType() == Context.UnknownAnyTy) {
9680*67e74705SXin Li ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9681*67e74705SXin Li if (Result.isInvalid()) {
9682*67e74705SXin Li VDecl->setInvalidDecl();
9683*67e74705SXin Li return;
9684*67e74705SXin Li }
9685*67e74705SXin Li Init = Result.get();
9686*67e74705SXin Li }
9687*67e74705SXin Li
9688*67e74705SXin Li // Perform the initialization.
9689*67e74705SXin Li ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9690*67e74705SXin Li if (!VDecl->isInvalidDecl()) {
9691*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9692*67e74705SXin Li InitializationKind Kind =
9693*67e74705SXin Li DirectInit
9694*67e74705SXin Li ? CXXDirectInit
9695*67e74705SXin Li ? InitializationKind::CreateDirect(VDecl->getLocation(),
9696*67e74705SXin Li Init->getLocStart(),
9697*67e74705SXin Li Init->getLocEnd())
9698*67e74705SXin Li : InitializationKind::CreateDirectList(VDecl->getLocation())
9699*67e74705SXin Li : InitializationKind::CreateCopy(VDecl->getLocation(),
9700*67e74705SXin Li Init->getLocStart());
9701*67e74705SXin Li
9702*67e74705SXin Li MultiExprArg Args = Init;
9703*67e74705SXin Li if (CXXDirectInit)
9704*67e74705SXin Li Args = MultiExprArg(CXXDirectInit->getExprs(),
9705*67e74705SXin Li CXXDirectInit->getNumExprs());
9706*67e74705SXin Li
9707*67e74705SXin Li // Try to correct any TypoExprs in the initialization arguments.
9708*67e74705SXin Li for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9709*67e74705SXin Li ExprResult Res = CorrectDelayedTyposInExpr(
9710*67e74705SXin Li Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9711*67e74705SXin Li InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9712*67e74705SXin Li return Init.Failed() ? ExprError() : E;
9713*67e74705SXin Li });
9714*67e74705SXin Li if (Res.isInvalid()) {
9715*67e74705SXin Li VDecl->setInvalidDecl();
9716*67e74705SXin Li } else if (Res.get() != Args[Idx]) {
9717*67e74705SXin Li Args[Idx] = Res.get();
9718*67e74705SXin Li }
9719*67e74705SXin Li }
9720*67e74705SXin Li if (VDecl->isInvalidDecl())
9721*67e74705SXin Li return;
9722*67e74705SXin Li
9723*67e74705SXin Li InitializationSequence InitSeq(*this, Entity, Kind, Args,
9724*67e74705SXin Li /*TopLevelOfInitList=*/false,
9725*67e74705SXin Li /*TreatUnavailableAsInvalid=*/false);
9726*67e74705SXin Li ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9727*67e74705SXin Li if (Result.isInvalid()) {
9728*67e74705SXin Li VDecl->setInvalidDecl();
9729*67e74705SXin Li return;
9730*67e74705SXin Li }
9731*67e74705SXin Li
9732*67e74705SXin Li Init = Result.getAs<Expr>();
9733*67e74705SXin Li }
9734*67e74705SXin Li
9735*67e74705SXin Li // Check for self-references within variable initializers.
9736*67e74705SXin Li // Variables declared within a function/method body (except for references)
9737*67e74705SXin Li // are handled by a dataflow analysis.
9738*67e74705SXin Li if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9739*67e74705SXin Li VDecl->getType()->isReferenceType()) {
9740*67e74705SXin Li CheckSelfReference(*this, RealDecl, Init, DirectInit);
9741*67e74705SXin Li }
9742*67e74705SXin Li
9743*67e74705SXin Li // If the type changed, it means we had an incomplete type that was
9744*67e74705SXin Li // completed by the initializer. For example:
9745*67e74705SXin Li // int ary[] = { 1, 3, 5 };
9746*67e74705SXin Li // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9747*67e74705SXin Li if (!VDecl->isInvalidDecl() && (DclT != SavT))
9748*67e74705SXin Li VDecl->setType(DclT);
9749*67e74705SXin Li
9750*67e74705SXin Li if (!VDecl->isInvalidDecl()) {
9751*67e74705SXin Li checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9752*67e74705SXin Li
9753*67e74705SXin Li if (VDecl->hasAttr<BlocksAttr>())
9754*67e74705SXin Li checkRetainCycles(VDecl, Init);
9755*67e74705SXin Li
9756*67e74705SXin Li // It is safe to assign a weak reference into a strong variable.
9757*67e74705SXin Li // Although this code can still have problems:
9758*67e74705SXin Li // id x = self.weakProp;
9759*67e74705SXin Li // id y = self.weakProp;
9760*67e74705SXin Li // we do not warn to warn spuriously when 'x' and 'y' are on separate
9761*67e74705SXin Li // paths through the function. This should be revisited if
9762*67e74705SXin Li // -Wrepeated-use-of-weak is made flow-sensitive.
9763*67e74705SXin Li if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9764*67e74705SXin Li !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9765*67e74705SXin Li Init->getLocStart()))
9766*67e74705SXin Li getCurFunction()->markSafeWeakUse(Init);
9767*67e74705SXin Li }
9768*67e74705SXin Li
9769*67e74705SXin Li // The initialization is usually a full-expression.
9770*67e74705SXin Li //
9771*67e74705SXin Li // FIXME: If this is a braced initialization of an aggregate, it is not
9772*67e74705SXin Li // an expression, and each individual field initializer is a separate
9773*67e74705SXin Li // full-expression. For instance, in:
9774*67e74705SXin Li //
9775*67e74705SXin Li // struct Temp { ~Temp(); };
9776*67e74705SXin Li // struct S { S(Temp); };
9777*67e74705SXin Li // struct T { S a, b; } t = { Temp(), Temp() }
9778*67e74705SXin Li //
9779*67e74705SXin Li // we should destroy the first Temp before constructing the second.
9780*67e74705SXin Li ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9781*67e74705SXin Li false,
9782*67e74705SXin Li VDecl->isConstexpr());
9783*67e74705SXin Li if (Result.isInvalid()) {
9784*67e74705SXin Li VDecl->setInvalidDecl();
9785*67e74705SXin Li return;
9786*67e74705SXin Li }
9787*67e74705SXin Li Init = Result.get();
9788*67e74705SXin Li
9789*67e74705SXin Li // Attach the initializer to the decl.
9790*67e74705SXin Li VDecl->setInit(Init);
9791*67e74705SXin Li
9792*67e74705SXin Li if (VDecl->isLocalVarDecl()) {
9793*67e74705SXin Li // C99 6.7.8p4: All the expressions in an initializer for an object that has
9794*67e74705SXin Li // static storage duration shall be constant expressions or string literals.
9795*67e74705SXin Li // C++ does not have this restriction.
9796*67e74705SXin Li if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9797*67e74705SXin Li const Expr *Culprit;
9798*67e74705SXin Li if (VDecl->getStorageClass() == SC_Static)
9799*67e74705SXin Li CheckForConstantInitializer(Init, DclT);
9800*67e74705SXin Li // C89 is stricter than C99 for non-static aggregate types.
9801*67e74705SXin Li // C89 6.5.7p3: All the expressions [...] in an initializer list
9802*67e74705SXin Li // for an object that has aggregate or union type shall be
9803*67e74705SXin Li // constant expressions.
9804*67e74705SXin Li else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9805*67e74705SXin Li isa<InitListExpr>(Init) &&
9806*67e74705SXin Li !Init->isConstantInitializer(Context, false, &Culprit))
9807*67e74705SXin Li Diag(Culprit->getExprLoc(),
9808*67e74705SXin Li diag::ext_aggregate_init_not_constant)
9809*67e74705SXin Li << Culprit->getSourceRange();
9810*67e74705SXin Li }
9811*67e74705SXin Li } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
9812*67e74705SXin Li VDecl->getLexicalDeclContext()->isRecord()) {
9813*67e74705SXin Li // This is an in-class initialization for a static data member, e.g.,
9814*67e74705SXin Li //
9815*67e74705SXin Li // struct S {
9816*67e74705SXin Li // static const int value = 17;
9817*67e74705SXin Li // };
9818*67e74705SXin Li
9819*67e74705SXin Li // C++ [class.mem]p4:
9820*67e74705SXin Li // A member-declarator can contain a constant-initializer only
9821*67e74705SXin Li // if it declares a static member (9.4) of const integral or
9822*67e74705SXin Li // const enumeration type, see 9.4.2.
9823*67e74705SXin Li //
9824*67e74705SXin Li // C++11 [class.static.data]p3:
9825*67e74705SXin Li // If a non-volatile non-inline const static data member is of integral
9826*67e74705SXin Li // or enumeration type, its declaration in the class definition can
9827*67e74705SXin Li // specify a brace-or-equal-initializer in which every initalizer-clause
9828*67e74705SXin Li // that is an assignment-expression is a constant expression. A static
9829*67e74705SXin Li // data member of literal type can be declared in the class definition
9830*67e74705SXin Li // with the constexpr specifier; if so, its declaration shall specify a
9831*67e74705SXin Li // brace-or-equal-initializer in which every initializer-clause that is
9832*67e74705SXin Li // an assignment-expression is a constant expression.
9833*67e74705SXin Li
9834*67e74705SXin Li // Do nothing on dependent types.
9835*67e74705SXin Li if (DclT->isDependentType()) {
9836*67e74705SXin Li
9837*67e74705SXin Li // Allow any 'static constexpr' members, whether or not they are of literal
9838*67e74705SXin Li // type. We separately check that every constexpr variable is of literal
9839*67e74705SXin Li // type.
9840*67e74705SXin Li } else if (VDecl->isConstexpr()) {
9841*67e74705SXin Li
9842*67e74705SXin Li // Require constness.
9843*67e74705SXin Li } else if (!DclT.isConstQualified()) {
9844*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9845*67e74705SXin Li << Init->getSourceRange();
9846*67e74705SXin Li VDecl->setInvalidDecl();
9847*67e74705SXin Li
9848*67e74705SXin Li // We allow integer constant expressions in all cases.
9849*67e74705SXin Li } else if (DclT->isIntegralOrEnumerationType()) {
9850*67e74705SXin Li // Check whether the expression is a constant expression.
9851*67e74705SXin Li SourceLocation Loc;
9852*67e74705SXin Li if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9853*67e74705SXin Li // In C++11, a non-constexpr const static data member with an
9854*67e74705SXin Li // in-class initializer cannot be volatile.
9855*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9856*67e74705SXin Li else if (Init->isValueDependent())
9857*67e74705SXin Li ; // Nothing to check.
9858*67e74705SXin Li else if (Init->isIntegerConstantExpr(Context, &Loc))
9859*67e74705SXin Li ; // Ok, it's an ICE!
9860*67e74705SXin Li else if (Init->isEvaluatable(Context)) {
9861*67e74705SXin Li // If we can constant fold the initializer through heroics, accept it,
9862*67e74705SXin Li // but report this as a use of an extension for -pedantic.
9863*67e74705SXin Li Diag(Loc, diag::ext_in_class_initializer_non_constant)
9864*67e74705SXin Li << Init->getSourceRange();
9865*67e74705SXin Li } else {
9866*67e74705SXin Li // Otherwise, this is some crazy unknown case. Report the issue at the
9867*67e74705SXin Li // location provided by the isIntegerConstantExpr failed check.
9868*67e74705SXin Li Diag(Loc, diag::err_in_class_initializer_non_constant)
9869*67e74705SXin Li << Init->getSourceRange();
9870*67e74705SXin Li VDecl->setInvalidDecl();
9871*67e74705SXin Li }
9872*67e74705SXin Li
9873*67e74705SXin Li // We allow foldable floating-point constants as an extension.
9874*67e74705SXin Li } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9875*67e74705SXin Li // In C++98, this is a GNU extension. In C++11, it is not, but we support
9876*67e74705SXin Li // it anyway and provide a fixit to add the 'constexpr'.
9877*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
9878*67e74705SXin Li Diag(VDecl->getLocation(),
9879*67e74705SXin Li diag::ext_in_class_initializer_float_type_cxx11)
9880*67e74705SXin Li << DclT << Init->getSourceRange();
9881*67e74705SXin Li Diag(VDecl->getLocStart(),
9882*67e74705SXin Li diag::note_in_class_initializer_float_type_cxx11)
9883*67e74705SXin Li << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9884*67e74705SXin Li } else {
9885*67e74705SXin Li Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9886*67e74705SXin Li << DclT << Init->getSourceRange();
9887*67e74705SXin Li
9888*67e74705SXin Li if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9889*67e74705SXin Li Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9890*67e74705SXin Li << Init->getSourceRange();
9891*67e74705SXin Li VDecl->setInvalidDecl();
9892*67e74705SXin Li }
9893*67e74705SXin Li }
9894*67e74705SXin Li
9895*67e74705SXin Li // Suggest adding 'constexpr' in C++11 for literal types.
9896*67e74705SXin Li } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9897*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9898*67e74705SXin Li << DclT << Init->getSourceRange()
9899*67e74705SXin Li << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9900*67e74705SXin Li VDecl->setConstexpr(true);
9901*67e74705SXin Li
9902*67e74705SXin Li } else {
9903*67e74705SXin Li Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9904*67e74705SXin Li << DclT << Init->getSourceRange();
9905*67e74705SXin Li VDecl->setInvalidDecl();
9906*67e74705SXin Li }
9907*67e74705SXin Li } else if (VDecl->isFileVarDecl()) {
9908*67e74705SXin Li if (VDecl->getStorageClass() == SC_Extern &&
9909*67e74705SXin Li (!getLangOpts().CPlusPlus ||
9910*67e74705SXin Li !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9911*67e74705SXin Li VDecl->isExternC())) &&
9912*67e74705SXin Li !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9913*67e74705SXin Li Diag(VDecl->getLocation(), diag::warn_extern_init);
9914*67e74705SXin Li
9915*67e74705SXin Li // C99 6.7.8p4. All file scoped initializers need to be constant.
9916*67e74705SXin Li if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9917*67e74705SXin Li CheckForConstantInitializer(Init, DclT);
9918*67e74705SXin Li }
9919*67e74705SXin Li
9920*67e74705SXin Li // We will represent direct-initialization similarly to copy-initialization:
9921*67e74705SXin Li // int x(1); -as-> int x = 1;
9922*67e74705SXin Li // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9923*67e74705SXin Li //
9924*67e74705SXin Li // Clients that want to distinguish between the two forms, can check for
9925*67e74705SXin Li // direct initializer using VarDecl::getInitStyle().
9926*67e74705SXin Li // A major benefit is that clients that don't particularly care about which
9927*67e74705SXin Li // exactly form was it (like the CodeGen) can handle both cases without
9928*67e74705SXin Li // special case code.
9929*67e74705SXin Li
9930*67e74705SXin Li // C++ 8.5p11:
9931*67e74705SXin Li // The form of initialization (using parentheses or '=') is generally
9932*67e74705SXin Li // insignificant, but does matter when the entity being initialized has a
9933*67e74705SXin Li // class type.
9934*67e74705SXin Li if (CXXDirectInit) {
9935*67e74705SXin Li assert(DirectInit && "Call-style initializer must be direct init.");
9936*67e74705SXin Li VDecl->setInitStyle(VarDecl::CallInit);
9937*67e74705SXin Li } else if (DirectInit) {
9938*67e74705SXin Li // This must be list-initialization. No other way is direct-initialization.
9939*67e74705SXin Li VDecl->setInitStyle(VarDecl::ListInit);
9940*67e74705SXin Li }
9941*67e74705SXin Li
9942*67e74705SXin Li CheckCompleteVariableDeclaration(VDecl);
9943*67e74705SXin Li }
9944*67e74705SXin Li
9945*67e74705SXin Li /// ActOnInitializerError - Given that there was an error parsing an
9946*67e74705SXin Li /// initializer for the given declaration, try to return to some form
9947*67e74705SXin Li /// of sanity.
ActOnInitializerError(Decl * D)9948*67e74705SXin Li void Sema::ActOnInitializerError(Decl *D) {
9949*67e74705SXin Li // Our main concern here is re-establishing invariants like "a
9950*67e74705SXin Li // variable's type is either dependent or complete".
9951*67e74705SXin Li if (!D || D->isInvalidDecl()) return;
9952*67e74705SXin Li
9953*67e74705SXin Li VarDecl *VD = dyn_cast<VarDecl>(D);
9954*67e74705SXin Li if (!VD) return;
9955*67e74705SXin Li
9956*67e74705SXin Li // Auto types are meaningless if we can't make sense of the initializer.
9957*67e74705SXin Li if (ParsingInitForAutoVars.count(D)) {
9958*67e74705SXin Li D->setInvalidDecl();
9959*67e74705SXin Li return;
9960*67e74705SXin Li }
9961*67e74705SXin Li
9962*67e74705SXin Li QualType Ty = VD->getType();
9963*67e74705SXin Li if (Ty->isDependentType()) return;
9964*67e74705SXin Li
9965*67e74705SXin Li // Require a complete type.
9966*67e74705SXin Li if (RequireCompleteType(VD->getLocation(),
9967*67e74705SXin Li Context.getBaseElementType(Ty),
9968*67e74705SXin Li diag::err_typecheck_decl_incomplete_type)) {
9969*67e74705SXin Li VD->setInvalidDecl();
9970*67e74705SXin Li return;
9971*67e74705SXin Li }
9972*67e74705SXin Li
9973*67e74705SXin Li // Require a non-abstract type.
9974*67e74705SXin Li if (RequireNonAbstractType(VD->getLocation(), Ty,
9975*67e74705SXin Li diag::err_abstract_type_in_decl,
9976*67e74705SXin Li AbstractVariableType)) {
9977*67e74705SXin Li VD->setInvalidDecl();
9978*67e74705SXin Li return;
9979*67e74705SXin Li }
9980*67e74705SXin Li
9981*67e74705SXin Li // Don't bother complaining about constructors or destructors,
9982*67e74705SXin Li // though.
9983*67e74705SXin Li }
9984*67e74705SXin Li
ActOnUninitializedDecl(Decl * RealDecl,bool TypeMayContainAuto)9985*67e74705SXin Li void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9986*67e74705SXin Li bool TypeMayContainAuto) {
9987*67e74705SXin Li // If there is no declaration, there was an error parsing it. Just ignore it.
9988*67e74705SXin Li if (!RealDecl)
9989*67e74705SXin Li return;
9990*67e74705SXin Li
9991*67e74705SXin Li if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9992*67e74705SXin Li QualType Type = Var->getType();
9993*67e74705SXin Li
9994*67e74705SXin Li // C++11 [dcl.spec.auto]p3
9995*67e74705SXin Li if (TypeMayContainAuto && Type->getContainedAutoType()) {
9996*67e74705SXin Li Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9997*67e74705SXin Li << Var->getDeclName() << Type;
9998*67e74705SXin Li Var->setInvalidDecl();
9999*67e74705SXin Li return;
10000*67e74705SXin Li }
10001*67e74705SXin Li
10002*67e74705SXin Li // C++11 [class.static.data]p3: A static data member can be declared with
10003*67e74705SXin Li // the constexpr specifier; if so, its declaration shall specify
10004*67e74705SXin Li // a brace-or-equal-initializer.
10005*67e74705SXin Li // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10006*67e74705SXin Li // the definition of a variable [...] or the declaration of a static data
10007*67e74705SXin Li // member.
10008*67e74705SXin Li if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
10009*67e74705SXin Li if (Var->isStaticDataMember()) {
10010*67e74705SXin Li // C++1z removes the relevant rule; the in-class declaration is always
10011*67e74705SXin Li // a definition there.
10012*67e74705SXin Li if (!getLangOpts().CPlusPlus1z) {
10013*67e74705SXin Li Diag(Var->getLocation(),
10014*67e74705SXin Li diag::err_constexpr_static_mem_var_requires_init)
10015*67e74705SXin Li << Var->getDeclName();
10016*67e74705SXin Li Var->setInvalidDecl();
10017*67e74705SXin Li return;
10018*67e74705SXin Li }
10019*67e74705SXin Li } else {
10020*67e74705SXin Li Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10021*67e74705SXin Li Var->setInvalidDecl();
10022*67e74705SXin Li return;
10023*67e74705SXin Li }
10024*67e74705SXin Li }
10025*67e74705SXin Li
10026*67e74705SXin Li // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
10027*67e74705SXin Li // definition having the concept specifier is called a variable concept. A
10028*67e74705SXin Li // concept definition refers to [...] a variable concept and its initializer.
10029*67e74705SXin Li if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10030*67e74705SXin Li if (VTD->isConcept()) {
10031*67e74705SXin Li Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10032*67e74705SXin Li Var->setInvalidDecl();
10033*67e74705SXin Li return;
10034*67e74705SXin Li }
10035*67e74705SXin Li }
10036*67e74705SXin Li
10037*67e74705SXin Li // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10038*67e74705SXin Li // be initialized.
10039*67e74705SXin Li if (!Var->isInvalidDecl() &&
10040*67e74705SXin Li Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10041*67e74705SXin Li Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10042*67e74705SXin Li Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10043*67e74705SXin Li Var->setInvalidDecl();
10044*67e74705SXin Li return;
10045*67e74705SXin Li }
10046*67e74705SXin Li
10047*67e74705SXin Li switch (Var->isThisDeclarationADefinition()) {
10048*67e74705SXin Li case VarDecl::Definition:
10049*67e74705SXin Li if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10050*67e74705SXin Li break;
10051*67e74705SXin Li
10052*67e74705SXin Li // We have an out-of-line definition of a static data member
10053*67e74705SXin Li // that has an in-class initializer, so we type-check this like
10054*67e74705SXin Li // a declaration.
10055*67e74705SXin Li //
10056*67e74705SXin Li // Fall through
10057*67e74705SXin Li
10058*67e74705SXin Li case VarDecl::DeclarationOnly:
10059*67e74705SXin Li // It's only a declaration.
10060*67e74705SXin Li
10061*67e74705SXin Li // Block scope. C99 6.7p7: If an identifier for an object is
10062*67e74705SXin Li // declared with no linkage (C99 6.2.2p6), the type for the
10063*67e74705SXin Li // object shall be complete.
10064*67e74705SXin Li if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10065*67e74705SXin Li !Var->hasLinkage() && !Var->isInvalidDecl() &&
10066*67e74705SXin Li RequireCompleteType(Var->getLocation(), Type,
10067*67e74705SXin Li diag::err_typecheck_decl_incomplete_type))
10068*67e74705SXin Li Var->setInvalidDecl();
10069*67e74705SXin Li
10070*67e74705SXin Li // Make sure that the type is not abstract.
10071*67e74705SXin Li if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10072*67e74705SXin Li RequireNonAbstractType(Var->getLocation(), Type,
10073*67e74705SXin Li diag::err_abstract_type_in_decl,
10074*67e74705SXin Li AbstractVariableType))
10075*67e74705SXin Li Var->setInvalidDecl();
10076*67e74705SXin Li if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10077*67e74705SXin Li Var->getStorageClass() == SC_PrivateExtern) {
10078*67e74705SXin Li Diag(Var->getLocation(), diag::warn_private_extern);
10079*67e74705SXin Li Diag(Var->getLocation(), diag::note_private_extern);
10080*67e74705SXin Li }
10081*67e74705SXin Li
10082*67e74705SXin Li return;
10083*67e74705SXin Li
10084*67e74705SXin Li case VarDecl::TentativeDefinition:
10085*67e74705SXin Li // File scope. C99 6.9.2p2: A declaration of an identifier for an
10086*67e74705SXin Li // object that has file scope without an initializer, and without a
10087*67e74705SXin Li // storage-class specifier or with the storage-class specifier "static",
10088*67e74705SXin Li // constitutes a tentative definition. Note: A tentative definition with
10089*67e74705SXin Li // external linkage is valid (C99 6.2.2p5).
10090*67e74705SXin Li if (!Var->isInvalidDecl()) {
10091*67e74705SXin Li if (const IncompleteArrayType *ArrayT
10092*67e74705SXin Li = Context.getAsIncompleteArrayType(Type)) {
10093*67e74705SXin Li if (RequireCompleteType(Var->getLocation(),
10094*67e74705SXin Li ArrayT->getElementType(),
10095*67e74705SXin Li diag::err_illegal_decl_array_incomplete_type))
10096*67e74705SXin Li Var->setInvalidDecl();
10097*67e74705SXin Li } else if (Var->getStorageClass() == SC_Static) {
10098*67e74705SXin Li // C99 6.9.2p3: If the declaration of an identifier for an object is
10099*67e74705SXin Li // a tentative definition and has internal linkage (C99 6.2.2p3), the
10100*67e74705SXin Li // declared type shall not be an incomplete type.
10101*67e74705SXin Li // NOTE: code such as the following
10102*67e74705SXin Li // static struct s;
10103*67e74705SXin Li // struct s { int a; };
10104*67e74705SXin Li // is accepted by gcc. Hence here we issue a warning instead of
10105*67e74705SXin Li // an error and we do not invalidate the static declaration.
10106*67e74705SXin Li // NOTE: to avoid multiple warnings, only check the first declaration.
10107*67e74705SXin Li if (Var->isFirstDecl())
10108*67e74705SXin Li RequireCompleteType(Var->getLocation(), Type,
10109*67e74705SXin Li diag::ext_typecheck_decl_incomplete_type);
10110*67e74705SXin Li }
10111*67e74705SXin Li }
10112*67e74705SXin Li
10113*67e74705SXin Li // Record the tentative definition; we're done.
10114*67e74705SXin Li if (!Var->isInvalidDecl())
10115*67e74705SXin Li TentativeDefinitions.push_back(Var);
10116*67e74705SXin Li return;
10117*67e74705SXin Li }
10118*67e74705SXin Li
10119*67e74705SXin Li // Provide a specific diagnostic for uninitialized variable
10120*67e74705SXin Li // definitions with incomplete array type.
10121*67e74705SXin Li if (Type->isIncompleteArrayType()) {
10122*67e74705SXin Li Diag(Var->getLocation(),
10123*67e74705SXin Li diag::err_typecheck_incomplete_array_needs_initializer);
10124*67e74705SXin Li Var->setInvalidDecl();
10125*67e74705SXin Li return;
10126*67e74705SXin Li }
10127*67e74705SXin Li
10128*67e74705SXin Li // Provide a specific diagnostic for uninitialized variable
10129*67e74705SXin Li // definitions with reference type.
10130*67e74705SXin Li if (Type->isReferenceType()) {
10131*67e74705SXin Li Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10132*67e74705SXin Li << Var->getDeclName()
10133*67e74705SXin Li << SourceRange(Var->getLocation(), Var->getLocation());
10134*67e74705SXin Li Var->setInvalidDecl();
10135*67e74705SXin Li return;
10136*67e74705SXin Li }
10137*67e74705SXin Li
10138*67e74705SXin Li // Do not attempt to type-check the default initializer for a
10139*67e74705SXin Li // variable with dependent type.
10140*67e74705SXin Li if (Type->isDependentType())
10141*67e74705SXin Li return;
10142*67e74705SXin Li
10143*67e74705SXin Li if (Var->isInvalidDecl())
10144*67e74705SXin Li return;
10145*67e74705SXin Li
10146*67e74705SXin Li if (!Var->hasAttr<AliasAttr>()) {
10147*67e74705SXin Li if (RequireCompleteType(Var->getLocation(),
10148*67e74705SXin Li Context.getBaseElementType(Type),
10149*67e74705SXin Li diag::err_typecheck_decl_incomplete_type)) {
10150*67e74705SXin Li Var->setInvalidDecl();
10151*67e74705SXin Li return;
10152*67e74705SXin Li }
10153*67e74705SXin Li } else {
10154*67e74705SXin Li return;
10155*67e74705SXin Li }
10156*67e74705SXin Li
10157*67e74705SXin Li // The variable can not have an abstract class type.
10158*67e74705SXin Li if (RequireNonAbstractType(Var->getLocation(), Type,
10159*67e74705SXin Li diag::err_abstract_type_in_decl,
10160*67e74705SXin Li AbstractVariableType)) {
10161*67e74705SXin Li Var->setInvalidDecl();
10162*67e74705SXin Li return;
10163*67e74705SXin Li }
10164*67e74705SXin Li
10165*67e74705SXin Li // Check for jumps past the implicit initializer. C++0x
10166*67e74705SXin Li // clarifies that this applies to a "variable with automatic
10167*67e74705SXin Li // storage duration", not a "local variable".
10168*67e74705SXin Li // C++11 [stmt.dcl]p3
10169*67e74705SXin Li // A program that jumps from a point where a variable with automatic
10170*67e74705SXin Li // storage duration is not in scope to a point where it is in scope is
10171*67e74705SXin Li // ill-formed unless the variable has scalar type, class type with a
10172*67e74705SXin Li // trivial default constructor and a trivial destructor, a cv-qualified
10173*67e74705SXin Li // version of one of these types, or an array of one of the preceding
10174*67e74705SXin Li // types and is declared without an initializer.
10175*67e74705SXin Li if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10176*67e74705SXin Li if (const RecordType *Record
10177*67e74705SXin Li = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10178*67e74705SXin Li CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10179*67e74705SXin Li // Mark the function for further checking even if the looser rules of
10180*67e74705SXin Li // C++11 do not require such checks, so that we can diagnose
10181*67e74705SXin Li // incompatibilities with C++98.
10182*67e74705SXin Li if (!CXXRecord->isPOD())
10183*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
10184*67e74705SXin Li }
10185*67e74705SXin Li }
10186*67e74705SXin Li
10187*67e74705SXin Li // C++03 [dcl.init]p9:
10188*67e74705SXin Li // If no initializer is specified for an object, and the
10189*67e74705SXin Li // object is of (possibly cv-qualified) non-POD class type (or
10190*67e74705SXin Li // array thereof), the object shall be default-initialized; if
10191*67e74705SXin Li // the object is of const-qualified type, the underlying class
10192*67e74705SXin Li // type shall have a user-declared default
10193*67e74705SXin Li // constructor. Otherwise, if no initializer is specified for
10194*67e74705SXin Li // a non- static object, the object and its subobjects, if
10195*67e74705SXin Li // any, have an indeterminate initial value); if the object
10196*67e74705SXin Li // or any of its subobjects are of const-qualified type, the
10197*67e74705SXin Li // program is ill-formed.
10198*67e74705SXin Li // C++0x [dcl.init]p11:
10199*67e74705SXin Li // If no initializer is specified for an object, the object is
10200*67e74705SXin Li // default-initialized; [...].
10201*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10202*67e74705SXin Li InitializationKind Kind
10203*67e74705SXin Li = InitializationKind::CreateDefault(Var->getLocation());
10204*67e74705SXin Li
10205*67e74705SXin Li InitializationSequence InitSeq(*this, Entity, Kind, None);
10206*67e74705SXin Li ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10207*67e74705SXin Li if (Init.isInvalid())
10208*67e74705SXin Li Var->setInvalidDecl();
10209*67e74705SXin Li else if (Init.get()) {
10210*67e74705SXin Li Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10211*67e74705SXin Li // This is important for template substitution.
10212*67e74705SXin Li Var->setInitStyle(VarDecl::CallInit);
10213*67e74705SXin Li }
10214*67e74705SXin Li
10215*67e74705SXin Li CheckCompleteVariableDeclaration(Var);
10216*67e74705SXin Li }
10217*67e74705SXin Li }
10218*67e74705SXin Li
ActOnCXXForRangeDecl(Decl * D)10219*67e74705SXin Li void Sema::ActOnCXXForRangeDecl(Decl *D) {
10220*67e74705SXin Li // If there is no declaration, there was an error parsing it. Ignore it.
10221*67e74705SXin Li if (!D)
10222*67e74705SXin Li return;
10223*67e74705SXin Li
10224*67e74705SXin Li VarDecl *VD = dyn_cast<VarDecl>(D);
10225*67e74705SXin Li if (!VD) {
10226*67e74705SXin Li Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10227*67e74705SXin Li D->setInvalidDecl();
10228*67e74705SXin Li return;
10229*67e74705SXin Li }
10230*67e74705SXin Li
10231*67e74705SXin Li VD->setCXXForRangeDecl(true);
10232*67e74705SXin Li
10233*67e74705SXin Li // for-range-declaration cannot be given a storage class specifier.
10234*67e74705SXin Li int Error = -1;
10235*67e74705SXin Li switch (VD->getStorageClass()) {
10236*67e74705SXin Li case SC_None:
10237*67e74705SXin Li break;
10238*67e74705SXin Li case SC_Extern:
10239*67e74705SXin Li Error = 0;
10240*67e74705SXin Li break;
10241*67e74705SXin Li case SC_Static:
10242*67e74705SXin Li Error = 1;
10243*67e74705SXin Li break;
10244*67e74705SXin Li case SC_PrivateExtern:
10245*67e74705SXin Li Error = 2;
10246*67e74705SXin Li break;
10247*67e74705SXin Li case SC_Auto:
10248*67e74705SXin Li Error = 3;
10249*67e74705SXin Li break;
10250*67e74705SXin Li case SC_Register:
10251*67e74705SXin Li Error = 4;
10252*67e74705SXin Li break;
10253*67e74705SXin Li }
10254*67e74705SXin Li if (Error != -1) {
10255*67e74705SXin Li Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10256*67e74705SXin Li << VD->getDeclName() << Error;
10257*67e74705SXin Li D->setInvalidDecl();
10258*67e74705SXin Li }
10259*67e74705SXin Li }
10260*67e74705SXin Li
10261*67e74705SXin Li StmtResult
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs,SourceLocation AttrEnd)10262*67e74705SXin Li Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10263*67e74705SXin Li IdentifierInfo *Ident,
10264*67e74705SXin Li ParsedAttributes &Attrs,
10265*67e74705SXin Li SourceLocation AttrEnd) {
10266*67e74705SXin Li // C++1y [stmt.iter]p1:
10267*67e74705SXin Li // A range-based for statement of the form
10268*67e74705SXin Li // for ( for-range-identifier : for-range-initializer ) statement
10269*67e74705SXin Li // is equivalent to
10270*67e74705SXin Li // for ( auto&& for-range-identifier : for-range-initializer ) statement
10271*67e74705SXin Li DeclSpec DS(Attrs.getPool().getFactory());
10272*67e74705SXin Li
10273*67e74705SXin Li const char *PrevSpec;
10274*67e74705SXin Li unsigned DiagID;
10275*67e74705SXin Li DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10276*67e74705SXin Li getPrintingPolicy());
10277*67e74705SXin Li
10278*67e74705SXin Li Declarator D(DS, Declarator::ForContext);
10279*67e74705SXin Li D.SetIdentifier(Ident, IdentLoc);
10280*67e74705SXin Li D.takeAttributes(Attrs, AttrEnd);
10281*67e74705SXin Li
10282*67e74705SXin Li ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10283*67e74705SXin Li D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10284*67e74705SXin Li EmptyAttrs, IdentLoc);
10285*67e74705SXin Li Decl *Var = ActOnDeclarator(S, D);
10286*67e74705SXin Li cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10287*67e74705SXin Li FinalizeDeclaration(Var);
10288*67e74705SXin Li return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10289*67e74705SXin Li AttrEnd.isValid() ? AttrEnd : IdentLoc);
10290*67e74705SXin Li }
10291*67e74705SXin Li
CheckCompleteVariableDeclaration(VarDecl * var)10292*67e74705SXin Li void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10293*67e74705SXin Li if (var->isInvalidDecl()) return;
10294*67e74705SXin Li
10295*67e74705SXin Li if (getLangOpts().OpenCL) {
10296*67e74705SXin Li // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10297*67e74705SXin Li // initialiser
10298*67e74705SXin Li if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10299*67e74705SXin Li !var->hasInit()) {
10300*67e74705SXin Li Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10301*67e74705SXin Li << 1 /*Init*/;
10302*67e74705SXin Li var->setInvalidDecl();
10303*67e74705SXin Li return;
10304*67e74705SXin Li }
10305*67e74705SXin Li }
10306*67e74705SXin Li
10307*67e74705SXin Li // In Objective-C, don't allow jumps past the implicit initialization of a
10308*67e74705SXin Li // local retaining variable.
10309*67e74705SXin Li if (getLangOpts().ObjC1 &&
10310*67e74705SXin Li var->hasLocalStorage()) {
10311*67e74705SXin Li switch (var->getType().getObjCLifetime()) {
10312*67e74705SXin Li case Qualifiers::OCL_None:
10313*67e74705SXin Li case Qualifiers::OCL_ExplicitNone:
10314*67e74705SXin Li case Qualifiers::OCL_Autoreleasing:
10315*67e74705SXin Li break;
10316*67e74705SXin Li
10317*67e74705SXin Li case Qualifiers::OCL_Weak:
10318*67e74705SXin Li case Qualifiers::OCL_Strong:
10319*67e74705SXin Li getCurFunction()->setHasBranchProtectedScope();
10320*67e74705SXin Li break;
10321*67e74705SXin Li }
10322*67e74705SXin Li }
10323*67e74705SXin Li
10324*67e74705SXin Li // Warn about externally-visible variables being defined without a
10325*67e74705SXin Li // prior declaration. We only want to do this for global
10326*67e74705SXin Li // declarations, but we also specifically need to avoid doing it for
10327*67e74705SXin Li // class members because the linkage of an anonymous class can
10328*67e74705SXin Li // change if it's later given a typedef name.
10329*67e74705SXin Li if (var->isThisDeclarationADefinition() &&
10330*67e74705SXin Li var->getDeclContext()->getRedeclContext()->isFileContext() &&
10331*67e74705SXin Li var->isExternallyVisible() && var->hasLinkage() &&
10332*67e74705SXin Li !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10333*67e74705SXin Li var->getLocation())) {
10334*67e74705SXin Li // Find a previous declaration that's not a definition.
10335*67e74705SXin Li VarDecl *prev = var->getPreviousDecl();
10336*67e74705SXin Li while (prev && prev->isThisDeclarationADefinition())
10337*67e74705SXin Li prev = prev->getPreviousDecl();
10338*67e74705SXin Li
10339*67e74705SXin Li if (!prev)
10340*67e74705SXin Li Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10341*67e74705SXin Li }
10342*67e74705SXin Li
10343*67e74705SXin Li if (var->getTLSKind() == VarDecl::TLS_Static) {
10344*67e74705SXin Li const Expr *Culprit;
10345*67e74705SXin Li if (var->getType().isDestructedType()) {
10346*67e74705SXin Li // GNU C++98 edits for __thread, [basic.start.term]p3:
10347*67e74705SXin Li // The type of an object with thread storage duration shall not
10348*67e74705SXin Li // have a non-trivial destructor.
10349*67e74705SXin Li Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10350*67e74705SXin Li if (getLangOpts().CPlusPlus11)
10351*67e74705SXin Li Diag(var->getLocation(), diag::note_use_thread_local);
10352*67e74705SXin Li } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10353*67e74705SXin Li !var->getInit()->isConstantInitializer(
10354*67e74705SXin Li Context, var->getType()->isReferenceType(), &Culprit)) {
10355*67e74705SXin Li // GNU C++98 edits for __thread, [basic.start.init]p4:
10356*67e74705SXin Li // An object of thread storage duration shall not require dynamic
10357*67e74705SXin Li // initialization.
10358*67e74705SXin Li // FIXME: Need strict checking here.
10359*67e74705SXin Li Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10360*67e74705SXin Li << Culprit->getSourceRange();
10361*67e74705SXin Li if (getLangOpts().CPlusPlus11)
10362*67e74705SXin Li Diag(var->getLocation(), diag::note_use_thread_local);
10363*67e74705SXin Li }
10364*67e74705SXin Li }
10365*67e74705SXin Li
10366*67e74705SXin Li // Apply section attributes and pragmas to global variables.
10367*67e74705SXin Li bool GlobalStorage = var->hasGlobalStorage();
10368*67e74705SXin Li if (GlobalStorage && var->isThisDeclarationADefinition() &&
10369*67e74705SXin Li ActiveTemplateInstantiations.empty()) {
10370*67e74705SXin Li PragmaStack<StringLiteral *> *Stack = nullptr;
10371*67e74705SXin Li int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10372*67e74705SXin Li if (var->getType().isConstQualified())
10373*67e74705SXin Li Stack = &ConstSegStack;
10374*67e74705SXin Li else if (!var->getInit()) {
10375*67e74705SXin Li Stack = &BSSSegStack;
10376*67e74705SXin Li SectionFlags |= ASTContext::PSF_Write;
10377*67e74705SXin Li } else {
10378*67e74705SXin Li Stack = &DataSegStack;
10379*67e74705SXin Li SectionFlags |= ASTContext::PSF_Write;
10380*67e74705SXin Li }
10381*67e74705SXin Li if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10382*67e74705SXin Li var->addAttr(SectionAttr::CreateImplicit(
10383*67e74705SXin Li Context, SectionAttr::Declspec_allocate,
10384*67e74705SXin Li Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10385*67e74705SXin Li }
10386*67e74705SXin Li if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10387*67e74705SXin Li if (UnifySection(SA->getName(), SectionFlags, var))
10388*67e74705SXin Li var->dropAttr<SectionAttr>();
10389*67e74705SXin Li
10390*67e74705SXin Li // Apply the init_seg attribute if this has an initializer. If the
10391*67e74705SXin Li // initializer turns out to not be dynamic, we'll end up ignoring this
10392*67e74705SXin Li // attribute.
10393*67e74705SXin Li if (CurInitSeg && var->getInit())
10394*67e74705SXin Li var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10395*67e74705SXin Li CurInitSegLoc));
10396*67e74705SXin Li }
10397*67e74705SXin Li
10398*67e74705SXin Li // All the following checks are C++ only.
10399*67e74705SXin Li if (!getLangOpts().CPlusPlus) return;
10400*67e74705SXin Li
10401*67e74705SXin Li QualType type = var->getType();
10402*67e74705SXin Li if (type->isDependentType()) return;
10403*67e74705SXin Li
10404*67e74705SXin Li // __block variables might require us to capture a copy-initializer.
10405*67e74705SXin Li if (var->hasAttr<BlocksAttr>()) {
10406*67e74705SXin Li // It's currently invalid to ever have a __block variable with an
10407*67e74705SXin Li // array type; should we diagnose that here?
10408*67e74705SXin Li
10409*67e74705SXin Li // Regardless, we don't want to ignore array nesting when
10410*67e74705SXin Li // constructing this copy.
10411*67e74705SXin Li if (type->isStructureOrClassType()) {
10412*67e74705SXin Li EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10413*67e74705SXin Li SourceLocation poi = var->getLocation();
10414*67e74705SXin Li Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10415*67e74705SXin Li ExprResult result
10416*67e74705SXin Li = PerformMoveOrCopyInitialization(
10417*67e74705SXin Li InitializedEntity::InitializeBlock(poi, type, false),
10418*67e74705SXin Li var, var->getType(), varRef, /*AllowNRVO=*/true);
10419*67e74705SXin Li if (!result.isInvalid()) {
10420*67e74705SXin Li result = MaybeCreateExprWithCleanups(result);
10421*67e74705SXin Li Expr *init = result.getAs<Expr>();
10422*67e74705SXin Li Context.setBlockVarCopyInits(var, init);
10423*67e74705SXin Li }
10424*67e74705SXin Li }
10425*67e74705SXin Li }
10426*67e74705SXin Li
10427*67e74705SXin Li Expr *Init = var->getInit();
10428*67e74705SXin Li bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10429*67e74705SXin Li QualType baseType = Context.getBaseElementType(type);
10430*67e74705SXin Li
10431*67e74705SXin Li if (!var->getDeclContext()->isDependentContext() &&
10432*67e74705SXin Li Init && !Init->isValueDependent()) {
10433*67e74705SXin Li if (IsGlobal && !var->isConstexpr() &&
10434*67e74705SXin Li !getDiagnostics().isIgnored(diag::warn_global_constructor,
10435*67e74705SXin Li var->getLocation())) {
10436*67e74705SXin Li // Warn about globals which don't have a constant initializer. Don't
10437*67e74705SXin Li // warn about globals with a non-trivial destructor because we already
10438*67e74705SXin Li // warned about them.
10439*67e74705SXin Li CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10440*67e74705SXin Li if (!(RD && !RD->hasTrivialDestructor()) &&
10441*67e74705SXin Li !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10442*67e74705SXin Li Diag(var->getLocation(), diag::warn_global_constructor)
10443*67e74705SXin Li << Init->getSourceRange();
10444*67e74705SXin Li }
10445*67e74705SXin Li
10446*67e74705SXin Li if (var->isConstexpr()) {
10447*67e74705SXin Li SmallVector<PartialDiagnosticAt, 8> Notes;
10448*67e74705SXin Li if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10449*67e74705SXin Li SourceLocation DiagLoc = var->getLocation();
10450*67e74705SXin Li // If the note doesn't add any useful information other than a source
10451*67e74705SXin Li // location, fold it into the primary diagnostic.
10452*67e74705SXin Li if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10453*67e74705SXin Li diag::note_invalid_subexpr_in_const_expr) {
10454*67e74705SXin Li DiagLoc = Notes[0].first;
10455*67e74705SXin Li Notes.clear();
10456*67e74705SXin Li }
10457*67e74705SXin Li Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10458*67e74705SXin Li << var << Init->getSourceRange();
10459*67e74705SXin Li for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10460*67e74705SXin Li Diag(Notes[I].first, Notes[I].second);
10461*67e74705SXin Li }
10462*67e74705SXin Li } else if (var->isUsableInConstantExpressions(Context)) {
10463*67e74705SXin Li // Check whether the initializer of a const variable of integral or
10464*67e74705SXin Li // enumeration type is an ICE now, since we can't tell whether it was
10465*67e74705SXin Li // initialized by a constant expression if we check later.
10466*67e74705SXin Li var->checkInitIsICE();
10467*67e74705SXin Li }
10468*67e74705SXin Li }
10469*67e74705SXin Li
10470*67e74705SXin Li // Require the destructor.
10471*67e74705SXin Li if (const RecordType *recordType = baseType->getAs<RecordType>())
10472*67e74705SXin Li FinalizeVarWithDestructor(var, recordType);
10473*67e74705SXin Li }
10474*67e74705SXin Li
10475*67e74705SXin Li /// \brief Determines if a variable's alignment is dependent.
hasDependentAlignment(VarDecl * VD)10476*67e74705SXin Li static bool hasDependentAlignment(VarDecl *VD) {
10477*67e74705SXin Li if (VD->getType()->isDependentType())
10478*67e74705SXin Li return true;
10479*67e74705SXin Li for (auto *I : VD->specific_attrs<AlignedAttr>())
10480*67e74705SXin Li if (I->isAlignmentDependent())
10481*67e74705SXin Li return true;
10482*67e74705SXin Li return false;
10483*67e74705SXin Li }
10484*67e74705SXin Li
10485*67e74705SXin Li /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10486*67e74705SXin Li /// any semantic actions necessary after any initializer has been attached.
10487*67e74705SXin Li void
FinalizeDeclaration(Decl * ThisDecl)10488*67e74705SXin Li Sema::FinalizeDeclaration(Decl *ThisDecl) {
10489*67e74705SXin Li // Note that we are no longer parsing the initializer for this declaration.
10490*67e74705SXin Li ParsingInitForAutoVars.erase(ThisDecl);
10491*67e74705SXin Li
10492*67e74705SXin Li VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10493*67e74705SXin Li if (!VD)
10494*67e74705SXin Li return;
10495*67e74705SXin Li
10496*67e74705SXin Li checkAttributesAfterMerging(*this, *VD);
10497*67e74705SXin Li
10498*67e74705SXin Li // Perform TLS alignment check here after attributes attached to the variable
10499*67e74705SXin Li // which may affect the alignment have been processed. Only perform the check
10500*67e74705SXin Li // if the target has a maximum TLS alignment (zero means no constraints).
10501*67e74705SXin Li if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10502*67e74705SXin Li // Protect the check so that it's not performed on dependent types and
10503*67e74705SXin Li // dependent alignments (we can't determine the alignment in that case).
10504*67e74705SXin Li if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10505*67e74705SXin Li CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10506*67e74705SXin Li if (Context.getDeclAlign(VD) > MaxAlignChars) {
10507*67e74705SXin Li Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10508*67e74705SXin Li << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10509*67e74705SXin Li << (unsigned)MaxAlignChars.getQuantity();
10510*67e74705SXin Li }
10511*67e74705SXin Li }
10512*67e74705SXin Li }
10513*67e74705SXin Li
10514*67e74705SXin Li if (VD->isStaticLocal()) {
10515*67e74705SXin Li if (FunctionDecl *FD =
10516*67e74705SXin Li dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10517*67e74705SXin Li // Static locals inherit dll attributes from their function.
10518*67e74705SXin Li if (Attr *A = getDLLAttr(FD)) {
10519*67e74705SXin Li auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10520*67e74705SXin Li NewAttr->setInherited(true);
10521*67e74705SXin Li VD->addAttr(NewAttr);
10522*67e74705SXin Li }
10523*67e74705SXin Li // CUDA E.2.9.4: Within the body of a __device__ or __global__
10524*67e74705SXin Li // function, only __shared__ variables may be declared with
10525*67e74705SXin Li // static storage class.
10526*67e74705SXin Li if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10527*67e74705SXin Li (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10528*67e74705SXin Li !VD->hasAttr<CUDASharedAttr>()) {
10529*67e74705SXin Li Diag(VD->getLocation(), diag::err_device_static_local_var);
10530*67e74705SXin Li VD->setInvalidDecl();
10531*67e74705SXin Li }
10532*67e74705SXin Li }
10533*67e74705SXin Li }
10534*67e74705SXin Li
10535*67e74705SXin Li // Perform check for initializers of device-side global variables.
10536*67e74705SXin Li // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10537*67e74705SXin Li // 7.5). We must also apply the same checks to all __shared__
10538*67e74705SXin Li // variables whether they are local or not. CUDA also allows
10539*67e74705SXin Li // constant initializers for __constant__ and __device__ variables.
10540*67e74705SXin Li if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10541*67e74705SXin Li const Expr *Init = VD->getInit();
10542*67e74705SXin Li if (Init && VD->hasGlobalStorage() &&
10543*67e74705SXin Li (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10544*67e74705SXin Li VD->hasAttr<CUDASharedAttr>())) {
10545*67e74705SXin Li assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10546*67e74705SXin Li bool AllowedInit = false;
10547*67e74705SXin Li if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10548*67e74705SXin Li AllowedInit =
10549*67e74705SXin Li isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10550*67e74705SXin Li // We'll allow constant initializers even if it's a non-empty
10551*67e74705SXin Li // constructor according to CUDA rules. This deviates from NVCC,
10552*67e74705SXin Li // but allows us to handle things like constexpr constructors.
10553*67e74705SXin Li if (!AllowedInit &&
10554*67e74705SXin Li (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10555*67e74705SXin Li AllowedInit = VD->getInit()->isConstantInitializer(
10556*67e74705SXin Li Context, VD->getType()->isReferenceType());
10557*67e74705SXin Li
10558*67e74705SXin Li // Also make sure that destructor, if there is one, is empty.
10559*67e74705SXin Li if (AllowedInit)
10560*67e74705SXin Li if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10561*67e74705SXin Li AllowedInit =
10562*67e74705SXin Li isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10563*67e74705SXin Li
10564*67e74705SXin Li if (!AllowedInit) {
10565*67e74705SXin Li Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10566*67e74705SXin Li ? diag::err_shared_var_init
10567*67e74705SXin Li : diag::err_dynamic_var_init)
10568*67e74705SXin Li << Init->getSourceRange();
10569*67e74705SXin Li VD->setInvalidDecl();
10570*67e74705SXin Li }
10571*67e74705SXin Li }
10572*67e74705SXin Li }
10573*67e74705SXin Li
10574*67e74705SXin Li // Grab the dllimport or dllexport attribute off of the VarDecl.
10575*67e74705SXin Li const InheritableAttr *DLLAttr = getDLLAttr(VD);
10576*67e74705SXin Li
10577*67e74705SXin Li // Imported static data members cannot be defined out-of-line.
10578*67e74705SXin Li if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10579*67e74705SXin Li if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10580*67e74705SXin Li VD->isThisDeclarationADefinition()) {
10581*67e74705SXin Li // We allow definitions of dllimport class template static data members
10582*67e74705SXin Li // with a warning.
10583*67e74705SXin Li CXXRecordDecl *Context =
10584*67e74705SXin Li cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10585*67e74705SXin Li bool IsClassTemplateMember =
10586*67e74705SXin Li isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10587*67e74705SXin Li Context->getDescribedClassTemplate();
10588*67e74705SXin Li
10589*67e74705SXin Li Diag(VD->getLocation(),
10590*67e74705SXin Li IsClassTemplateMember
10591*67e74705SXin Li ? diag::warn_attribute_dllimport_static_field_definition
10592*67e74705SXin Li : diag::err_attribute_dllimport_static_field_definition);
10593*67e74705SXin Li Diag(IA->getLocation(), diag::note_attribute);
10594*67e74705SXin Li if (!IsClassTemplateMember)
10595*67e74705SXin Li VD->setInvalidDecl();
10596*67e74705SXin Li }
10597*67e74705SXin Li }
10598*67e74705SXin Li
10599*67e74705SXin Li // dllimport/dllexport variables cannot be thread local, their TLS index
10600*67e74705SXin Li // isn't exported with the variable.
10601*67e74705SXin Li if (DLLAttr && VD->getTLSKind()) {
10602*67e74705SXin Li auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10603*67e74705SXin Li if (F && getDLLAttr(F)) {
10604*67e74705SXin Li assert(VD->isStaticLocal());
10605*67e74705SXin Li // But if this is a static local in a dlimport/dllexport function, the
10606*67e74705SXin Li // function will never be inlined, which means the var would never be
10607*67e74705SXin Li // imported, so having it marked import/export is safe.
10608*67e74705SXin Li } else {
10609*67e74705SXin Li Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10610*67e74705SXin Li << DLLAttr;
10611*67e74705SXin Li VD->setInvalidDecl();
10612*67e74705SXin Li }
10613*67e74705SXin Li }
10614*67e74705SXin Li
10615*67e74705SXin Li if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10616*67e74705SXin Li if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10617*67e74705SXin Li Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10618*67e74705SXin Li VD->dropAttr<UsedAttr>();
10619*67e74705SXin Li }
10620*67e74705SXin Li }
10621*67e74705SXin Li
10622*67e74705SXin Li const DeclContext *DC = VD->getDeclContext();
10623*67e74705SXin Li // If there's a #pragma GCC visibility in scope, and this isn't a class
10624*67e74705SXin Li // member, set the visibility of this variable.
10625*67e74705SXin Li if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10626*67e74705SXin Li AddPushedVisibilityAttribute(VD);
10627*67e74705SXin Li
10628*67e74705SXin Li // FIXME: Warn on unused templates.
10629*67e74705SXin Li if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10630*67e74705SXin Li !isa<VarTemplatePartialSpecializationDecl>(VD))
10631*67e74705SXin Li MarkUnusedFileScopedDecl(VD);
10632*67e74705SXin Li
10633*67e74705SXin Li // Now we have parsed the initializer and can update the table of magic
10634*67e74705SXin Li // tag values.
10635*67e74705SXin Li if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10636*67e74705SXin Li !VD->getType()->isIntegralOrEnumerationType())
10637*67e74705SXin Li return;
10638*67e74705SXin Li
10639*67e74705SXin Li for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10640*67e74705SXin Li const Expr *MagicValueExpr = VD->getInit();
10641*67e74705SXin Li if (!MagicValueExpr) {
10642*67e74705SXin Li continue;
10643*67e74705SXin Li }
10644*67e74705SXin Li llvm::APSInt MagicValueInt;
10645*67e74705SXin Li if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10646*67e74705SXin Li Diag(I->getRange().getBegin(),
10647*67e74705SXin Li diag::err_type_tag_for_datatype_not_ice)
10648*67e74705SXin Li << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10649*67e74705SXin Li continue;
10650*67e74705SXin Li }
10651*67e74705SXin Li if (MagicValueInt.getActiveBits() > 64) {
10652*67e74705SXin Li Diag(I->getRange().getBegin(),
10653*67e74705SXin Li diag::err_type_tag_for_datatype_too_large)
10654*67e74705SXin Li << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10655*67e74705SXin Li continue;
10656*67e74705SXin Li }
10657*67e74705SXin Li uint64_t MagicValue = MagicValueInt.getZExtValue();
10658*67e74705SXin Li RegisterTypeTagForDatatype(I->getArgumentKind(),
10659*67e74705SXin Li MagicValue,
10660*67e74705SXin Li I->getMatchingCType(),
10661*67e74705SXin Li I->getLayoutCompatible(),
10662*67e74705SXin Li I->getMustBeNull());
10663*67e74705SXin Li }
10664*67e74705SXin Li }
10665*67e74705SXin Li
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)10666*67e74705SXin Li Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10667*67e74705SXin Li ArrayRef<Decl *> Group) {
10668*67e74705SXin Li SmallVector<Decl*, 8> Decls;
10669*67e74705SXin Li
10670*67e74705SXin Li if (DS.isTypeSpecOwned())
10671*67e74705SXin Li Decls.push_back(DS.getRepAsDecl());
10672*67e74705SXin Li
10673*67e74705SXin Li DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10674*67e74705SXin Li for (unsigned i = 0, e = Group.size(); i != e; ++i)
10675*67e74705SXin Li if (Decl *D = Group[i]) {
10676*67e74705SXin Li if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10677*67e74705SXin Li if (!FirstDeclaratorInGroup)
10678*67e74705SXin Li FirstDeclaratorInGroup = DD;
10679*67e74705SXin Li Decls.push_back(D);
10680*67e74705SXin Li }
10681*67e74705SXin Li
10682*67e74705SXin Li if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10683*67e74705SXin Li if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10684*67e74705SXin Li handleTagNumbering(Tag, S);
10685*67e74705SXin Li if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10686*67e74705SXin Li getLangOpts().CPlusPlus)
10687*67e74705SXin Li Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10688*67e74705SXin Li }
10689*67e74705SXin Li }
10690*67e74705SXin Li
10691*67e74705SXin Li return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10692*67e74705SXin Li }
10693*67e74705SXin Li
10694*67e74705SXin Li /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10695*67e74705SXin Li /// group, performing any necessary semantic checking.
10696*67e74705SXin Li Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group,bool TypeMayContainAuto)10697*67e74705SXin Li Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10698*67e74705SXin Li bool TypeMayContainAuto) {
10699*67e74705SXin Li // C++0x [dcl.spec.auto]p7:
10700*67e74705SXin Li // If the type deduced for the template parameter U is not the same in each
10701*67e74705SXin Li // deduction, the program is ill-formed.
10702*67e74705SXin Li // FIXME: When initializer-list support is added, a distinction is needed
10703*67e74705SXin Li // between the deduced type U and the deduced type which 'auto' stands for.
10704*67e74705SXin Li // auto a = 0, b = { 1, 2, 3 };
10705*67e74705SXin Li // is legal because the deduced type U is 'int' in both cases.
10706*67e74705SXin Li if (TypeMayContainAuto && Group.size() > 1) {
10707*67e74705SXin Li QualType Deduced;
10708*67e74705SXin Li CanQualType DeducedCanon;
10709*67e74705SXin Li VarDecl *DeducedDecl = nullptr;
10710*67e74705SXin Li for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10711*67e74705SXin Li if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10712*67e74705SXin Li AutoType *AT = D->getType()->getContainedAutoType();
10713*67e74705SXin Li // Don't reissue diagnostics when instantiating a template.
10714*67e74705SXin Li if (AT && D->isInvalidDecl())
10715*67e74705SXin Li break;
10716*67e74705SXin Li QualType U = AT ? AT->getDeducedType() : QualType();
10717*67e74705SXin Li if (!U.isNull()) {
10718*67e74705SXin Li CanQualType UCanon = Context.getCanonicalType(U);
10719*67e74705SXin Li if (Deduced.isNull()) {
10720*67e74705SXin Li Deduced = U;
10721*67e74705SXin Li DeducedCanon = UCanon;
10722*67e74705SXin Li DeducedDecl = D;
10723*67e74705SXin Li } else if (DeducedCanon != UCanon) {
10724*67e74705SXin Li Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10725*67e74705SXin Li diag::err_auto_different_deductions)
10726*67e74705SXin Li << (unsigned)AT->getKeyword()
10727*67e74705SXin Li << Deduced << DeducedDecl->getDeclName()
10728*67e74705SXin Li << U << D->getDeclName()
10729*67e74705SXin Li << DeducedDecl->getInit()->getSourceRange()
10730*67e74705SXin Li << D->getInit()->getSourceRange();
10731*67e74705SXin Li D->setInvalidDecl();
10732*67e74705SXin Li break;
10733*67e74705SXin Li }
10734*67e74705SXin Li }
10735*67e74705SXin Li }
10736*67e74705SXin Li }
10737*67e74705SXin Li }
10738*67e74705SXin Li
10739*67e74705SXin Li ActOnDocumentableDecls(Group);
10740*67e74705SXin Li
10741*67e74705SXin Li return DeclGroupPtrTy::make(
10742*67e74705SXin Li DeclGroupRef::Create(Context, Group.data(), Group.size()));
10743*67e74705SXin Li }
10744*67e74705SXin Li
ActOnDocumentableDecl(Decl * D)10745*67e74705SXin Li void Sema::ActOnDocumentableDecl(Decl *D) {
10746*67e74705SXin Li ActOnDocumentableDecls(D);
10747*67e74705SXin Li }
10748*67e74705SXin Li
ActOnDocumentableDecls(ArrayRef<Decl * > Group)10749*67e74705SXin Li void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10750*67e74705SXin Li // Don't parse the comment if Doxygen diagnostics are ignored.
10751*67e74705SXin Li if (Group.empty() || !Group[0])
10752*67e74705SXin Li return;
10753*67e74705SXin Li
10754*67e74705SXin Li if (Diags.isIgnored(diag::warn_doc_param_not_found,
10755*67e74705SXin Li Group[0]->getLocation()) &&
10756*67e74705SXin Li Diags.isIgnored(diag::warn_unknown_comment_command_name,
10757*67e74705SXin Li Group[0]->getLocation()))
10758*67e74705SXin Li return;
10759*67e74705SXin Li
10760*67e74705SXin Li if (Group.size() >= 2) {
10761*67e74705SXin Li // This is a decl group. Normally it will contain only declarations
10762*67e74705SXin Li // produced from declarator list. But in case we have any definitions or
10763*67e74705SXin Li // additional declaration references:
10764*67e74705SXin Li // 'typedef struct S {} S;'
10765*67e74705SXin Li // 'typedef struct S *S;'
10766*67e74705SXin Li // 'struct S *pS;'
10767*67e74705SXin Li // FinalizeDeclaratorGroup adds these as separate declarations.
10768*67e74705SXin Li Decl *MaybeTagDecl = Group[0];
10769*67e74705SXin Li if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10770*67e74705SXin Li Group = Group.slice(1);
10771*67e74705SXin Li }
10772*67e74705SXin Li }
10773*67e74705SXin Li
10774*67e74705SXin Li // See if there are any new comments that are not attached to a decl.
10775*67e74705SXin Li ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10776*67e74705SXin Li if (!Comments.empty() &&
10777*67e74705SXin Li !Comments.back()->isAttached()) {
10778*67e74705SXin Li // There is at least one comment that not attached to a decl.
10779*67e74705SXin Li // Maybe it should be attached to one of these decls?
10780*67e74705SXin Li //
10781*67e74705SXin Li // Note that this way we pick up not only comments that precede the
10782*67e74705SXin Li // declaration, but also comments that *follow* the declaration -- thanks to
10783*67e74705SXin Li // the lookahead in the lexer: we've consumed the semicolon and looked
10784*67e74705SXin Li // ahead through comments.
10785*67e74705SXin Li for (unsigned i = 0, e = Group.size(); i != e; ++i)
10786*67e74705SXin Li Context.getCommentForDecl(Group[i], &PP);
10787*67e74705SXin Li }
10788*67e74705SXin Li }
10789*67e74705SXin Li
10790*67e74705SXin Li /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10791*67e74705SXin Li /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)10792*67e74705SXin Li Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10793*67e74705SXin Li const DeclSpec &DS = D.getDeclSpec();
10794*67e74705SXin Li
10795*67e74705SXin Li // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10796*67e74705SXin Li
10797*67e74705SXin Li // C++03 [dcl.stc]p2 also permits 'auto'.
10798*67e74705SXin Li StorageClass SC = SC_None;
10799*67e74705SXin Li if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10800*67e74705SXin Li SC = SC_Register;
10801*67e74705SXin Li } else if (getLangOpts().CPlusPlus &&
10802*67e74705SXin Li DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10803*67e74705SXin Li SC = SC_Auto;
10804*67e74705SXin Li } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10805*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(),
10806*67e74705SXin Li diag::err_invalid_storage_class_in_func_decl);
10807*67e74705SXin Li D.getMutableDeclSpec().ClearStorageClassSpecs();
10808*67e74705SXin Li }
10809*67e74705SXin Li
10810*67e74705SXin Li if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10811*67e74705SXin Li Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10812*67e74705SXin Li << DeclSpec::getSpecifierName(TSCS);
10813*67e74705SXin Li if (DS.isInlineSpecified())
10814*67e74705SXin Li Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
10815*67e74705SXin Li << getLangOpts().CPlusPlus1z;
10816*67e74705SXin Li if (DS.isConstexprSpecified())
10817*67e74705SXin Li Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10818*67e74705SXin Li << 0;
10819*67e74705SXin Li if (DS.isConceptSpecified())
10820*67e74705SXin Li Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10821*67e74705SXin Li
10822*67e74705SXin Li DiagnoseFunctionSpecifiers(DS);
10823*67e74705SXin Li
10824*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10825*67e74705SXin Li QualType parmDeclType = TInfo->getType();
10826*67e74705SXin Li
10827*67e74705SXin Li if (getLangOpts().CPlusPlus) {
10828*67e74705SXin Li // Check that there are no default arguments inside the type of this
10829*67e74705SXin Li // parameter.
10830*67e74705SXin Li CheckExtraCXXDefaultArguments(D);
10831*67e74705SXin Li
10832*67e74705SXin Li // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10833*67e74705SXin Li if (D.getCXXScopeSpec().isSet()) {
10834*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10835*67e74705SXin Li << D.getCXXScopeSpec().getRange();
10836*67e74705SXin Li D.getCXXScopeSpec().clear();
10837*67e74705SXin Li }
10838*67e74705SXin Li }
10839*67e74705SXin Li
10840*67e74705SXin Li // Ensure we have a valid name
10841*67e74705SXin Li IdentifierInfo *II = nullptr;
10842*67e74705SXin Li if (D.hasName()) {
10843*67e74705SXin Li II = D.getIdentifier();
10844*67e74705SXin Li if (!II) {
10845*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10846*67e74705SXin Li << GetNameForDeclarator(D).getName();
10847*67e74705SXin Li D.setInvalidType(true);
10848*67e74705SXin Li }
10849*67e74705SXin Li }
10850*67e74705SXin Li
10851*67e74705SXin Li // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10852*67e74705SXin Li if (II) {
10853*67e74705SXin Li LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10854*67e74705SXin Li ForRedeclaration);
10855*67e74705SXin Li LookupName(R, S);
10856*67e74705SXin Li if (R.isSingleResult()) {
10857*67e74705SXin Li NamedDecl *PrevDecl = R.getFoundDecl();
10858*67e74705SXin Li if (PrevDecl->isTemplateParameter()) {
10859*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
10860*67e74705SXin Li DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10861*67e74705SXin Li // Just pretend that we didn't see the previous declaration.
10862*67e74705SXin Li PrevDecl = nullptr;
10863*67e74705SXin Li } else if (S->isDeclScope(PrevDecl)) {
10864*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10865*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10866*67e74705SXin Li
10867*67e74705SXin Li // Recover by removing the name
10868*67e74705SXin Li II = nullptr;
10869*67e74705SXin Li D.SetIdentifier(nullptr, D.getIdentifierLoc());
10870*67e74705SXin Li D.setInvalidType(true);
10871*67e74705SXin Li }
10872*67e74705SXin Li }
10873*67e74705SXin Li }
10874*67e74705SXin Li
10875*67e74705SXin Li // Temporarily put parameter variables in the translation unit, not
10876*67e74705SXin Li // the enclosing context. This prevents them from accidentally
10877*67e74705SXin Li // looking like class members in C++.
10878*67e74705SXin Li ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10879*67e74705SXin Li D.getLocStart(),
10880*67e74705SXin Li D.getIdentifierLoc(), II,
10881*67e74705SXin Li parmDeclType, TInfo,
10882*67e74705SXin Li SC);
10883*67e74705SXin Li
10884*67e74705SXin Li if (D.isInvalidType())
10885*67e74705SXin Li New->setInvalidDecl();
10886*67e74705SXin Li
10887*67e74705SXin Li assert(S->isFunctionPrototypeScope());
10888*67e74705SXin Li assert(S->getFunctionPrototypeDepth() >= 1);
10889*67e74705SXin Li New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10890*67e74705SXin Li S->getNextFunctionPrototypeIndex());
10891*67e74705SXin Li
10892*67e74705SXin Li // Add the parameter declaration into this scope.
10893*67e74705SXin Li S->AddDecl(New);
10894*67e74705SXin Li if (II)
10895*67e74705SXin Li IdResolver.AddDecl(New);
10896*67e74705SXin Li
10897*67e74705SXin Li ProcessDeclAttributes(S, New, D);
10898*67e74705SXin Li
10899*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified())
10900*67e74705SXin Li Diag(New->getLocation(), diag::err_module_private_local)
10901*67e74705SXin Li << 1 << New->getDeclName()
10902*67e74705SXin Li << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10903*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10904*67e74705SXin Li
10905*67e74705SXin Li if (New->hasAttr<BlocksAttr>()) {
10906*67e74705SXin Li Diag(New->getLocation(), diag::err_block_on_nonlocal);
10907*67e74705SXin Li }
10908*67e74705SXin Li return New;
10909*67e74705SXin Li }
10910*67e74705SXin Li
10911*67e74705SXin Li /// \brief Synthesizes a variable for a parameter arising from a
10912*67e74705SXin Li /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)10913*67e74705SXin Li ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10914*67e74705SXin Li SourceLocation Loc,
10915*67e74705SXin Li QualType T) {
10916*67e74705SXin Li /* FIXME: setting StartLoc == Loc.
10917*67e74705SXin Li Would it be worth to modify callers so as to provide proper source
10918*67e74705SXin Li location for the unnamed parameters, embedding the parameter's type? */
10919*67e74705SXin Li ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10920*67e74705SXin Li T, Context.getTrivialTypeSourceInfo(T, Loc),
10921*67e74705SXin Li SC_None, nullptr);
10922*67e74705SXin Li Param->setImplicit();
10923*67e74705SXin Li return Param;
10924*67e74705SXin Li }
10925*67e74705SXin Li
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)10926*67e74705SXin Li void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
10927*67e74705SXin Li // Don't diagnose unused-parameter errors in template instantiations; we
10928*67e74705SXin Li // will already have done so in the template itself.
10929*67e74705SXin Li if (!ActiveTemplateInstantiations.empty())
10930*67e74705SXin Li return;
10931*67e74705SXin Li
10932*67e74705SXin Li for (const ParmVarDecl *Parameter : Parameters) {
10933*67e74705SXin Li if (!Parameter->isReferenced() && Parameter->getDeclName() &&
10934*67e74705SXin Li !Parameter->hasAttr<UnusedAttr>()) {
10935*67e74705SXin Li Diag(Parameter->getLocation(), diag::warn_unused_parameter)
10936*67e74705SXin Li << Parameter->getDeclName();
10937*67e74705SXin Li }
10938*67e74705SXin Li }
10939*67e74705SXin Li }
10940*67e74705SXin Li
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)10941*67e74705SXin Li void Sema::DiagnoseSizeOfParametersAndReturnValue(
10942*67e74705SXin Li ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
10943*67e74705SXin Li if (LangOpts.NumLargeByValueCopy == 0) // No check.
10944*67e74705SXin Li return;
10945*67e74705SXin Li
10946*67e74705SXin Li // Warn if the return value is pass-by-value and larger than the specified
10947*67e74705SXin Li // threshold.
10948*67e74705SXin Li if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10949*67e74705SXin Li unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10950*67e74705SXin Li if (Size > LangOpts.NumLargeByValueCopy)
10951*67e74705SXin Li Diag(D->getLocation(), diag::warn_return_value_size)
10952*67e74705SXin Li << D->getDeclName() << Size;
10953*67e74705SXin Li }
10954*67e74705SXin Li
10955*67e74705SXin Li // Warn if any parameter is pass-by-value and larger than the specified
10956*67e74705SXin Li // threshold.
10957*67e74705SXin Li for (const ParmVarDecl *Parameter : Parameters) {
10958*67e74705SXin Li QualType T = Parameter->getType();
10959*67e74705SXin Li if (T->isDependentType() || !T.isPODType(Context))
10960*67e74705SXin Li continue;
10961*67e74705SXin Li unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10962*67e74705SXin Li if (Size > LangOpts.NumLargeByValueCopy)
10963*67e74705SXin Li Diag(Parameter->getLocation(), diag::warn_parameter_size)
10964*67e74705SXin Li << Parameter->getDeclName() << Size;
10965*67e74705SXin Li }
10966*67e74705SXin Li }
10967*67e74705SXin Li
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)10968*67e74705SXin Li ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10969*67e74705SXin Li SourceLocation NameLoc, IdentifierInfo *Name,
10970*67e74705SXin Li QualType T, TypeSourceInfo *TSInfo,
10971*67e74705SXin Li StorageClass SC) {
10972*67e74705SXin Li // In ARC, infer a lifetime qualifier for appropriate parameter types.
10973*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount &&
10974*67e74705SXin Li T.getObjCLifetime() == Qualifiers::OCL_None &&
10975*67e74705SXin Li T->isObjCLifetimeType()) {
10976*67e74705SXin Li
10977*67e74705SXin Li Qualifiers::ObjCLifetime lifetime;
10978*67e74705SXin Li
10979*67e74705SXin Li // Special cases for arrays:
10980*67e74705SXin Li // - if it's const, use __unsafe_unretained
10981*67e74705SXin Li // - otherwise, it's an error
10982*67e74705SXin Li if (T->isArrayType()) {
10983*67e74705SXin Li if (!T.isConstQualified()) {
10984*67e74705SXin Li DelayedDiagnostics.add(
10985*67e74705SXin Li sema::DelayedDiagnostic::makeForbiddenType(
10986*67e74705SXin Li NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10987*67e74705SXin Li }
10988*67e74705SXin Li lifetime = Qualifiers::OCL_ExplicitNone;
10989*67e74705SXin Li } else {
10990*67e74705SXin Li lifetime = T->getObjCARCImplicitLifetime();
10991*67e74705SXin Li }
10992*67e74705SXin Li T = Context.getLifetimeQualifiedType(T, lifetime);
10993*67e74705SXin Li }
10994*67e74705SXin Li
10995*67e74705SXin Li ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10996*67e74705SXin Li Context.getAdjustedParameterType(T),
10997*67e74705SXin Li TSInfo, SC, nullptr);
10998*67e74705SXin Li
10999*67e74705SXin Li // Parameters can not be abstract class types.
11000*67e74705SXin Li // For record types, this is done by the AbstractClassUsageDiagnoser once
11001*67e74705SXin Li // the class has been completely parsed.
11002*67e74705SXin Li if (!CurContext->isRecord() &&
11003*67e74705SXin Li RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11004*67e74705SXin Li AbstractParamType))
11005*67e74705SXin Li New->setInvalidDecl();
11006*67e74705SXin Li
11007*67e74705SXin Li // Parameter declarators cannot be interface types. All ObjC objects are
11008*67e74705SXin Li // passed by reference.
11009*67e74705SXin Li if (T->isObjCObjectType()) {
11010*67e74705SXin Li SourceLocation TypeEndLoc =
11011*67e74705SXin Li getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11012*67e74705SXin Li Diag(NameLoc,
11013*67e74705SXin Li diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11014*67e74705SXin Li << FixItHint::CreateInsertion(TypeEndLoc, "*");
11015*67e74705SXin Li T = Context.getObjCObjectPointerType(T);
11016*67e74705SXin Li New->setType(T);
11017*67e74705SXin Li }
11018*67e74705SXin Li
11019*67e74705SXin Li // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11020*67e74705SXin Li // duration shall not be qualified by an address-space qualifier."
11021*67e74705SXin Li // Since all parameters have automatic store duration, they can not have
11022*67e74705SXin Li // an address space.
11023*67e74705SXin Li if (T.getAddressSpace() != 0) {
11024*67e74705SXin Li // OpenCL allows function arguments declared to be an array of a type
11025*67e74705SXin Li // to be qualified with an address space.
11026*67e74705SXin Li if (!(getLangOpts().OpenCL && T->isArrayType())) {
11027*67e74705SXin Li Diag(NameLoc, diag::err_arg_with_address_space);
11028*67e74705SXin Li New->setInvalidDecl();
11029*67e74705SXin Li }
11030*67e74705SXin Li }
11031*67e74705SXin Li
11032*67e74705SXin Li return New;
11033*67e74705SXin Li }
11034*67e74705SXin Li
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)11035*67e74705SXin Li void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11036*67e74705SXin Li SourceLocation LocAfterDecls) {
11037*67e74705SXin Li DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11038*67e74705SXin Li
11039*67e74705SXin Li // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11040*67e74705SXin Li // for a K&R function.
11041*67e74705SXin Li if (!FTI.hasPrototype) {
11042*67e74705SXin Li for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11043*67e74705SXin Li --i;
11044*67e74705SXin Li if (FTI.Params[i].Param == nullptr) {
11045*67e74705SXin Li SmallString<256> Code;
11046*67e74705SXin Li llvm::raw_svector_ostream(Code)
11047*67e74705SXin Li << " int " << FTI.Params[i].Ident->getName() << ";\n";
11048*67e74705SXin Li Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11049*67e74705SXin Li << FTI.Params[i].Ident
11050*67e74705SXin Li << FixItHint::CreateInsertion(LocAfterDecls, Code);
11051*67e74705SXin Li
11052*67e74705SXin Li // Implicitly declare the argument as type 'int' for lack of a better
11053*67e74705SXin Li // type.
11054*67e74705SXin Li AttributeFactory attrs;
11055*67e74705SXin Li DeclSpec DS(attrs);
11056*67e74705SXin Li const char* PrevSpec; // unused
11057*67e74705SXin Li unsigned DiagID; // unused
11058*67e74705SXin Li DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11059*67e74705SXin Li DiagID, Context.getPrintingPolicy());
11060*67e74705SXin Li // Use the identifier location for the type source range.
11061*67e74705SXin Li DS.SetRangeStart(FTI.Params[i].IdentLoc);
11062*67e74705SXin Li DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11063*67e74705SXin Li Declarator ParamD(DS, Declarator::KNRTypeListContext);
11064*67e74705SXin Li ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11065*67e74705SXin Li FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11066*67e74705SXin Li }
11067*67e74705SXin Li }
11068*67e74705SXin Li }
11069*67e74705SXin Li }
11070*67e74705SXin Li
11071*67e74705SXin Li Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)11072*67e74705SXin Li Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11073*67e74705SXin Li MultiTemplateParamsArg TemplateParameterLists,
11074*67e74705SXin Li SkipBodyInfo *SkipBody) {
11075*67e74705SXin Li assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11076*67e74705SXin Li assert(D.isFunctionDeclarator() && "Not a function declarator!");
11077*67e74705SXin Li Scope *ParentScope = FnBodyScope->getParent();
11078*67e74705SXin Li
11079*67e74705SXin Li D.setFunctionDefinitionKind(FDK_Definition);
11080*67e74705SXin Li Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11081*67e74705SXin Li return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11082*67e74705SXin Li }
11083*67e74705SXin Li
ActOnFinishInlineFunctionDef(FunctionDecl * D)11084*67e74705SXin Li void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11085*67e74705SXin Li Consumer.HandleInlineFunctionDefinition(D);
11086*67e74705SXin Li }
11087*67e74705SXin Li
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossibleZeroParamPrototype)11088*67e74705SXin Li static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11089*67e74705SXin Li const FunctionDecl*& PossibleZeroParamPrototype) {
11090*67e74705SXin Li // Don't warn about invalid declarations.
11091*67e74705SXin Li if (FD->isInvalidDecl())
11092*67e74705SXin Li return false;
11093*67e74705SXin Li
11094*67e74705SXin Li // Or declarations that aren't global.
11095*67e74705SXin Li if (!FD->isGlobal())
11096*67e74705SXin Li return false;
11097*67e74705SXin Li
11098*67e74705SXin Li // Don't warn about C++ member functions.
11099*67e74705SXin Li if (isa<CXXMethodDecl>(FD))
11100*67e74705SXin Li return false;
11101*67e74705SXin Li
11102*67e74705SXin Li // Don't warn about 'main'.
11103*67e74705SXin Li if (FD->isMain())
11104*67e74705SXin Li return false;
11105*67e74705SXin Li
11106*67e74705SXin Li // Don't warn about inline functions.
11107*67e74705SXin Li if (FD->isInlined())
11108*67e74705SXin Li return false;
11109*67e74705SXin Li
11110*67e74705SXin Li // Don't warn about function templates.
11111*67e74705SXin Li if (FD->getDescribedFunctionTemplate())
11112*67e74705SXin Li return false;
11113*67e74705SXin Li
11114*67e74705SXin Li // Don't warn about function template specializations.
11115*67e74705SXin Li if (FD->isFunctionTemplateSpecialization())
11116*67e74705SXin Li return false;
11117*67e74705SXin Li
11118*67e74705SXin Li // Don't warn for OpenCL kernels.
11119*67e74705SXin Li if (FD->hasAttr<OpenCLKernelAttr>())
11120*67e74705SXin Li return false;
11121*67e74705SXin Li
11122*67e74705SXin Li // Don't warn on explicitly deleted functions.
11123*67e74705SXin Li if (FD->isDeleted())
11124*67e74705SXin Li return false;
11125*67e74705SXin Li
11126*67e74705SXin Li bool MissingPrototype = true;
11127*67e74705SXin Li for (const FunctionDecl *Prev = FD->getPreviousDecl();
11128*67e74705SXin Li Prev; Prev = Prev->getPreviousDecl()) {
11129*67e74705SXin Li // Ignore any declarations that occur in function or method
11130*67e74705SXin Li // scope, because they aren't visible from the header.
11131*67e74705SXin Li if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11132*67e74705SXin Li continue;
11133*67e74705SXin Li
11134*67e74705SXin Li MissingPrototype = !Prev->getType()->isFunctionProtoType();
11135*67e74705SXin Li if (FD->getNumParams() == 0)
11136*67e74705SXin Li PossibleZeroParamPrototype = Prev;
11137*67e74705SXin Li break;
11138*67e74705SXin Li }
11139*67e74705SXin Li
11140*67e74705SXin Li return MissingPrototype;
11141*67e74705SXin Li }
11142*67e74705SXin Li
11143*67e74705SXin Li void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)11144*67e74705SXin Li Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11145*67e74705SXin Li const FunctionDecl *EffectiveDefinition,
11146*67e74705SXin Li SkipBodyInfo *SkipBody) {
11147*67e74705SXin Li // Don't complain if we're in GNU89 mode and the previous definition
11148*67e74705SXin Li // was an extern inline function.
11149*67e74705SXin Li const FunctionDecl *Definition = EffectiveDefinition;
11150*67e74705SXin Li if (!Definition)
11151*67e74705SXin Li if (!FD->isDefined(Definition))
11152*67e74705SXin Li return;
11153*67e74705SXin Li
11154*67e74705SXin Li if (canRedefineFunction(Definition, getLangOpts()))
11155*67e74705SXin Li return;
11156*67e74705SXin Li
11157*67e74705SXin Li // If we don't have a visible definition of the function, and it's inline or
11158*67e74705SXin Li // a template, skip the new definition.
11159*67e74705SXin Li if (SkipBody && !hasVisibleDefinition(Definition) &&
11160*67e74705SXin Li (Definition->getFormalLinkage() == InternalLinkage ||
11161*67e74705SXin Li Definition->isInlined() ||
11162*67e74705SXin Li Definition->getDescribedFunctionTemplate() ||
11163*67e74705SXin Li Definition->getNumTemplateParameterLists())) {
11164*67e74705SXin Li SkipBody->ShouldSkip = true;
11165*67e74705SXin Li if (auto *TD = Definition->getDescribedFunctionTemplate())
11166*67e74705SXin Li makeMergedDefinitionVisible(TD, FD->getLocation());
11167*67e74705SXin Li else
11168*67e74705SXin Li makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11169*67e74705SXin Li FD->getLocation());
11170*67e74705SXin Li return;
11171*67e74705SXin Li }
11172*67e74705SXin Li
11173*67e74705SXin Li if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11174*67e74705SXin Li Definition->getStorageClass() == SC_Extern)
11175*67e74705SXin Li Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11176*67e74705SXin Li << FD->getDeclName() << getLangOpts().CPlusPlus;
11177*67e74705SXin Li else
11178*67e74705SXin Li Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11179*67e74705SXin Li
11180*67e74705SXin Li Diag(Definition->getLocation(), diag::note_previous_definition);
11181*67e74705SXin Li FD->setInvalidDecl();
11182*67e74705SXin Li }
11183*67e74705SXin Li
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator,Sema & S)11184*67e74705SXin Li static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11185*67e74705SXin Li Sema &S) {
11186*67e74705SXin Li CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11187*67e74705SXin Li
11188*67e74705SXin Li LambdaScopeInfo *LSI = S.PushLambdaScope();
11189*67e74705SXin Li LSI->CallOperator = CallOperator;
11190*67e74705SXin Li LSI->Lambda = LambdaClass;
11191*67e74705SXin Li LSI->ReturnType = CallOperator->getReturnType();
11192*67e74705SXin Li const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11193*67e74705SXin Li
11194*67e74705SXin Li if (LCD == LCD_None)
11195*67e74705SXin Li LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11196*67e74705SXin Li else if (LCD == LCD_ByCopy)
11197*67e74705SXin Li LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11198*67e74705SXin Li else if (LCD == LCD_ByRef)
11199*67e74705SXin Li LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11200*67e74705SXin Li DeclarationNameInfo DNI = CallOperator->getNameInfo();
11201*67e74705SXin Li
11202*67e74705SXin Li LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11203*67e74705SXin Li LSI->Mutable = !CallOperator->isConst();
11204*67e74705SXin Li
11205*67e74705SXin Li // Add the captures to the LSI so they can be noted as already
11206*67e74705SXin Li // captured within tryCaptureVar.
11207*67e74705SXin Li auto I = LambdaClass->field_begin();
11208*67e74705SXin Li for (const auto &C : LambdaClass->captures()) {
11209*67e74705SXin Li if (C.capturesVariable()) {
11210*67e74705SXin Li VarDecl *VD = C.getCapturedVar();
11211*67e74705SXin Li if (VD->isInitCapture())
11212*67e74705SXin Li S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11213*67e74705SXin Li QualType CaptureType = VD->getType();
11214*67e74705SXin Li const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11215*67e74705SXin Li LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11216*67e74705SXin Li /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11217*67e74705SXin Li /*EllipsisLoc*/C.isPackExpansion()
11218*67e74705SXin Li ? C.getEllipsisLoc() : SourceLocation(),
11219*67e74705SXin Li CaptureType, /*Expr*/ nullptr);
11220*67e74705SXin Li
11221*67e74705SXin Li } else if (C.capturesThis()) {
11222*67e74705SXin Li LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11223*67e74705SXin Li /*Expr*/ nullptr,
11224*67e74705SXin Li C.getCaptureKind() == LCK_StarThis);
11225*67e74705SXin Li } else {
11226*67e74705SXin Li LSI->addVLATypeCapture(C.getLocation(), I->getType());
11227*67e74705SXin Li }
11228*67e74705SXin Li ++I;
11229*67e74705SXin Li }
11230*67e74705SXin Li }
11231*67e74705SXin Li
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody)11232*67e74705SXin Li Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11233*67e74705SXin Li SkipBodyInfo *SkipBody) {
11234*67e74705SXin Li // Clear the last template instantiation error context.
11235*67e74705SXin Li LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11236*67e74705SXin Li
11237*67e74705SXin Li if (!D)
11238*67e74705SXin Li return D;
11239*67e74705SXin Li FunctionDecl *FD = nullptr;
11240*67e74705SXin Li
11241*67e74705SXin Li if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11242*67e74705SXin Li FD = FunTmpl->getTemplatedDecl();
11243*67e74705SXin Li else
11244*67e74705SXin Li FD = cast<FunctionDecl>(D);
11245*67e74705SXin Li
11246*67e74705SXin Li // See if this is a redefinition.
11247*67e74705SXin Li if (!FD->isLateTemplateParsed()) {
11248*67e74705SXin Li CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11249*67e74705SXin Li
11250*67e74705SXin Li // If we're skipping the body, we're done. Don't enter the scope.
11251*67e74705SXin Li if (SkipBody && SkipBody->ShouldSkip)
11252*67e74705SXin Li return D;
11253*67e74705SXin Li }
11254*67e74705SXin Li
11255*67e74705SXin Li // If we are instantiating a generic lambda call operator, push
11256*67e74705SXin Li // a LambdaScopeInfo onto the function stack. But use the information
11257*67e74705SXin Li // that's already been calculated (ActOnLambdaExpr) to prime the current
11258*67e74705SXin Li // LambdaScopeInfo.
11259*67e74705SXin Li // When the template operator is being specialized, the LambdaScopeInfo,
11260*67e74705SXin Li // has to be properly restored so that tryCaptureVariable doesn't try
11261*67e74705SXin Li // and capture any new variables. In addition when calculating potential
11262*67e74705SXin Li // captures during transformation of nested lambdas, it is necessary to
11263*67e74705SXin Li // have the LSI properly restored.
11264*67e74705SXin Li if (isGenericLambdaCallOperatorSpecialization(FD)) {
11265*67e74705SXin Li assert(ActiveTemplateInstantiations.size() &&
11266*67e74705SXin Li "There should be an active template instantiation on the stack "
11267*67e74705SXin Li "when instantiating a generic lambda!");
11268*67e74705SXin Li RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11269*67e74705SXin Li }
11270*67e74705SXin Li else
11271*67e74705SXin Li // Enter a new function scope
11272*67e74705SXin Li PushFunctionScope();
11273*67e74705SXin Li
11274*67e74705SXin Li // Builtin functions cannot be defined.
11275*67e74705SXin Li if (unsigned BuiltinID = FD->getBuiltinID()) {
11276*67e74705SXin Li if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11277*67e74705SXin Li !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11278*67e74705SXin Li Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11279*67e74705SXin Li FD->setInvalidDecl();
11280*67e74705SXin Li }
11281*67e74705SXin Li }
11282*67e74705SXin Li
11283*67e74705SXin Li // The return type of a function definition must be complete
11284*67e74705SXin Li // (C99 6.9.1p3, C++ [dcl.fct]p6).
11285*67e74705SXin Li QualType ResultType = FD->getReturnType();
11286*67e74705SXin Li if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11287*67e74705SXin Li !FD->isInvalidDecl() &&
11288*67e74705SXin Li RequireCompleteType(FD->getLocation(), ResultType,
11289*67e74705SXin Li diag::err_func_def_incomplete_result))
11290*67e74705SXin Li FD->setInvalidDecl();
11291*67e74705SXin Li
11292*67e74705SXin Li if (FnBodyScope)
11293*67e74705SXin Li PushDeclContext(FnBodyScope, FD);
11294*67e74705SXin Li
11295*67e74705SXin Li // Check the validity of our function parameters
11296*67e74705SXin Li CheckParmsForFunctionDef(FD->parameters(),
11297*67e74705SXin Li /*CheckParameterNames=*/true);
11298*67e74705SXin Li
11299*67e74705SXin Li // Introduce our parameters into the function scope
11300*67e74705SXin Li for (auto Param : FD->parameters()) {
11301*67e74705SXin Li Param->setOwningFunction(FD);
11302*67e74705SXin Li
11303*67e74705SXin Li // If this has an identifier, add it to the scope stack.
11304*67e74705SXin Li if (Param->getIdentifier() && FnBodyScope) {
11305*67e74705SXin Li CheckShadow(FnBodyScope, Param);
11306*67e74705SXin Li
11307*67e74705SXin Li PushOnScopeChains(Param, FnBodyScope);
11308*67e74705SXin Li }
11309*67e74705SXin Li }
11310*67e74705SXin Li
11311*67e74705SXin Li // If we had any tags defined in the function prototype,
11312*67e74705SXin Li // introduce them into the function scope.
11313*67e74705SXin Li if (FnBodyScope) {
11314*67e74705SXin Li for (ArrayRef<NamedDecl *>::iterator
11315*67e74705SXin Li I = FD->getDeclsInPrototypeScope().begin(),
11316*67e74705SXin Li E = FD->getDeclsInPrototypeScope().end();
11317*67e74705SXin Li I != E; ++I) {
11318*67e74705SXin Li NamedDecl *D = *I;
11319*67e74705SXin Li
11320*67e74705SXin Li // Some of these decls (like enums) may have been pinned to the
11321*67e74705SXin Li // translation unit for lack of a real context earlier. If so, remove
11322*67e74705SXin Li // from the translation unit and reattach to the current context.
11323*67e74705SXin Li if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11324*67e74705SXin Li // Is the decl actually in the context?
11325*67e74705SXin Li if (Context.getTranslationUnitDecl()->containsDecl(D))
11326*67e74705SXin Li Context.getTranslationUnitDecl()->removeDecl(D);
11327*67e74705SXin Li // Either way, reassign the lexical decl context to our FunctionDecl.
11328*67e74705SXin Li D->setLexicalDeclContext(CurContext);
11329*67e74705SXin Li }
11330*67e74705SXin Li
11331*67e74705SXin Li // If the decl has a non-null name, make accessible in the current scope.
11332*67e74705SXin Li if (!D->getName().empty())
11333*67e74705SXin Li PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11334*67e74705SXin Li
11335*67e74705SXin Li // Similarly, dive into enums and fish their constants out, making them
11336*67e74705SXin Li // accessible in this scope.
11337*67e74705SXin Li if (auto *ED = dyn_cast<EnumDecl>(D)) {
11338*67e74705SXin Li for (auto *EI : ED->enumerators())
11339*67e74705SXin Li PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11340*67e74705SXin Li }
11341*67e74705SXin Li }
11342*67e74705SXin Li }
11343*67e74705SXin Li
11344*67e74705SXin Li // Ensure that the function's exception specification is instantiated.
11345*67e74705SXin Li if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11346*67e74705SXin Li ResolveExceptionSpec(D->getLocation(), FPT);
11347*67e74705SXin Li
11348*67e74705SXin Li // dllimport cannot be applied to non-inline function definitions.
11349*67e74705SXin Li if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11350*67e74705SXin Li !FD->isTemplateInstantiation()) {
11351*67e74705SXin Li assert(!FD->hasAttr<DLLExportAttr>());
11352*67e74705SXin Li Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11353*67e74705SXin Li FD->setInvalidDecl();
11354*67e74705SXin Li return D;
11355*67e74705SXin Li }
11356*67e74705SXin Li // We want to attach documentation to original Decl (which might be
11357*67e74705SXin Li // a function template).
11358*67e74705SXin Li ActOnDocumentableDecl(D);
11359*67e74705SXin Li if (getCurLexicalContext()->isObjCContainer() &&
11360*67e74705SXin Li getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11361*67e74705SXin Li getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11362*67e74705SXin Li Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11363*67e74705SXin Li
11364*67e74705SXin Li return D;
11365*67e74705SXin Li }
11366*67e74705SXin Li
11367*67e74705SXin Li /// \brief Given the set of return statements within a function body,
11368*67e74705SXin Li /// compute the variables that are subject to the named return value
11369*67e74705SXin Li /// optimization.
11370*67e74705SXin Li ///
11371*67e74705SXin Li /// Each of the variables that is subject to the named return value
11372*67e74705SXin Li /// optimization will be marked as NRVO variables in the AST, and any
11373*67e74705SXin Li /// return statement that has a marked NRVO variable as its NRVO candidate can
11374*67e74705SXin Li /// use the named return value optimization.
11375*67e74705SXin Li ///
11376*67e74705SXin Li /// This function applies a very simplistic algorithm for NRVO: if every return
11377*67e74705SXin Li /// statement in the scope of a variable has the same NRVO candidate, that
11378*67e74705SXin Li /// candidate is an NRVO variable.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)11379*67e74705SXin Li void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11380*67e74705SXin Li ReturnStmt **Returns = Scope->Returns.data();
11381*67e74705SXin Li
11382*67e74705SXin Li for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11383*67e74705SXin Li if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11384*67e74705SXin Li if (!NRVOCandidate->isNRVOVariable())
11385*67e74705SXin Li Returns[I]->setNRVOCandidate(nullptr);
11386*67e74705SXin Li }
11387*67e74705SXin Li }
11388*67e74705SXin Li }
11389*67e74705SXin Li
canDelayFunctionBody(const Declarator & D)11390*67e74705SXin Li bool Sema::canDelayFunctionBody(const Declarator &D) {
11391*67e74705SXin Li // We can't delay parsing the body of a constexpr function template (yet).
11392*67e74705SXin Li if (D.getDeclSpec().isConstexprSpecified())
11393*67e74705SXin Li return false;
11394*67e74705SXin Li
11395*67e74705SXin Li // We can't delay parsing the body of a function template with a deduced
11396*67e74705SXin Li // return type (yet).
11397*67e74705SXin Li if (D.getDeclSpec().containsPlaceholderType()) {
11398*67e74705SXin Li // If the placeholder introduces a non-deduced trailing return type,
11399*67e74705SXin Li // we can still delay parsing it.
11400*67e74705SXin Li if (D.getNumTypeObjects()) {
11401*67e74705SXin Li const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11402*67e74705SXin Li if (Outer.Kind == DeclaratorChunk::Function &&
11403*67e74705SXin Li Outer.Fun.hasTrailingReturnType()) {
11404*67e74705SXin Li QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11405*67e74705SXin Li return Ty.isNull() || !Ty->isUndeducedType();
11406*67e74705SXin Li }
11407*67e74705SXin Li }
11408*67e74705SXin Li return false;
11409*67e74705SXin Li }
11410*67e74705SXin Li
11411*67e74705SXin Li return true;
11412*67e74705SXin Li }
11413*67e74705SXin Li
canSkipFunctionBody(Decl * D)11414*67e74705SXin Li bool Sema::canSkipFunctionBody(Decl *D) {
11415*67e74705SXin Li // We cannot skip the body of a function (or function template) which is
11416*67e74705SXin Li // constexpr, since we may need to evaluate its body in order to parse the
11417*67e74705SXin Li // rest of the file.
11418*67e74705SXin Li // We cannot skip the body of a function with an undeduced return type,
11419*67e74705SXin Li // because any callers of that function need to know the type.
11420*67e74705SXin Li if (const FunctionDecl *FD = D->getAsFunction())
11421*67e74705SXin Li if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11422*67e74705SXin Li return false;
11423*67e74705SXin Li return Consumer.shouldSkipFunctionBody(D);
11424*67e74705SXin Li }
11425*67e74705SXin Li
ActOnSkippedFunctionBody(Decl * Decl)11426*67e74705SXin Li Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11427*67e74705SXin Li if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11428*67e74705SXin Li FD->setHasSkippedBody();
11429*67e74705SXin Li else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11430*67e74705SXin Li MD->setHasSkippedBody();
11431*67e74705SXin Li return Decl;
11432*67e74705SXin Li }
11433*67e74705SXin Li
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)11434*67e74705SXin Li Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11435*67e74705SXin Li return ActOnFinishFunctionBody(D, BodyArg, false);
11436*67e74705SXin Li }
11437*67e74705SXin Li
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)11438*67e74705SXin Li Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11439*67e74705SXin Li bool IsInstantiation) {
11440*67e74705SXin Li FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11441*67e74705SXin Li
11442*67e74705SXin Li sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11443*67e74705SXin Li sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11444*67e74705SXin Li
11445*67e74705SXin Li if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11446*67e74705SXin Li CheckCompletedCoroutineBody(FD, Body);
11447*67e74705SXin Li
11448*67e74705SXin Li if (FD) {
11449*67e74705SXin Li FD->setBody(Body);
11450*67e74705SXin Li
11451*67e74705SXin Li if (getLangOpts().CPlusPlus14) {
11452*67e74705SXin Li if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11453*67e74705SXin Li FD->getReturnType()->isUndeducedType()) {
11454*67e74705SXin Li // If the function has a deduced result type but contains no 'return'
11455*67e74705SXin Li // statements, the result type as written must be exactly 'auto', and
11456*67e74705SXin Li // the deduced result type is 'void'.
11457*67e74705SXin Li if (!FD->getReturnType()->getAs<AutoType>()) {
11458*67e74705SXin Li Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11459*67e74705SXin Li << FD->getReturnType();
11460*67e74705SXin Li FD->setInvalidDecl();
11461*67e74705SXin Li } else {
11462*67e74705SXin Li // Substitute 'void' for the 'auto' in the type.
11463*67e74705SXin Li TypeLoc ResultType = getReturnTypeLoc(FD);
11464*67e74705SXin Li Context.adjustDeducedFunctionResultType(
11465*67e74705SXin Li FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11466*67e74705SXin Li }
11467*67e74705SXin Li }
11468*67e74705SXin Li } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11469*67e74705SXin Li // In C++11, we don't use 'auto' deduction rules for lambda call
11470*67e74705SXin Li // operators because we don't support return type deduction.
11471*67e74705SXin Li auto *LSI = getCurLambda();
11472*67e74705SXin Li if (LSI->HasImplicitReturnType) {
11473*67e74705SXin Li deduceClosureReturnType(*LSI);
11474*67e74705SXin Li
11475*67e74705SXin Li // C++11 [expr.prim.lambda]p4:
11476*67e74705SXin Li // [...] if there are no return statements in the compound-statement
11477*67e74705SXin Li // [the deduced type is] the type void
11478*67e74705SXin Li QualType RetType =
11479*67e74705SXin Li LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11480*67e74705SXin Li
11481*67e74705SXin Li // Update the return type to the deduced type.
11482*67e74705SXin Li const FunctionProtoType *Proto =
11483*67e74705SXin Li FD->getType()->getAs<FunctionProtoType>();
11484*67e74705SXin Li FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11485*67e74705SXin Li Proto->getExtProtoInfo()));
11486*67e74705SXin Li }
11487*67e74705SXin Li }
11488*67e74705SXin Li
11489*67e74705SXin Li // The only way to be included in UndefinedButUsed is if there is an
11490*67e74705SXin Li // ODR use before the definition. Avoid the expensive map lookup if this
11491*67e74705SXin Li // is the first declaration.
11492*67e74705SXin Li if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11493*67e74705SXin Li if (!FD->isExternallyVisible())
11494*67e74705SXin Li UndefinedButUsed.erase(FD);
11495*67e74705SXin Li else if (FD->isInlined() &&
11496*67e74705SXin Li !LangOpts.GNUInline &&
11497*67e74705SXin Li (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11498*67e74705SXin Li UndefinedButUsed.erase(FD);
11499*67e74705SXin Li }
11500*67e74705SXin Li
11501*67e74705SXin Li // If the function implicitly returns zero (like 'main') or is naked,
11502*67e74705SXin Li // don't complain about missing return statements.
11503*67e74705SXin Li if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11504*67e74705SXin Li WP.disableCheckFallThrough();
11505*67e74705SXin Li
11506*67e74705SXin Li // MSVC permits the use of pure specifier (=0) on function definition,
11507*67e74705SXin Li // defined at class scope, warn about this non-standard construct.
11508*67e74705SXin Li if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11509*67e74705SXin Li Diag(FD->getLocation(), diag::ext_pure_function_definition);
11510*67e74705SXin Li
11511*67e74705SXin Li if (!FD->isInvalidDecl()) {
11512*67e74705SXin Li // Don't diagnose unused parameters of defaulted or deleted functions.
11513*67e74705SXin Li if (!FD->isDeleted() && !FD->isDefaulted())
11514*67e74705SXin Li DiagnoseUnusedParameters(FD->parameters());
11515*67e74705SXin Li DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11516*67e74705SXin Li FD->getReturnType(), FD);
11517*67e74705SXin Li
11518*67e74705SXin Li // If this is a structor, we need a vtable.
11519*67e74705SXin Li if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11520*67e74705SXin Li MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11521*67e74705SXin Li else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11522*67e74705SXin Li MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11523*67e74705SXin Li
11524*67e74705SXin Li // Try to apply the named return value optimization. We have to check
11525*67e74705SXin Li // if we can do this here because lambdas keep return statements around
11526*67e74705SXin Li // to deduce an implicit return type.
11527*67e74705SXin Li if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11528*67e74705SXin Li !FD->isDependentContext())
11529*67e74705SXin Li computeNRVO(Body, getCurFunction());
11530*67e74705SXin Li }
11531*67e74705SXin Li
11532*67e74705SXin Li // GNU warning -Wmissing-prototypes:
11533*67e74705SXin Li // Warn if a global function is defined without a previous
11534*67e74705SXin Li // prototype declaration. This warning is issued even if the
11535*67e74705SXin Li // definition itself provides a prototype. The aim is to detect
11536*67e74705SXin Li // global functions that fail to be declared in header files.
11537*67e74705SXin Li const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11538*67e74705SXin Li if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11539*67e74705SXin Li Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11540*67e74705SXin Li
11541*67e74705SXin Li if (PossibleZeroParamPrototype) {
11542*67e74705SXin Li // We found a declaration that is not a prototype,
11543*67e74705SXin Li // but that could be a zero-parameter prototype
11544*67e74705SXin Li if (TypeSourceInfo *TI =
11545*67e74705SXin Li PossibleZeroParamPrototype->getTypeSourceInfo()) {
11546*67e74705SXin Li TypeLoc TL = TI->getTypeLoc();
11547*67e74705SXin Li if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11548*67e74705SXin Li Diag(PossibleZeroParamPrototype->getLocation(),
11549*67e74705SXin Li diag::note_declaration_not_a_prototype)
11550*67e74705SXin Li << PossibleZeroParamPrototype
11551*67e74705SXin Li << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11552*67e74705SXin Li }
11553*67e74705SXin Li }
11554*67e74705SXin Li }
11555*67e74705SXin Li
11556*67e74705SXin Li if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11557*67e74705SXin Li const CXXMethodDecl *KeyFunction;
11558*67e74705SXin Li if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11559*67e74705SXin Li MD->isVirtual() &&
11560*67e74705SXin Li (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11561*67e74705SXin Li MD == KeyFunction->getCanonicalDecl()) {
11562*67e74705SXin Li // Update the key-function state if necessary for this ABI.
11563*67e74705SXin Li if (FD->isInlined() &&
11564*67e74705SXin Li !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11565*67e74705SXin Li Context.setNonKeyFunction(MD);
11566*67e74705SXin Li
11567*67e74705SXin Li // If the newly-chosen key function is already defined, then we
11568*67e74705SXin Li // need to mark the vtable as used retroactively.
11569*67e74705SXin Li KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11570*67e74705SXin Li const FunctionDecl *Definition;
11571*67e74705SXin Li if (KeyFunction && KeyFunction->isDefined(Definition))
11572*67e74705SXin Li MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11573*67e74705SXin Li } else {
11574*67e74705SXin Li // We just defined they key function; mark the vtable as used.
11575*67e74705SXin Li MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11576*67e74705SXin Li }
11577*67e74705SXin Li }
11578*67e74705SXin Li }
11579*67e74705SXin Li
11580*67e74705SXin Li assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11581*67e74705SXin Li "Function parsing confused");
11582*67e74705SXin Li } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11583*67e74705SXin Li assert(MD == getCurMethodDecl() && "Method parsing confused");
11584*67e74705SXin Li MD->setBody(Body);
11585*67e74705SXin Li if (!MD->isInvalidDecl()) {
11586*67e74705SXin Li DiagnoseUnusedParameters(MD->parameters());
11587*67e74705SXin Li DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11588*67e74705SXin Li MD->getReturnType(), MD);
11589*67e74705SXin Li
11590*67e74705SXin Li if (Body)
11591*67e74705SXin Li computeNRVO(Body, getCurFunction());
11592*67e74705SXin Li }
11593*67e74705SXin Li if (getCurFunction()->ObjCShouldCallSuper) {
11594*67e74705SXin Li Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11595*67e74705SXin Li << MD->getSelector().getAsString();
11596*67e74705SXin Li getCurFunction()->ObjCShouldCallSuper = false;
11597*67e74705SXin Li }
11598*67e74705SXin Li if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11599*67e74705SXin Li const ObjCMethodDecl *InitMethod = nullptr;
11600*67e74705SXin Li bool isDesignated =
11601*67e74705SXin Li MD->isDesignatedInitializerForTheInterface(&InitMethod);
11602*67e74705SXin Li assert(isDesignated && InitMethod);
11603*67e74705SXin Li (void)isDesignated;
11604*67e74705SXin Li
11605*67e74705SXin Li auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11606*67e74705SXin Li auto IFace = MD->getClassInterface();
11607*67e74705SXin Li if (!IFace)
11608*67e74705SXin Li return false;
11609*67e74705SXin Li auto SuperD = IFace->getSuperClass();
11610*67e74705SXin Li if (!SuperD)
11611*67e74705SXin Li return false;
11612*67e74705SXin Li return SuperD->getIdentifier() ==
11613*67e74705SXin Li NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11614*67e74705SXin Li };
11615*67e74705SXin Li // Don't issue this warning for unavailable inits or direct subclasses
11616*67e74705SXin Li // of NSObject.
11617*67e74705SXin Li if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11618*67e74705SXin Li Diag(MD->getLocation(),
11619*67e74705SXin Li diag::warn_objc_designated_init_missing_super_call);
11620*67e74705SXin Li Diag(InitMethod->getLocation(),
11621*67e74705SXin Li diag::note_objc_designated_init_marked_here);
11622*67e74705SXin Li }
11623*67e74705SXin Li getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11624*67e74705SXin Li }
11625*67e74705SXin Li if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11626*67e74705SXin Li // Don't issue this warning for unavaialable inits.
11627*67e74705SXin Li if (!MD->isUnavailable())
11628*67e74705SXin Li Diag(MD->getLocation(),
11629*67e74705SXin Li diag::warn_objc_secondary_init_missing_init_call);
11630*67e74705SXin Li getCurFunction()->ObjCWarnForNoInitDelegation = false;
11631*67e74705SXin Li }
11632*67e74705SXin Li } else {
11633*67e74705SXin Li return nullptr;
11634*67e74705SXin Li }
11635*67e74705SXin Li
11636*67e74705SXin Li assert(!getCurFunction()->ObjCShouldCallSuper &&
11637*67e74705SXin Li "This should only be set for ObjC methods, which should have been "
11638*67e74705SXin Li "handled in the block above.");
11639*67e74705SXin Li
11640*67e74705SXin Li // Verify and clean out per-function state.
11641*67e74705SXin Li if (Body && (!FD || !FD->isDefaulted())) {
11642*67e74705SXin Li // C++ constructors that have function-try-blocks can't have return
11643*67e74705SXin Li // statements in the handlers of that block. (C++ [except.handle]p14)
11644*67e74705SXin Li // Verify this.
11645*67e74705SXin Li if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11646*67e74705SXin Li DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11647*67e74705SXin Li
11648*67e74705SXin Li // Verify that gotos and switch cases don't jump into scopes illegally.
11649*67e74705SXin Li if (getCurFunction()->NeedsScopeChecking() &&
11650*67e74705SXin Li !PP.isCodeCompletionEnabled())
11651*67e74705SXin Li DiagnoseInvalidJumps(Body);
11652*67e74705SXin Li
11653*67e74705SXin Li if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11654*67e74705SXin Li if (!Destructor->getParent()->isDependentType())
11655*67e74705SXin Li CheckDestructor(Destructor);
11656*67e74705SXin Li
11657*67e74705SXin Li MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11658*67e74705SXin Li Destructor->getParent());
11659*67e74705SXin Li }
11660*67e74705SXin Li
11661*67e74705SXin Li // If any errors have occurred, clear out any temporaries that may have
11662*67e74705SXin Li // been leftover. This ensures that these temporaries won't be picked up for
11663*67e74705SXin Li // deletion in some later function.
11664*67e74705SXin Li if (getDiagnostics().hasErrorOccurred() ||
11665*67e74705SXin Li getDiagnostics().getSuppressAllDiagnostics()) {
11666*67e74705SXin Li DiscardCleanupsInEvaluationContext();
11667*67e74705SXin Li }
11668*67e74705SXin Li if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11669*67e74705SXin Li !isa<FunctionTemplateDecl>(dcl)) {
11670*67e74705SXin Li // Since the body is valid, issue any analysis-based warnings that are
11671*67e74705SXin Li // enabled.
11672*67e74705SXin Li ActivePolicy = &WP;
11673*67e74705SXin Li }
11674*67e74705SXin Li
11675*67e74705SXin Li if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11676*67e74705SXin Li (!CheckConstexprFunctionDecl(FD) ||
11677*67e74705SXin Li !CheckConstexprFunctionBody(FD, Body)))
11678*67e74705SXin Li FD->setInvalidDecl();
11679*67e74705SXin Li
11680*67e74705SXin Li if (FD && FD->hasAttr<NakedAttr>()) {
11681*67e74705SXin Li for (const Stmt *S : Body->children()) {
11682*67e74705SXin Li if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11683*67e74705SXin Li Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11684*67e74705SXin Li Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11685*67e74705SXin Li FD->setInvalidDecl();
11686*67e74705SXin Li break;
11687*67e74705SXin Li }
11688*67e74705SXin Li }
11689*67e74705SXin Li }
11690*67e74705SXin Li
11691*67e74705SXin Li assert(ExprCleanupObjects.size() ==
11692*67e74705SXin Li ExprEvalContexts.back().NumCleanupObjects &&
11693*67e74705SXin Li "Leftover temporaries in function");
11694*67e74705SXin Li assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
11695*67e74705SXin Li assert(MaybeODRUseExprs.empty() &&
11696*67e74705SXin Li "Leftover expressions for odr-use checking");
11697*67e74705SXin Li }
11698*67e74705SXin Li
11699*67e74705SXin Li if (!IsInstantiation)
11700*67e74705SXin Li PopDeclContext();
11701*67e74705SXin Li
11702*67e74705SXin Li PopFunctionScopeInfo(ActivePolicy, dcl);
11703*67e74705SXin Li // If any errors have occurred, clear out any temporaries that may have
11704*67e74705SXin Li // been leftover. This ensures that these temporaries won't be picked up for
11705*67e74705SXin Li // deletion in some later function.
11706*67e74705SXin Li if (getDiagnostics().hasErrorOccurred()) {
11707*67e74705SXin Li DiscardCleanupsInEvaluationContext();
11708*67e74705SXin Li }
11709*67e74705SXin Li
11710*67e74705SXin Li return dcl;
11711*67e74705SXin Li }
11712*67e74705SXin Li
11713*67e74705SXin Li /// When we finish delayed parsing of an attribute, we must attach it to the
11714*67e74705SXin Li /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)11715*67e74705SXin Li void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11716*67e74705SXin Li ParsedAttributes &Attrs) {
11717*67e74705SXin Li // Always attach attributes to the underlying decl.
11718*67e74705SXin Li if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11719*67e74705SXin Li D = TD->getTemplatedDecl();
11720*67e74705SXin Li ProcessDeclAttributeList(S, D, Attrs.getList());
11721*67e74705SXin Li
11722*67e74705SXin Li if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11723*67e74705SXin Li if (Method->isStatic())
11724*67e74705SXin Li checkThisInStaticMemberFunctionAttributes(Method);
11725*67e74705SXin Li }
11726*67e74705SXin Li
11727*67e74705SXin Li /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11728*67e74705SXin Li /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)11729*67e74705SXin Li NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11730*67e74705SXin Li IdentifierInfo &II, Scope *S) {
11731*67e74705SXin Li // Before we produce a declaration for an implicitly defined
11732*67e74705SXin Li // function, see whether there was a locally-scoped declaration of
11733*67e74705SXin Li // this name as a function or variable. If so, use that
11734*67e74705SXin Li // (non-visible) declaration, and complain about it.
11735*67e74705SXin Li if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11736*67e74705SXin Li Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11737*67e74705SXin Li Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11738*67e74705SXin Li return ExternCPrev;
11739*67e74705SXin Li }
11740*67e74705SXin Li
11741*67e74705SXin Li // Extension in C99. Legal in C90, but warn about it.
11742*67e74705SXin Li unsigned diag_id;
11743*67e74705SXin Li if (II.getName().startswith("__builtin_"))
11744*67e74705SXin Li diag_id = diag::warn_builtin_unknown;
11745*67e74705SXin Li else if (getLangOpts().C99)
11746*67e74705SXin Li diag_id = diag::ext_implicit_function_decl;
11747*67e74705SXin Li else
11748*67e74705SXin Li diag_id = diag::warn_implicit_function_decl;
11749*67e74705SXin Li Diag(Loc, diag_id) << &II;
11750*67e74705SXin Li
11751*67e74705SXin Li // Because typo correction is expensive, only do it if the implicit
11752*67e74705SXin Li // function declaration is going to be treated as an error.
11753*67e74705SXin Li if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11754*67e74705SXin Li TypoCorrection Corrected;
11755*67e74705SXin Li if (S &&
11756*67e74705SXin Li (Corrected = CorrectTypo(
11757*67e74705SXin Li DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11758*67e74705SXin Li llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11759*67e74705SXin Li diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11760*67e74705SXin Li /*ErrorRecovery*/false);
11761*67e74705SXin Li }
11762*67e74705SXin Li
11763*67e74705SXin Li // Set a Declarator for the implicit definition: int foo();
11764*67e74705SXin Li const char *Dummy;
11765*67e74705SXin Li AttributeFactory attrFactory;
11766*67e74705SXin Li DeclSpec DS(attrFactory);
11767*67e74705SXin Li unsigned DiagID;
11768*67e74705SXin Li bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11769*67e74705SXin Li Context.getPrintingPolicy());
11770*67e74705SXin Li (void)Error; // Silence warning.
11771*67e74705SXin Li assert(!Error && "Error setting up implicit decl!");
11772*67e74705SXin Li SourceLocation NoLoc;
11773*67e74705SXin Li Declarator D(DS, Declarator::BlockContext);
11774*67e74705SXin Li D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11775*67e74705SXin Li /*IsAmbiguous=*/false,
11776*67e74705SXin Li /*LParenLoc=*/NoLoc,
11777*67e74705SXin Li /*Params=*/nullptr,
11778*67e74705SXin Li /*NumParams=*/0,
11779*67e74705SXin Li /*EllipsisLoc=*/NoLoc,
11780*67e74705SXin Li /*RParenLoc=*/NoLoc,
11781*67e74705SXin Li /*TypeQuals=*/0,
11782*67e74705SXin Li /*RefQualifierIsLvalueRef=*/true,
11783*67e74705SXin Li /*RefQualifierLoc=*/NoLoc,
11784*67e74705SXin Li /*ConstQualifierLoc=*/NoLoc,
11785*67e74705SXin Li /*VolatileQualifierLoc=*/NoLoc,
11786*67e74705SXin Li /*RestrictQualifierLoc=*/NoLoc,
11787*67e74705SXin Li /*MutableLoc=*/NoLoc,
11788*67e74705SXin Li EST_None,
11789*67e74705SXin Li /*ESpecRange=*/SourceRange(),
11790*67e74705SXin Li /*Exceptions=*/nullptr,
11791*67e74705SXin Li /*ExceptionRanges=*/nullptr,
11792*67e74705SXin Li /*NumExceptions=*/0,
11793*67e74705SXin Li /*NoexceptExpr=*/nullptr,
11794*67e74705SXin Li /*ExceptionSpecTokens=*/nullptr,
11795*67e74705SXin Li Loc, Loc, D),
11796*67e74705SXin Li DS.getAttributes(),
11797*67e74705SXin Li SourceLocation());
11798*67e74705SXin Li D.SetIdentifier(&II, Loc);
11799*67e74705SXin Li
11800*67e74705SXin Li // Insert this function into translation-unit scope.
11801*67e74705SXin Li
11802*67e74705SXin Li DeclContext *PrevDC = CurContext;
11803*67e74705SXin Li CurContext = Context.getTranslationUnitDecl();
11804*67e74705SXin Li
11805*67e74705SXin Li FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11806*67e74705SXin Li FD->setImplicit();
11807*67e74705SXin Li
11808*67e74705SXin Li CurContext = PrevDC;
11809*67e74705SXin Li
11810*67e74705SXin Li AddKnownFunctionAttributes(FD);
11811*67e74705SXin Li
11812*67e74705SXin Li return FD;
11813*67e74705SXin Li }
11814*67e74705SXin Li
11815*67e74705SXin Li /// \brief Adds any function attributes that we know a priori based on
11816*67e74705SXin Li /// the declaration of this function.
11817*67e74705SXin Li ///
11818*67e74705SXin Li /// These attributes can apply both to implicitly-declared builtins
11819*67e74705SXin Li /// (like __builtin___printf_chk) or to library-declared functions
11820*67e74705SXin Li /// like NSLog or printf.
11821*67e74705SXin Li ///
11822*67e74705SXin Li /// We need to check for duplicate attributes both here and where user-written
11823*67e74705SXin Li /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)11824*67e74705SXin Li void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11825*67e74705SXin Li if (FD->isInvalidDecl())
11826*67e74705SXin Li return;
11827*67e74705SXin Li
11828*67e74705SXin Li // If this is a built-in function, map its builtin attributes to
11829*67e74705SXin Li // actual attributes.
11830*67e74705SXin Li if (unsigned BuiltinID = FD->getBuiltinID()) {
11831*67e74705SXin Li // Handle printf-formatting attributes.
11832*67e74705SXin Li unsigned FormatIdx;
11833*67e74705SXin Li bool HasVAListArg;
11834*67e74705SXin Li if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11835*67e74705SXin Li if (!FD->hasAttr<FormatAttr>()) {
11836*67e74705SXin Li const char *fmt = "printf";
11837*67e74705SXin Li unsigned int NumParams = FD->getNumParams();
11838*67e74705SXin Li if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11839*67e74705SXin Li FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11840*67e74705SXin Li fmt = "NSString";
11841*67e74705SXin Li FD->addAttr(FormatAttr::CreateImplicit(Context,
11842*67e74705SXin Li &Context.Idents.get(fmt),
11843*67e74705SXin Li FormatIdx+1,
11844*67e74705SXin Li HasVAListArg ? 0 : FormatIdx+2,
11845*67e74705SXin Li FD->getLocation()));
11846*67e74705SXin Li }
11847*67e74705SXin Li }
11848*67e74705SXin Li if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11849*67e74705SXin Li HasVAListArg)) {
11850*67e74705SXin Li if (!FD->hasAttr<FormatAttr>())
11851*67e74705SXin Li FD->addAttr(FormatAttr::CreateImplicit(Context,
11852*67e74705SXin Li &Context.Idents.get("scanf"),
11853*67e74705SXin Li FormatIdx+1,
11854*67e74705SXin Li HasVAListArg ? 0 : FormatIdx+2,
11855*67e74705SXin Li FD->getLocation()));
11856*67e74705SXin Li }
11857*67e74705SXin Li
11858*67e74705SXin Li // Mark const if we don't care about errno and that is the only
11859*67e74705SXin Li // thing preventing the function from being const. This allows
11860*67e74705SXin Li // IRgen to use LLVM intrinsics for such functions.
11861*67e74705SXin Li if (!getLangOpts().MathErrno &&
11862*67e74705SXin Li Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11863*67e74705SXin Li if (!FD->hasAttr<ConstAttr>())
11864*67e74705SXin Li FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11865*67e74705SXin Li }
11866*67e74705SXin Li
11867*67e74705SXin Li if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11868*67e74705SXin Li !FD->hasAttr<ReturnsTwiceAttr>())
11869*67e74705SXin Li FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11870*67e74705SXin Li FD->getLocation()));
11871*67e74705SXin Li if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11872*67e74705SXin Li FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11873*67e74705SXin Li if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11874*67e74705SXin Li FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11875*67e74705SXin Li if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11876*67e74705SXin Li FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11877*67e74705SXin Li if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11878*67e74705SXin Li !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11879*67e74705SXin Li // Add the appropriate attribute, depending on the CUDA compilation mode
11880*67e74705SXin Li // and which target the builtin belongs to. For example, during host
11881*67e74705SXin Li // compilation, aux builtins are __device__, while the rest are __host__.
11882*67e74705SXin Li if (getLangOpts().CUDAIsDevice !=
11883*67e74705SXin Li Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11884*67e74705SXin Li FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11885*67e74705SXin Li else
11886*67e74705SXin Li FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11887*67e74705SXin Li }
11888*67e74705SXin Li }
11889*67e74705SXin Li
11890*67e74705SXin Li // If C++ exceptions are enabled but we are told extern "C" functions cannot
11891*67e74705SXin Li // throw, add an implicit nothrow attribute to any extern "C" function we come
11892*67e74705SXin Li // across.
11893*67e74705SXin Li if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11894*67e74705SXin Li FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11895*67e74705SXin Li const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11896*67e74705SXin Li if (!FPT || FPT->getExceptionSpecType() == EST_None)
11897*67e74705SXin Li FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11898*67e74705SXin Li }
11899*67e74705SXin Li
11900*67e74705SXin Li IdentifierInfo *Name = FD->getIdentifier();
11901*67e74705SXin Li if (!Name)
11902*67e74705SXin Li return;
11903*67e74705SXin Li if ((!getLangOpts().CPlusPlus &&
11904*67e74705SXin Li FD->getDeclContext()->isTranslationUnit()) ||
11905*67e74705SXin Li (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11906*67e74705SXin Li cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11907*67e74705SXin Li LinkageSpecDecl::lang_c)) {
11908*67e74705SXin Li // Okay: this could be a libc/libm/Objective-C function we know
11909*67e74705SXin Li // about.
11910*67e74705SXin Li } else
11911*67e74705SXin Li return;
11912*67e74705SXin Li
11913*67e74705SXin Li if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11914*67e74705SXin Li // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11915*67e74705SXin Li // target-specific builtins, perhaps?
11916*67e74705SXin Li if (!FD->hasAttr<FormatAttr>())
11917*67e74705SXin Li FD->addAttr(FormatAttr::CreateImplicit(Context,
11918*67e74705SXin Li &Context.Idents.get("printf"), 2,
11919*67e74705SXin Li Name->isStr("vasprintf") ? 0 : 3,
11920*67e74705SXin Li FD->getLocation()));
11921*67e74705SXin Li }
11922*67e74705SXin Li
11923*67e74705SXin Li if (Name->isStr("__CFStringMakeConstantString")) {
11924*67e74705SXin Li // We already have a __builtin___CFStringMakeConstantString,
11925*67e74705SXin Li // but builds that use -fno-constant-cfstrings don't go through that.
11926*67e74705SXin Li if (!FD->hasAttr<FormatArgAttr>())
11927*67e74705SXin Li FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11928*67e74705SXin Li FD->getLocation()));
11929*67e74705SXin Li }
11930*67e74705SXin Li }
11931*67e74705SXin Li
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)11932*67e74705SXin Li TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11933*67e74705SXin Li TypeSourceInfo *TInfo) {
11934*67e74705SXin Li assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11935*67e74705SXin Li assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11936*67e74705SXin Li
11937*67e74705SXin Li if (!TInfo) {
11938*67e74705SXin Li assert(D.isInvalidType() && "no declarator info for valid type");
11939*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(T);
11940*67e74705SXin Li }
11941*67e74705SXin Li
11942*67e74705SXin Li // Scope manipulation handled by caller.
11943*67e74705SXin Li TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11944*67e74705SXin Li D.getLocStart(),
11945*67e74705SXin Li D.getIdentifierLoc(),
11946*67e74705SXin Li D.getIdentifier(),
11947*67e74705SXin Li TInfo);
11948*67e74705SXin Li
11949*67e74705SXin Li // Bail out immediately if we have an invalid declaration.
11950*67e74705SXin Li if (D.isInvalidType()) {
11951*67e74705SXin Li NewTD->setInvalidDecl();
11952*67e74705SXin Li return NewTD;
11953*67e74705SXin Li }
11954*67e74705SXin Li
11955*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified()) {
11956*67e74705SXin Li if (CurContext->isFunctionOrMethod())
11957*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_module_private_local)
11958*67e74705SXin Li << 2 << NewTD->getDeclName()
11959*67e74705SXin Li << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11960*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11961*67e74705SXin Li else
11962*67e74705SXin Li NewTD->setModulePrivate();
11963*67e74705SXin Li }
11964*67e74705SXin Li
11965*67e74705SXin Li // C++ [dcl.typedef]p8:
11966*67e74705SXin Li // If the typedef declaration defines an unnamed class (or
11967*67e74705SXin Li // enum), the first typedef-name declared by the declaration
11968*67e74705SXin Li // to be that class type (or enum type) is used to denote the
11969*67e74705SXin Li // class type (or enum type) for linkage purposes only.
11970*67e74705SXin Li // We need to check whether the type was declared in the declaration.
11971*67e74705SXin Li switch (D.getDeclSpec().getTypeSpecType()) {
11972*67e74705SXin Li case TST_enum:
11973*67e74705SXin Li case TST_struct:
11974*67e74705SXin Li case TST_interface:
11975*67e74705SXin Li case TST_union:
11976*67e74705SXin Li case TST_class: {
11977*67e74705SXin Li TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11978*67e74705SXin Li setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11979*67e74705SXin Li break;
11980*67e74705SXin Li }
11981*67e74705SXin Li
11982*67e74705SXin Li default:
11983*67e74705SXin Li break;
11984*67e74705SXin Li }
11985*67e74705SXin Li
11986*67e74705SXin Li return NewTD;
11987*67e74705SXin Li }
11988*67e74705SXin Li
11989*67e74705SXin Li /// \brief Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)11990*67e74705SXin Li bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11991*67e74705SXin Li SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11992*67e74705SXin Li QualType T = TI->getType();
11993*67e74705SXin Li
11994*67e74705SXin Li if (T->isDependentType())
11995*67e74705SXin Li return false;
11996*67e74705SXin Li
11997*67e74705SXin Li if (const BuiltinType *BT = T->getAs<BuiltinType>())
11998*67e74705SXin Li if (BT->isInteger())
11999*67e74705SXin Li return false;
12000*67e74705SXin Li
12001*67e74705SXin Li Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12002*67e74705SXin Li return true;
12003*67e74705SXin Li }
12004*67e74705SXin Li
12005*67e74705SXin Li /// Check whether this is a valid redeclaration of a previous enumeration.
12006*67e74705SXin Li /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool EnumUnderlyingIsImplicit,const EnumDecl * Prev)12007*67e74705SXin Li bool Sema::CheckEnumRedeclaration(
12008*67e74705SXin Li SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12009*67e74705SXin Li bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12010*67e74705SXin Li bool IsFixed = !EnumUnderlyingTy.isNull();
12011*67e74705SXin Li
12012*67e74705SXin Li if (IsScoped != Prev->isScoped()) {
12013*67e74705SXin Li Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12014*67e74705SXin Li << Prev->isScoped();
12015*67e74705SXin Li Diag(Prev->getLocation(), diag::note_previous_declaration);
12016*67e74705SXin Li return true;
12017*67e74705SXin Li }
12018*67e74705SXin Li
12019*67e74705SXin Li if (IsFixed && Prev->isFixed()) {
12020*67e74705SXin Li if (!EnumUnderlyingTy->isDependentType() &&
12021*67e74705SXin Li !Prev->getIntegerType()->isDependentType() &&
12022*67e74705SXin Li !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12023*67e74705SXin Li Prev->getIntegerType())) {
12024*67e74705SXin Li // TODO: Highlight the underlying type of the redeclaration.
12025*67e74705SXin Li Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12026*67e74705SXin Li << EnumUnderlyingTy << Prev->getIntegerType();
12027*67e74705SXin Li Diag(Prev->getLocation(), diag::note_previous_declaration)
12028*67e74705SXin Li << Prev->getIntegerTypeRange();
12029*67e74705SXin Li return true;
12030*67e74705SXin Li }
12031*67e74705SXin Li } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12032*67e74705SXin Li ;
12033*67e74705SXin Li } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12034*67e74705SXin Li ;
12035*67e74705SXin Li } else if (IsFixed != Prev->isFixed()) {
12036*67e74705SXin Li Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12037*67e74705SXin Li << Prev->isFixed();
12038*67e74705SXin Li Diag(Prev->getLocation(), diag::note_previous_declaration);
12039*67e74705SXin Li return true;
12040*67e74705SXin Li }
12041*67e74705SXin Li
12042*67e74705SXin Li return false;
12043*67e74705SXin Li }
12044*67e74705SXin Li
12045*67e74705SXin Li /// \brief Get diagnostic %select index for tag kind for
12046*67e74705SXin Li /// redeclaration diagnostic message.
12047*67e74705SXin Li /// WARNING: Indexes apply to particular diagnostics only!
12048*67e74705SXin Li ///
12049*67e74705SXin Li /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)12050*67e74705SXin Li static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12051*67e74705SXin Li switch (Tag) {
12052*67e74705SXin Li case TTK_Struct: return 0;
12053*67e74705SXin Li case TTK_Interface: return 1;
12054*67e74705SXin Li case TTK_Class: return 2;
12055*67e74705SXin Li default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12056*67e74705SXin Li }
12057*67e74705SXin Li }
12058*67e74705SXin Li
12059*67e74705SXin Li /// \brief Determine if tag kind is a class-key compatible with
12060*67e74705SXin Li /// class for redeclaration (class, struct, or __interface).
12061*67e74705SXin Li ///
12062*67e74705SXin Li /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)12063*67e74705SXin Li static bool isClassCompatTagKind(TagTypeKind Tag)
12064*67e74705SXin Li {
12065*67e74705SXin Li return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12066*67e74705SXin Li }
12067*67e74705SXin Li
12068*67e74705SXin Li /// \brief Determine whether a tag with a given kind is acceptable
12069*67e74705SXin Li /// as a redeclaration of the given tag declaration.
12070*67e74705SXin Li ///
12071*67e74705SXin Li /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)12072*67e74705SXin Li bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12073*67e74705SXin Li TagTypeKind NewTag, bool isDefinition,
12074*67e74705SXin Li SourceLocation NewTagLoc,
12075*67e74705SXin Li const IdentifierInfo *Name) {
12076*67e74705SXin Li // C++ [dcl.type.elab]p3:
12077*67e74705SXin Li // The class-key or enum keyword present in the
12078*67e74705SXin Li // elaborated-type-specifier shall agree in kind with the
12079*67e74705SXin Li // declaration to which the name in the elaborated-type-specifier
12080*67e74705SXin Li // refers. This rule also applies to the form of
12081*67e74705SXin Li // elaborated-type-specifier that declares a class-name or
12082*67e74705SXin Li // friend class since it can be construed as referring to the
12083*67e74705SXin Li // definition of the class. Thus, in any
12084*67e74705SXin Li // elaborated-type-specifier, the enum keyword shall be used to
12085*67e74705SXin Li // refer to an enumeration (7.2), the union class-key shall be
12086*67e74705SXin Li // used to refer to a union (clause 9), and either the class or
12087*67e74705SXin Li // struct class-key shall be used to refer to a class (clause 9)
12088*67e74705SXin Li // declared using the class or struct class-key.
12089*67e74705SXin Li TagTypeKind OldTag = Previous->getTagKind();
12090*67e74705SXin Li if (!isDefinition || !isClassCompatTagKind(NewTag))
12091*67e74705SXin Li if (OldTag == NewTag)
12092*67e74705SXin Li return true;
12093*67e74705SXin Li
12094*67e74705SXin Li if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12095*67e74705SXin Li // Warn about the struct/class tag mismatch.
12096*67e74705SXin Li bool isTemplate = false;
12097*67e74705SXin Li if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12098*67e74705SXin Li isTemplate = Record->getDescribedClassTemplate();
12099*67e74705SXin Li
12100*67e74705SXin Li if (!ActiveTemplateInstantiations.empty()) {
12101*67e74705SXin Li // In a template instantiation, do not offer fix-its for tag mismatches
12102*67e74705SXin Li // since they usually mess up the template instead of fixing the problem.
12103*67e74705SXin Li Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12104*67e74705SXin Li << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12105*67e74705SXin Li << getRedeclDiagFromTagKind(OldTag);
12106*67e74705SXin Li return true;
12107*67e74705SXin Li }
12108*67e74705SXin Li
12109*67e74705SXin Li if (isDefinition) {
12110*67e74705SXin Li // On definitions, check previous tags and issue a fix-it for each
12111*67e74705SXin Li // one that doesn't match the current tag.
12112*67e74705SXin Li if (Previous->getDefinition()) {
12113*67e74705SXin Li // Don't suggest fix-its for redefinitions.
12114*67e74705SXin Li return true;
12115*67e74705SXin Li }
12116*67e74705SXin Li
12117*67e74705SXin Li bool previousMismatch = false;
12118*67e74705SXin Li for (auto I : Previous->redecls()) {
12119*67e74705SXin Li if (I->getTagKind() != NewTag) {
12120*67e74705SXin Li if (!previousMismatch) {
12121*67e74705SXin Li previousMismatch = true;
12122*67e74705SXin Li Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12123*67e74705SXin Li << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12124*67e74705SXin Li << getRedeclDiagFromTagKind(I->getTagKind());
12125*67e74705SXin Li }
12126*67e74705SXin Li Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12127*67e74705SXin Li << getRedeclDiagFromTagKind(NewTag)
12128*67e74705SXin Li << FixItHint::CreateReplacement(I->getInnerLocStart(),
12129*67e74705SXin Li TypeWithKeyword::getTagTypeKindName(NewTag));
12130*67e74705SXin Li }
12131*67e74705SXin Li }
12132*67e74705SXin Li return true;
12133*67e74705SXin Li }
12134*67e74705SXin Li
12135*67e74705SXin Li // Check for a previous definition. If current tag and definition
12136*67e74705SXin Li // are same type, do nothing. If no definition, but disagree with
12137*67e74705SXin Li // with previous tag type, give a warning, but no fix-it.
12138*67e74705SXin Li const TagDecl *Redecl = Previous->getDefinition() ?
12139*67e74705SXin Li Previous->getDefinition() : Previous;
12140*67e74705SXin Li if (Redecl->getTagKind() == NewTag) {
12141*67e74705SXin Li return true;
12142*67e74705SXin Li }
12143*67e74705SXin Li
12144*67e74705SXin Li Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12145*67e74705SXin Li << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12146*67e74705SXin Li << getRedeclDiagFromTagKind(OldTag);
12147*67e74705SXin Li Diag(Redecl->getLocation(), diag::note_previous_use);
12148*67e74705SXin Li
12149*67e74705SXin Li // If there is a previous definition, suggest a fix-it.
12150*67e74705SXin Li if (Previous->getDefinition()) {
12151*67e74705SXin Li Diag(NewTagLoc, diag::note_struct_class_suggestion)
12152*67e74705SXin Li << getRedeclDiagFromTagKind(Redecl->getTagKind())
12153*67e74705SXin Li << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12154*67e74705SXin Li TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12155*67e74705SXin Li }
12156*67e74705SXin Li
12157*67e74705SXin Li return true;
12158*67e74705SXin Li }
12159*67e74705SXin Li return false;
12160*67e74705SXin Li }
12161*67e74705SXin Li
12162*67e74705SXin Li /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12163*67e74705SXin Li /// from an outer enclosing namespace or file scope inside a friend declaration.
12164*67e74705SXin Li /// This should provide the commented out code in the following snippet:
12165*67e74705SXin Li /// namespace N {
12166*67e74705SXin Li /// struct X;
12167*67e74705SXin Li /// namespace M {
12168*67e74705SXin Li /// struct Y { friend struct /*N::*/ X; };
12169*67e74705SXin Li /// }
12170*67e74705SXin Li /// }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)12171*67e74705SXin Li static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12172*67e74705SXin Li SourceLocation NameLoc) {
12173*67e74705SXin Li // While the decl is in a namespace, do repeated lookup of that name and see
12174*67e74705SXin Li // if we get the same namespace back. If we do not, continue until
12175*67e74705SXin Li // translation unit scope, at which point we have a fully qualified NNS.
12176*67e74705SXin Li SmallVector<IdentifierInfo *, 4> Namespaces;
12177*67e74705SXin Li DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12178*67e74705SXin Li for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12179*67e74705SXin Li // This tag should be declared in a namespace, which can only be enclosed by
12180*67e74705SXin Li // other namespaces. Bail if there's an anonymous namespace in the chain.
12181*67e74705SXin Li NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12182*67e74705SXin Li if (!Namespace || Namespace->isAnonymousNamespace())
12183*67e74705SXin Li return FixItHint();
12184*67e74705SXin Li IdentifierInfo *II = Namespace->getIdentifier();
12185*67e74705SXin Li Namespaces.push_back(II);
12186*67e74705SXin Li NamedDecl *Lookup = SemaRef.LookupSingleName(
12187*67e74705SXin Li S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12188*67e74705SXin Li if (Lookup == Namespace)
12189*67e74705SXin Li break;
12190*67e74705SXin Li }
12191*67e74705SXin Li
12192*67e74705SXin Li // Once we have all the namespaces, reverse them to go outermost first, and
12193*67e74705SXin Li // build an NNS.
12194*67e74705SXin Li SmallString<64> Insertion;
12195*67e74705SXin Li llvm::raw_svector_ostream OS(Insertion);
12196*67e74705SXin Li if (DC->isTranslationUnit())
12197*67e74705SXin Li OS << "::";
12198*67e74705SXin Li std::reverse(Namespaces.begin(), Namespaces.end());
12199*67e74705SXin Li for (auto *II : Namespaces)
12200*67e74705SXin Li OS << II->getName() << "::";
12201*67e74705SXin Li return FixItHint::CreateInsertion(NameLoc, Insertion);
12202*67e74705SXin Li }
12203*67e74705SXin Li
12204*67e74705SXin Li /// \brief Determine whether a tag originally declared in context \p OldDC can
12205*67e74705SXin Li /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12206*67e74705SXin Li /// found a declaration in \p OldDC as a previous decl, perhaps through a
12207*67e74705SXin Li /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)12208*67e74705SXin Li static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12209*67e74705SXin Li DeclContext *NewDC) {
12210*67e74705SXin Li OldDC = OldDC->getRedeclContext();
12211*67e74705SXin Li NewDC = NewDC->getRedeclContext();
12212*67e74705SXin Li
12213*67e74705SXin Li if (OldDC->Equals(NewDC))
12214*67e74705SXin Li return true;
12215*67e74705SXin Li
12216*67e74705SXin Li // In MSVC mode, we allow a redeclaration if the contexts are related (either
12217*67e74705SXin Li // encloses the other).
12218*67e74705SXin Li if (S.getLangOpts().MSVCCompat &&
12219*67e74705SXin Li (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12220*67e74705SXin Li return true;
12221*67e74705SXin Li
12222*67e74705SXin Li return false;
12223*67e74705SXin Li }
12224*67e74705SXin Li
12225*67e74705SXin Li /// Find the DeclContext in which a tag is implicitly declared if we see an
12226*67e74705SXin Li /// elaborated type specifier in the specified context, and lookup finds
12227*67e74705SXin Li /// nothing.
getTagInjectionContext(DeclContext * DC)12228*67e74705SXin Li static DeclContext *getTagInjectionContext(DeclContext *DC) {
12229*67e74705SXin Li while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12230*67e74705SXin Li DC = DC->getParent();
12231*67e74705SXin Li return DC;
12232*67e74705SXin Li }
12233*67e74705SXin Li
12234*67e74705SXin Li /// Find the Scope in which a tag is implicitly declared if we see an
12235*67e74705SXin Li /// elaborated type specifier in the specified context, and lookup finds
12236*67e74705SXin Li /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)12237*67e74705SXin Li static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12238*67e74705SXin Li while (S->isClassScope() ||
12239*67e74705SXin Li (LangOpts.CPlusPlus &&
12240*67e74705SXin Li S->isFunctionPrototypeScope()) ||
12241*67e74705SXin Li ((S->getFlags() & Scope::DeclScope) == 0) ||
12242*67e74705SXin Li (S->getEntity() && S->getEntity()->isTransparentContext()))
12243*67e74705SXin Li S = S->getParent();
12244*67e74705SXin Li return S;
12245*67e74705SXin Li }
12246*67e74705SXin Li
12247*67e74705SXin Li /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
12248*67e74705SXin Li /// former case, Name will be non-null. In the later case, Name will be null.
12249*67e74705SXin Li /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12250*67e74705SXin Li /// reference/declaration/definition of a tag.
12251*67e74705SXin Li ///
12252*67e74705SXin Li /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12253*67e74705SXin Li /// trailing-type-specifier) other than one in an alias-declaration.
12254*67e74705SXin Li ///
12255*67e74705SXin Li /// \param SkipBody If non-null, will be set to indicate if the caller should
12256*67e74705SXin Li /// skip the definition of this tag and treat it as if it were a declaration.
ActOnTag(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,AccessSpecifier AS,SourceLocation ModulePrivateLoc,MultiTemplateParamsArg TemplateParameterLists,bool & OwnedDecl,bool & IsDependent,SourceLocation ScopedEnumKWLoc,bool ScopedEnumUsesClassTag,TypeResult UnderlyingType,bool IsTypeSpecifier,SkipBodyInfo * SkipBody)12257*67e74705SXin Li Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12258*67e74705SXin Li SourceLocation KWLoc, CXXScopeSpec &SS,
12259*67e74705SXin Li IdentifierInfo *Name, SourceLocation NameLoc,
12260*67e74705SXin Li AttributeList *Attr, AccessSpecifier AS,
12261*67e74705SXin Li SourceLocation ModulePrivateLoc,
12262*67e74705SXin Li MultiTemplateParamsArg TemplateParameterLists,
12263*67e74705SXin Li bool &OwnedDecl, bool &IsDependent,
12264*67e74705SXin Li SourceLocation ScopedEnumKWLoc,
12265*67e74705SXin Li bool ScopedEnumUsesClassTag,
12266*67e74705SXin Li TypeResult UnderlyingType,
12267*67e74705SXin Li bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12268*67e74705SXin Li // If this is not a definition, it must have a name.
12269*67e74705SXin Li IdentifierInfo *OrigName = Name;
12270*67e74705SXin Li assert((Name != nullptr || TUK == TUK_Definition) &&
12271*67e74705SXin Li "Nameless record must be a definition!");
12272*67e74705SXin Li assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12273*67e74705SXin Li
12274*67e74705SXin Li OwnedDecl = false;
12275*67e74705SXin Li TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12276*67e74705SXin Li bool ScopedEnum = ScopedEnumKWLoc.isValid();
12277*67e74705SXin Li
12278*67e74705SXin Li // FIXME: Check explicit specializations more carefully.
12279*67e74705SXin Li bool isExplicitSpecialization = false;
12280*67e74705SXin Li bool Invalid = false;
12281*67e74705SXin Li
12282*67e74705SXin Li // We only need to do this matching if we have template parameters
12283*67e74705SXin Li // or a scope specifier, which also conveniently avoids this work
12284*67e74705SXin Li // for non-C++ cases.
12285*67e74705SXin Li if (TemplateParameterLists.size() > 0 ||
12286*67e74705SXin Li (SS.isNotEmpty() && TUK != TUK_Reference)) {
12287*67e74705SXin Li if (TemplateParameterList *TemplateParams =
12288*67e74705SXin Li MatchTemplateParametersToScopeSpecifier(
12289*67e74705SXin Li KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12290*67e74705SXin Li TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12291*67e74705SXin Li if (Kind == TTK_Enum) {
12292*67e74705SXin Li Diag(KWLoc, diag::err_enum_template);
12293*67e74705SXin Li return nullptr;
12294*67e74705SXin Li }
12295*67e74705SXin Li
12296*67e74705SXin Li if (TemplateParams->size() > 0) {
12297*67e74705SXin Li // This is a declaration or definition of a class template (which may
12298*67e74705SXin Li // be a member of another template).
12299*67e74705SXin Li
12300*67e74705SXin Li if (Invalid)
12301*67e74705SXin Li return nullptr;
12302*67e74705SXin Li
12303*67e74705SXin Li OwnedDecl = false;
12304*67e74705SXin Li DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12305*67e74705SXin Li SS, Name, NameLoc, Attr,
12306*67e74705SXin Li TemplateParams, AS,
12307*67e74705SXin Li ModulePrivateLoc,
12308*67e74705SXin Li /*FriendLoc*/SourceLocation(),
12309*67e74705SXin Li TemplateParameterLists.size()-1,
12310*67e74705SXin Li TemplateParameterLists.data(),
12311*67e74705SXin Li SkipBody);
12312*67e74705SXin Li return Result.get();
12313*67e74705SXin Li } else {
12314*67e74705SXin Li // The "template<>" header is extraneous.
12315*67e74705SXin Li Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12316*67e74705SXin Li << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12317*67e74705SXin Li isExplicitSpecialization = true;
12318*67e74705SXin Li }
12319*67e74705SXin Li }
12320*67e74705SXin Li }
12321*67e74705SXin Li
12322*67e74705SXin Li // Figure out the underlying type if this a enum declaration. We need to do
12323*67e74705SXin Li // this early, because it's needed to detect if this is an incompatible
12324*67e74705SXin Li // redeclaration.
12325*67e74705SXin Li llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12326*67e74705SXin Li bool EnumUnderlyingIsImplicit = false;
12327*67e74705SXin Li
12328*67e74705SXin Li if (Kind == TTK_Enum) {
12329*67e74705SXin Li if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12330*67e74705SXin Li // No underlying type explicitly specified, or we failed to parse the
12331*67e74705SXin Li // type, default to int.
12332*67e74705SXin Li EnumUnderlying = Context.IntTy.getTypePtr();
12333*67e74705SXin Li else if (UnderlyingType.get()) {
12334*67e74705SXin Li // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12335*67e74705SXin Li // integral type; any cv-qualification is ignored.
12336*67e74705SXin Li TypeSourceInfo *TI = nullptr;
12337*67e74705SXin Li GetTypeFromParser(UnderlyingType.get(), &TI);
12338*67e74705SXin Li EnumUnderlying = TI;
12339*67e74705SXin Li
12340*67e74705SXin Li if (CheckEnumUnderlyingType(TI))
12341*67e74705SXin Li // Recover by falling back to int.
12342*67e74705SXin Li EnumUnderlying = Context.IntTy.getTypePtr();
12343*67e74705SXin Li
12344*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12345*67e74705SXin Li UPPC_FixedUnderlyingType))
12346*67e74705SXin Li EnumUnderlying = Context.IntTy.getTypePtr();
12347*67e74705SXin Li
12348*67e74705SXin Li } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12349*67e74705SXin Li if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12350*67e74705SXin Li // Microsoft enums are always of int type.
12351*67e74705SXin Li EnumUnderlying = Context.IntTy.getTypePtr();
12352*67e74705SXin Li EnumUnderlyingIsImplicit = true;
12353*67e74705SXin Li }
12354*67e74705SXin Li }
12355*67e74705SXin Li }
12356*67e74705SXin Li
12357*67e74705SXin Li DeclContext *SearchDC = CurContext;
12358*67e74705SXin Li DeclContext *DC = CurContext;
12359*67e74705SXin Li bool isStdBadAlloc = false;
12360*67e74705SXin Li
12361*67e74705SXin Li RedeclarationKind Redecl = ForRedeclaration;
12362*67e74705SXin Li if (TUK == TUK_Friend || TUK == TUK_Reference)
12363*67e74705SXin Li Redecl = NotForRedeclaration;
12364*67e74705SXin Li
12365*67e74705SXin Li LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12366*67e74705SXin Li if (Name && SS.isNotEmpty()) {
12367*67e74705SXin Li // We have a nested-name tag ('struct foo::bar').
12368*67e74705SXin Li
12369*67e74705SXin Li // Check for invalid 'foo::'.
12370*67e74705SXin Li if (SS.isInvalid()) {
12371*67e74705SXin Li Name = nullptr;
12372*67e74705SXin Li goto CreateNewDecl;
12373*67e74705SXin Li }
12374*67e74705SXin Li
12375*67e74705SXin Li // If this is a friend or a reference to a class in a dependent
12376*67e74705SXin Li // context, don't try to make a decl for it.
12377*67e74705SXin Li if (TUK == TUK_Friend || TUK == TUK_Reference) {
12378*67e74705SXin Li DC = computeDeclContext(SS, false);
12379*67e74705SXin Li if (!DC) {
12380*67e74705SXin Li IsDependent = true;
12381*67e74705SXin Li return nullptr;
12382*67e74705SXin Li }
12383*67e74705SXin Li } else {
12384*67e74705SXin Li DC = computeDeclContext(SS, true);
12385*67e74705SXin Li if (!DC) {
12386*67e74705SXin Li Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12387*67e74705SXin Li << SS.getRange();
12388*67e74705SXin Li return nullptr;
12389*67e74705SXin Li }
12390*67e74705SXin Li }
12391*67e74705SXin Li
12392*67e74705SXin Li if (RequireCompleteDeclContext(SS, DC))
12393*67e74705SXin Li return nullptr;
12394*67e74705SXin Li
12395*67e74705SXin Li SearchDC = DC;
12396*67e74705SXin Li // Look-up name inside 'foo::'.
12397*67e74705SXin Li LookupQualifiedName(Previous, DC);
12398*67e74705SXin Li
12399*67e74705SXin Li if (Previous.isAmbiguous())
12400*67e74705SXin Li return nullptr;
12401*67e74705SXin Li
12402*67e74705SXin Li if (Previous.empty()) {
12403*67e74705SXin Li // Name lookup did not find anything. However, if the
12404*67e74705SXin Li // nested-name-specifier refers to the current instantiation,
12405*67e74705SXin Li // and that current instantiation has any dependent base
12406*67e74705SXin Li // classes, we might find something at instantiation time: treat
12407*67e74705SXin Li // this as a dependent elaborated-type-specifier.
12408*67e74705SXin Li // But this only makes any sense for reference-like lookups.
12409*67e74705SXin Li if (Previous.wasNotFoundInCurrentInstantiation() &&
12410*67e74705SXin Li (TUK == TUK_Reference || TUK == TUK_Friend)) {
12411*67e74705SXin Li IsDependent = true;
12412*67e74705SXin Li return nullptr;
12413*67e74705SXin Li }
12414*67e74705SXin Li
12415*67e74705SXin Li // A tag 'foo::bar' must already exist.
12416*67e74705SXin Li Diag(NameLoc, diag::err_not_tag_in_scope)
12417*67e74705SXin Li << Kind << Name << DC << SS.getRange();
12418*67e74705SXin Li Name = nullptr;
12419*67e74705SXin Li Invalid = true;
12420*67e74705SXin Li goto CreateNewDecl;
12421*67e74705SXin Li }
12422*67e74705SXin Li } else if (Name) {
12423*67e74705SXin Li // C++14 [class.mem]p14:
12424*67e74705SXin Li // If T is the name of a class, then each of the following shall have a
12425*67e74705SXin Li // name different from T:
12426*67e74705SXin Li // -- every member of class T that is itself a type
12427*67e74705SXin Li if (TUK != TUK_Reference && TUK != TUK_Friend &&
12428*67e74705SXin Li DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12429*67e74705SXin Li return nullptr;
12430*67e74705SXin Li
12431*67e74705SXin Li // If this is a named struct, check to see if there was a previous forward
12432*67e74705SXin Li // declaration or definition.
12433*67e74705SXin Li // FIXME: We're looking into outer scopes here, even when we
12434*67e74705SXin Li // shouldn't be. Doing so can result in ambiguities that we
12435*67e74705SXin Li // shouldn't be diagnosing.
12436*67e74705SXin Li LookupName(Previous, S);
12437*67e74705SXin Li
12438*67e74705SXin Li // When declaring or defining a tag, ignore ambiguities introduced
12439*67e74705SXin Li // by types using'ed into this scope.
12440*67e74705SXin Li if (Previous.isAmbiguous() &&
12441*67e74705SXin Li (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12442*67e74705SXin Li LookupResult::Filter F = Previous.makeFilter();
12443*67e74705SXin Li while (F.hasNext()) {
12444*67e74705SXin Li NamedDecl *ND = F.next();
12445*67e74705SXin Li if (!ND->getDeclContext()->getRedeclContext()->Equals(
12446*67e74705SXin Li SearchDC->getRedeclContext()))
12447*67e74705SXin Li F.erase();
12448*67e74705SXin Li }
12449*67e74705SXin Li F.done();
12450*67e74705SXin Li }
12451*67e74705SXin Li
12452*67e74705SXin Li // C++11 [namespace.memdef]p3:
12453*67e74705SXin Li // If the name in a friend declaration is neither qualified nor
12454*67e74705SXin Li // a template-id and the declaration is a function or an
12455*67e74705SXin Li // elaborated-type-specifier, the lookup to determine whether
12456*67e74705SXin Li // the entity has been previously declared shall not consider
12457*67e74705SXin Li // any scopes outside the innermost enclosing namespace.
12458*67e74705SXin Li //
12459*67e74705SXin Li // MSVC doesn't implement the above rule for types, so a friend tag
12460*67e74705SXin Li // declaration may be a redeclaration of a type declared in an enclosing
12461*67e74705SXin Li // scope. They do implement this rule for friend functions.
12462*67e74705SXin Li //
12463*67e74705SXin Li // Does it matter that this should be by scope instead of by
12464*67e74705SXin Li // semantic context?
12465*67e74705SXin Li if (!Previous.empty() && TUK == TUK_Friend) {
12466*67e74705SXin Li DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12467*67e74705SXin Li LookupResult::Filter F = Previous.makeFilter();
12468*67e74705SXin Li bool FriendSawTagOutsideEnclosingNamespace = false;
12469*67e74705SXin Li while (F.hasNext()) {
12470*67e74705SXin Li NamedDecl *ND = F.next();
12471*67e74705SXin Li DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12472*67e74705SXin Li if (DC->isFileContext() &&
12473*67e74705SXin Li !EnclosingNS->Encloses(ND->getDeclContext())) {
12474*67e74705SXin Li if (getLangOpts().MSVCCompat)
12475*67e74705SXin Li FriendSawTagOutsideEnclosingNamespace = true;
12476*67e74705SXin Li else
12477*67e74705SXin Li F.erase();
12478*67e74705SXin Li }
12479*67e74705SXin Li }
12480*67e74705SXin Li F.done();
12481*67e74705SXin Li
12482*67e74705SXin Li // Diagnose this MSVC extension in the easy case where lookup would have
12483*67e74705SXin Li // unambiguously found something outside the enclosing namespace.
12484*67e74705SXin Li if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12485*67e74705SXin Li NamedDecl *ND = Previous.getFoundDecl();
12486*67e74705SXin Li Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12487*67e74705SXin Li << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12488*67e74705SXin Li }
12489*67e74705SXin Li }
12490*67e74705SXin Li
12491*67e74705SXin Li // Note: there used to be some attempt at recovery here.
12492*67e74705SXin Li if (Previous.isAmbiguous())
12493*67e74705SXin Li return nullptr;
12494*67e74705SXin Li
12495*67e74705SXin Li if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12496*67e74705SXin Li // FIXME: This makes sure that we ignore the contexts associated
12497*67e74705SXin Li // with C structs, unions, and enums when looking for a matching
12498*67e74705SXin Li // tag declaration or definition. See the similar lookup tweak
12499*67e74705SXin Li // in Sema::LookupName; is there a better way to deal with this?
12500*67e74705SXin Li while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12501*67e74705SXin Li SearchDC = SearchDC->getParent();
12502*67e74705SXin Li }
12503*67e74705SXin Li }
12504*67e74705SXin Li
12505*67e74705SXin Li if (Previous.isSingleResult() &&
12506*67e74705SXin Li Previous.getFoundDecl()->isTemplateParameter()) {
12507*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
12508*67e74705SXin Li DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12509*67e74705SXin Li // Just pretend that we didn't see the previous declaration.
12510*67e74705SXin Li Previous.clear();
12511*67e74705SXin Li }
12512*67e74705SXin Li
12513*67e74705SXin Li if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12514*67e74705SXin Li DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12515*67e74705SXin Li // This is a declaration of or a reference to "std::bad_alloc".
12516*67e74705SXin Li isStdBadAlloc = true;
12517*67e74705SXin Li
12518*67e74705SXin Li if (Previous.empty() && StdBadAlloc) {
12519*67e74705SXin Li // std::bad_alloc has been implicitly declared (but made invisible to
12520*67e74705SXin Li // name lookup). Fill in this implicit declaration as the previous
12521*67e74705SXin Li // declaration, so that the declarations get chained appropriately.
12522*67e74705SXin Li Previous.addDecl(getStdBadAlloc());
12523*67e74705SXin Li }
12524*67e74705SXin Li }
12525*67e74705SXin Li
12526*67e74705SXin Li // If we didn't find a previous declaration, and this is a reference
12527*67e74705SXin Li // (or friend reference), move to the correct scope. In C++, we
12528*67e74705SXin Li // also need to do a redeclaration lookup there, just in case
12529*67e74705SXin Li // there's a shadow friend decl.
12530*67e74705SXin Li if (Name && Previous.empty() &&
12531*67e74705SXin Li (TUK == TUK_Reference || TUK == TUK_Friend)) {
12532*67e74705SXin Li if (Invalid) goto CreateNewDecl;
12533*67e74705SXin Li assert(SS.isEmpty());
12534*67e74705SXin Li
12535*67e74705SXin Li if (TUK == TUK_Reference) {
12536*67e74705SXin Li // C++ [basic.scope.pdecl]p5:
12537*67e74705SXin Li // -- for an elaborated-type-specifier of the form
12538*67e74705SXin Li //
12539*67e74705SXin Li // class-key identifier
12540*67e74705SXin Li //
12541*67e74705SXin Li // if the elaborated-type-specifier is used in the
12542*67e74705SXin Li // decl-specifier-seq or parameter-declaration-clause of a
12543*67e74705SXin Li // function defined in namespace scope, the identifier is
12544*67e74705SXin Li // declared as a class-name in the namespace that contains
12545*67e74705SXin Li // the declaration; otherwise, except as a friend
12546*67e74705SXin Li // declaration, the identifier is declared in the smallest
12547*67e74705SXin Li // non-class, non-function-prototype scope that contains the
12548*67e74705SXin Li // declaration.
12549*67e74705SXin Li //
12550*67e74705SXin Li // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12551*67e74705SXin Li // C structs and unions.
12552*67e74705SXin Li //
12553*67e74705SXin Li // It is an error in C++ to declare (rather than define) an enum
12554*67e74705SXin Li // type, including via an elaborated type specifier. We'll
12555*67e74705SXin Li // diagnose that later; for now, declare the enum in the same
12556*67e74705SXin Li // scope as we would have picked for any other tag type.
12557*67e74705SXin Li //
12558*67e74705SXin Li // GNU C also supports this behavior as part of its incomplete
12559*67e74705SXin Li // enum types extension, while GNU C++ does not.
12560*67e74705SXin Li //
12561*67e74705SXin Li // Find the context where we'll be declaring the tag.
12562*67e74705SXin Li // FIXME: We would like to maintain the current DeclContext as the
12563*67e74705SXin Li // lexical context,
12564*67e74705SXin Li SearchDC = getTagInjectionContext(SearchDC);
12565*67e74705SXin Li
12566*67e74705SXin Li // Find the scope where we'll be declaring the tag.
12567*67e74705SXin Li S = getTagInjectionScope(S, getLangOpts());
12568*67e74705SXin Li } else {
12569*67e74705SXin Li assert(TUK == TUK_Friend);
12570*67e74705SXin Li // C++ [namespace.memdef]p3:
12571*67e74705SXin Li // If a friend declaration in a non-local class first declares a
12572*67e74705SXin Li // class or function, the friend class or function is a member of
12573*67e74705SXin Li // the innermost enclosing namespace.
12574*67e74705SXin Li SearchDC = SearchDC->getEnclosingNamespaceContext();
12575*67e74705SXin Li }
12576*67e74705SXin Li
12577*67e74705SXin Li // In C++, we need to do a redeclaration lookup to properly
12578*67e74705SXin Li // diagnose some problems.
12579*67e74705SXin Li // FIXME: redeclaration lookup is also used (with and without C++) to find a
12580*67e74705SXin Li // hidden declaration so that we don't get ambiguity errors when using a
12581*67e74705SXin Li // type declared by an elaborated-type-specifier. In C that is not correct
12582*67e74705SXin Li // and we should instead merge compatible types found by lookup.
12583*67e74705SXin Li if (getLangOpts().CPlusPlus) {
12584*67e74705SXin Li Previous.setRedeclarationKind(ForRedeclaration);
12585*67e74705SXin Li LookupQualifiedName(Previous, SearchDC);
12586*67e74705SXin Li } else {
12587*67e74705SXin Li Previous.setRedeclarationKind(ForRedeclaration);
12588*67e74705SXin Li LookupName(Previous, S);
12589*67e74705SXin Li }
12590*67e74705SXin Li }
12591*67e74705SXin Li
12592*67e74705SXin Li // If we have a known previous declaration to use, then use it.
12593*67e74705SXin Li if (Previous.empty() && SkipBody && SkipBody->Previous)
12594*67e74705SXin Li Previous.addDecl(SkipBody->Previous);
12595*67e74705SXin Li
12596*67e74705SXin Li if (!Previous.empty()) {
12597*67e74705SXin Li NamedDecl *PrevDecl = Previous.getFoundDecl();
12598*67e74705SXin Li NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12599*67e74705SXin Li
12600*67e74705SXin Li // It's okay to have a tag decl in the same scope as a typedef
12601*67e74705SXin Li // which hides a tag decl in the same scope. Finding this
12602*67e74705SXin Li // insanity with a redeclaration lookup can only actually happen
12603*67e74705SXin Li // in C++.
12604*67e74705SXin Li //
12605*67e74705SXin Li // This is also okay for elaborated-type-specifiers, which is
12606*67e74705SXin Li // technically forbidden by the current standard but which is
12607*67e74705SXin Li // okay according to the likely resolution of an open issue;
12608*67e74705SXin Li // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12609*67e74705SXin Li if (getLangOpts().CPlusPlus) {
12610*67e74705SXin Li if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12611*67e74705SXin Li if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12612*67e74705SXin Li TagDecl *Tag = TT->getDecl();
12613*67e74705SXin Li if (Tag->getDeclName() == Name &&
12614*67e74705SXin Li Tag->getDeclContext()->getRedeclContext()
12615*67e74705SXin Li ->Equals(TD->getDeclContext()->getRedeclContext())) {
12616*67e74705SXin Li PrevDecl = Tag;
12617*67e74705SXin Li Previous.clear();
12618*67e74705SXin Li Previous.addDecl(Tag);
12619*67e74705SXin Li Previous.resolveKind();
12620*67e74705SXin Li }
12621*67e74705SXin Li }
12622*67e74705SXin Li }
12623*67e74705SXin Li }
12624*67e74705SXin Li
12625*67e74705SXin Li // If this is a redeclaration of a using shadow declaration, it must
12626*67e74705SXin Li // declare a tag in the same context. In MSVC mode, we allow a
12627*67e74705SXin Li // redefinition if either context is within the other.
12628*67e74705SXin Li if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12629*67e74705SXin Li auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12630*67e74705SXin Li if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12631*67e74705SXin Li isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12632*67e74705SXin Li !(OldTag && isAcceptableTagRedeclContext(
12633*67e74705SXin Li *this, OldTag->getDeclContext(), SearchDC))) {
12634*67e74705SXin Li Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12635*67e74705SXin Li Diag(Shadow->getTargetDecl()->getLocation(),
12636*67e74705SXin Li diag::note_using_decl_target);
12637*67e74705SXin Li Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12638*67e74705SXin Li << 0;
12639*67e74705SXin Li // Recover by ignoring the old declaration.
12640*67e74705SXin Li Previous.clear();
12641*67e74705SXin Li goto CreateNewDecl;
12642*67e74705SXin Li }
12643*67e74705SXin Li }
12644*67e74705SXin Li
12645*67e74705SXin Li if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12646*67e74705SXin Li // If this is a use of a previous tag, or if the tag is already declared
12647*67e74705SXin Li // in the same scope (so that the definition/declaration completes or
12648*67e74705SXin Li // rementions the tag), reuse the decl.
12649*67e74705SXin Li if (TUK == TUK_Reference || TUK == TUK_Friend ||
12650*67e74705SXin Li isDeclInScope(DirectPrevDecl, SearchDC, S,
12651*67e74705SXin Li SS.isNotEmpty() || isExplicitSpecialization)) {
12652*67e74705SXin Li // Make sure that this wasn't declared as an enum and now used as a
12653*67e74705SXin Li // struct or something similar.
12654*67e74705SXin Li if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12655*67e74705SXin Li TUK == TUK_Definition, KWLoc,
12656*67e74705SXin Li Name)) {
12657*67e74705SXin Li bool SafeToContinue
12658*67e74705SXin Li = (PrevTagDecl->getTagKind() != TTK_Enum &&
12659*67e74705SXin Li Kind != TTK_Enum);
12660*67e74705SXin Li if (SafeToContinue)
12661*67e74705SXin Li Diag(KWLoc, diag::err_use_with_wrong_tag)
12662*67e74705SXin Li << Name
12663*67e74705SXin Li << FixItHint::CreateReplacement(SourceRange(KWLoc),
12664*67e74705SXin Li PrevTagDecl->getKindName());
12665*67e74705SXin Li else
12666*67e74705SXin Li Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12667*67e74705SXin Li Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12668*67e74705SXin Li
12669*67e74705SXin Li if (SafeToContinue)
12670*67e74705SXin Li Kind = PrevTagDecl->getTagKind();
12671*67e74705SXin Li else {
12672*67e74705SXin Li // Recover by making this an anonymous redefinition.
12673*67e74705SXin Li Name = nullptr;
12674*67e74705SXin Li Previous.clear();
12675*67e74705SXin Li Invalid = true;
12676*67e74705SXin Li }
12677*67e74705SXin Li }
12678*67e74705SXin Li
12679*67e74705SXin Li if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12680*67e74705SXin Li const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12681*67e74705SXin Li
12682*67e74705SXin Li // If this is an elaborated-type-specifier for a scoped enumeration,
12683*67e74705SXin Li // the 'class' keyword is not necessary and not permitted.
12684*67e74705SXin Li if (TUK == TUK_Reference || TUK == TUK_Friend) {
12685*67e74705SXin Li if (ScopedEnum)
12686*67e74705SXin Li Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12687*67e74705SXin Li << PrevEnum->isScoped()
12688*67e74705SXin Li << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12689*67e74705SXin Li return PrevTagDecl;
12690*67e74705SXin Li }
12691*67e74705SXin Li
12692*67e74705SXin Li QualType EnumUnderlyingTy;
12693*67e74705SXin Li if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12694*67e74705SXin Li EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12695*67e74705SXin Li else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12696*67e74705SXin Li EnumUnderlyingTy = QualType(T, 0);
12697*67e74705SXin Li
12698*67e74705SXin Li // All conflicts with previous declarations are recovered by
12699*67e74705SXin Li // returning the previous declaration, unless this is a definition,
12700*67e74705SXin Li // in which case we want the caller to bail out.
12701*67e74705SXin Li if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12702*67e74705SXin Li ScopedEnum, EnumUnderlyingTy,
12703*67e74705SXin Li EnumUnderlyingIsImplicit, PrevEnum))
12704*67e74705SXin Li return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12705*67e74705SXin Li }
12706*67e74705SXin Li
12707*67e74705SXin Li // C++11 [class.mem]p1:
12708*67e74705SXin Li // A member shall not be declared twice in the member-specification,
12709*67e74705SXin Li // except that a nested class or member class template can be declared
12710*67e74705SXin Li // and then later defined.
12711*67e74705SXin Li if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12712*67e74705SXin Li S->isDeclScope(PrevDecl)) {
12713*67e74705SXin Li Diag(NameLoc, diag::ext_member_redeclared);
12714*67e74705SXin Li Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12715*67e74705SXin Li }
12716*67e74705SXin Li
12717*67e74705SXin Li if (!Invalid) {
12718*67e74705SXin Li // If this is a use, just return the declaration we found, unless
12719*67e74705SXin Li // we have attributes.
12720*67e74705SXin Li if (TUK == TUK_Reference || TUK == TUK_Friend) {
12721*67e74705SXin Li if (Attr) {
12722*67e74705SXin Li // FIXME: Diagnose these attributes. For now, we create a new
12723*67e74705SXin Li // declaration to hold them.
12724*67e74705SXin Li } else if (TUK == TUK_Reference &&
12725*67e74705SXin Li (PrevTagDecl->getFriendObjectKind() ==
12726*67e74705SXin Li Decl::FOK_Undeclared ||
12727*67e74705SXin Li PP.getModuleContainingLocation(
12728*67e74705SXin Li PrevDecl->getLocation()) !=
12729*67e74705SXin Li PP.getModuleContainingLocation(KWLoc)) &&
12730*67e74705SXin Li SS.isEmpty()) {
12731*67e74705SXin Li // This declaration is a reference to an existing entity, but
12732*67e74705SXin Li // has different visibility from that entity: it either makes
12733*67e74705SXin Li // a friend visible or it makes a type visible in a new module.
12734*67e74705SXin Li // In either case, create a new declaration. We only do this if
12735*67e74705SXin Li // the declaration would have meant the same thing if no prior
12736*67e74705SXin Li // declaration were found, that is, if it was found in the same
12737*67e74705SXin Li // scope where we would have injected a declaration.
12738*67e74705SXin Li if (!getTagInjectionContext(CurContext)->getRedeclContext()
12739*67e74705SXin Li ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12740*67e74705SXin Li return PrevTagDecl;
12741*67e74705SXin Li // This is in the injected scope, create a new declaration in
12742*67e74705SXin Li // that scope.
12743*67e74705SXin Li S = getTagInjectionScope(S, getLangOpts());
12744*67e74705SXin Li } else {
12745*67e74705SXin Li return PrevTagDecl;
12746*67e74705SXin Li }
12747*67e74705SXin Li }
12748*67e74705SXin Li
12749*67e74705SXin Li // Diagnose attempts to redefine a tag.
12750*67e74705SXin Li if (TUK == TUK_Definition) {
12751*67e74705SXin Li if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12752*67e74705SXin Li // If we're defining a specialization and the previous definition
12753*67e74705SXin Li // is from an implicit instantiation, don't emit an error
12754*67e74705SXin Li // here; we'll catch this in the general case below.
12755*67e74705SXin Li bool IsExplicitSpecializationAfterInstantiation = false;
12756*67e74705SXin Li if (isExplicitSpecialization) {
12757*67e74705SXin Li if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12758*67e74705SXin Li IsExplicitSpecializationAfterInstantiation =
12759*67e74705SXin Li RD->getTemplateSpecializationKind() !=
12760*67e74705SXin Li TSK_ExplicitSpecialization;
12761*67e74705SXin Li else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12762*67e74705SXin Li IsExplicitSpecializationAfterInstantiation =
12763*67e74705SXin Li ED->getTemplateSpecializationKind() !=
12764*67e74705SXin Li TSK_ExplicitSpecialization;
12765*67e74705SXin Li }
12766*67e74705SXin Li
12767*67e74705SXin Li NamedDecl *Hidden = nullptr;
12768*67e74705SXin Li if (SkipBody && getLangOpts().CPlusPlus &&
12769*67e74705SXin Li !hasVisibleDefinition(Def, &Hidden)) {
12770*67e74705SXin Li // There is a definition of this tag, but it is not visible. We
12771*67e74705SXin Li // explicitly make use of C++'s one definition rule here, and
12772*67e74705SXin Li // assume that this definition is identical to the hidden one
12773*67e74705SXin Li // we already have. Make the existing definition visible and
12774*67e74705SXin Li // use it in place of this one.
12775*67e74705SXin Li SkipBody->ShouldSkip = true;
12776*67e74705SXin Li makeMergedDefinitionVisible(Hidden, KWLoc);
12777*67e74705SXin Li return Def;
12778*67e74705SXin Li } else if (!IsExplicitSpecializationAfterInstantiation) {
12779*67e74705SXin Li // A redeclaration in function prototype scope in C isn't
12780*67e74705SXin Li // visible elsewhere, so merely issue a warning.
12781*67e74705SXin Li if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12782*67e74705SXin Li Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12783*67e74705SXin Li else
12784*67e74705SXin Li Diag(NameLoc, diag::err_redefinition) << Name;
12785*67e74705SXin Li Diag(Def->getLocation(), diag::note_previous_definition);
12786*67e74705SXin Li // If this is a redefinition, recover by making this
12787*67e74705SXin Li // struct be anonymous, which will make any later
12788*67e74705SXin Li // references get the previous definition.
12789*67e74705SXin Li Name = nullptr;
12790*67e74705SXin Li Previous.clear();
12791*67e74705SXin Li Invalid = true;
12792*67e74705SXin Li }
12793*67e74705SXin Li } else {
12794*67e74705SXin Li // If the type is currently being defined, complain
12795*67e74705SXin Li // about a nested redefinition.
12796*67e74705SXin Li auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12797*67e74705SXin Li if (TD->isBeingDefined()) {
12798*67e74705SXin Li Diag(NameLoc, diag::err_nested_redefinition) << Name;
12799*67e74705SXin Li Diag(PrevTagDecl->getLocation(),
12800*67e74705SXin Li diag::note_previous_definition);
12801*67e74705SXin Li Name = nullptr;
12802*67e74705SXin Li Previous.clear();
12803*67e74705SXin Li Invalid = true;
12804*67e74705SXin Li }
12805*67e74705SXin Li }
12806*67e74705SXin Li
12807*67e74705SXin Li // Okay, this is definition of a previously declared or referenced
12808*67e74705SXin Li // tag. We're going to create a new Decl for it.
12809*67e74705SXin Li }
12810*67e74705SXin Li
12811*67e74705SXin Li // Okay, we're going to make a redeclaration. If this is some kind
12812*67e74705SXin Li // of reference, make sure we build the redeclaration in the same DC
12813*67e74705SXin Li // as the original, and ignore the current access specifier.
12814*67e74705SXin Li if (TUK == TUK_Friend || TUK == TUK_Reference) {
12815*67e74705SXin Li SearchDC = PrevTagDecl->getDeclContext();
12816*67e74705SXin Li AS = AS_none;
12817*67e74705SXin Li }
12818*67e74705SXin Li }
12819*67e74705SXin Li // If we get here we have (another) forward declaration or we
12820*67e74705SXin Li // have a definition. Just create a new decl.
12821*67e74705SXin Li
12822*67e74705SXin Li } else {
12823*67e74705SXin Li // If we get here, this is a definition of a new tag type in a nested
12824*67e74705SXin Li // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12825*67e74705SXin Li // new decl/type. We set PrevDecl to NULL so that the entities
12826*67e74705SXin Li // have distinct types.
12827*67e74705SXin Li Previous.clear();
12828*67e74705SXin Li }
12829*67e74705SXin Li // If we get here, we're going to create a new Decl. If PrevDecl
12830*67e74705SXin Li // is non-NULL, it's a definition of the tag declared by
12831*67e74705SXin Li // PrevDecl. If it's NULL, we have a new definition.
12832*67e74705SXin Li
12833*67e74705SXin Li // Otherwise, PrevDecl is not a tag, but was found with tag
12834*67e74705SXin Li // lookup. This is only actually possible in C++, where a few
12835*67e74705SXin Li // things like templates still live in the tag namespace.
12836*67e74705SXin Li } else {
12837*67e74705SXin Li // Use a better diagnostic if an elaborated-type-specifier
12838*67e74705SXin Li // found the wrong kind of type on the first
12839*67e74705SXin Li // (non-redeclaration) lookup.
12840*67e74705SXin Li if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12841*67e74705SXin Li !Previous.isForRedeclaration()) {
12842*67e74705SXin Li unsigned Kind = 0;
12843*67e74705SXin Li if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12844*67e74705SXin Li else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12845*67e74705SXin Li else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12846*67e74705SXin Li Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12847*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_declared_at);
12848*67e74705SXin Li Invalid = true;
12849*67e74705SXin Li
12850*67e74705SXin Li // Otherwise, only diagnose if the declaration is in scope.
12851*67e74705SXin Li } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12852*67e74705SXin Li SS.isNotEmpty() || isExplicitSpecialization)) {
12853*67e74705SXin Li // do nothing
12854*67e74705SXin Li
12855*67e74705SXin Li // Diagnose implicit declarations introduced by elaborated types.
12856*67e74705SXin Li } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12857*67e74705SXin Li unsigned Kind = 0;
12858*67e74705SXin Li if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12859*67e74705SXin Li else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12860*67e74705SXin Li else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12861*67e74705SXin Li Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12862*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12863*67e74705SXin Li Invalid = true;
12864*67e74705SXin Li
12865*67e74705SXin Li // Otherwise it's a declaration. Call out a particularly common
12866*67e74705SXin Li // case here.
12867*67e74705SXin Li } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12868*67e74705SXin Li unsigned Kind = 0;
12869*67e74705SXin Li if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12870*67e74705SXin Li Diag(NameLoc, diag::err_tag_definition_of_typedef)
12871*67e74705SXin Li << Name << Kind << TND->getUnderlyingType();
12872*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12873*67e74705SXin Li Invalid = true;
12874*67e74705SXin Li
12875*67e74705SXin Li // Otherwise, diagnose.
12876*67e74705SXin Li } else {
12877*67e74705SXin Li // The tag name clashes with something else in the target scope,
12878*67e74705SXin Li // issue an error and recover by making this tag be anonymous.
12879*67e74705SXin Li Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12880*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12881*67e74705SXin Li Name = nullptr;
12882*67e74705SXin Li Invalid = true;
12883*67e74705SXin Li }
12884*67e74705SXin Li
12885*67e74705SXin Li // The existing declaration isn't relevant to us; we're in a
12886*67e74705SXin Li // new scope, so clear out the previous declaration.
12887*67e74705SXin Li Previous.clear();
12888*67e74705SXin Li }
12889*67e74705SXin Li }
12890*67e74705SXin Li
12891*67e74705SXin Li CreateNewDecl:
12892*67e74705SXin Li
12893*67e74705SXin Li TagDecl *PrevDecl = nullptr;
12894*67e74705SXin Li if (Previous.isSingleResult())
12895*67e74705SXin Li PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12896*67e74705SXin Li
12897*67e74705SXin Li // If there is an identifier, use the location of the identifier as the
12898*67e74705SXin Li // location of the decl, otherwise use the location of the struct/union
12899*67e74705SXin Li // keyword.
12900*67e74705SXin Li SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12901*67e74705SXin Li
12902*67e74705SXin Li // Otherwise, create a new declaration. If there is a previous
12903*67e74705SXin Li // declaration of the same entity, the two will be linked via
12904*67e74705SXin Li // PrevDecl.
12905*67e74705SXin Li TagDecl *New;
12906*67e74705SXin Li
12907*67e74705SXin Li bool IsForwardReference = false;
12908*67e74705SXin Li if (Kind == TTK_Enum) {
12909*67e74705SXin Li // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12910*67e74705SXin Li // enum X { A, B, C } D; D should chain to X.
12911*67e74705SXin Li New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12912*67e74705SXin Li cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12913*67e74705SXin Li ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12914*67e74705SXin Li // If this is an undefined enum, warn.
12915*67e74705SXin Li if (TUK != TUK_Definition && !Invalid) {
12916*67e74705SXin Li TagDecl *Def;
12917*67e74705SXin Li if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12918*67e74705SXin Li cast<EnumDecl>(New)->isFixed()) {
12919*67e74705SXin Li // C++0x: 7.2p2: opaque-enum-declaration.
12920*67e74705SXin Li // Conflicts are diagnosed above. Do nothing.
12921*67e74705SXin Li }
12922*67e74705SXin Li else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12923*67e74705SXin Li Diag(Loc, diag::ext_forward_ref_enum_def)
12924*67e74705SXin Li << New;
12925*67e74705SXin Li Diag(Def->getLocation(), diag::note_previous_definition);
12926*67e74705SXin Li } else {
12927*67e74705SXin Li unsigned DiagID = diag::ext_forward_ref_enum;
12928*67e74705SXin Li if (getLangOpts().MSVCCompat)
12929*67e74705SXin Li DiagID = diag::ext_ms_forward_ref_enum;
12930*67e74705SXin Li else if (getLangOpts().CPlusPlus)
12931*67e74705SXin Li DiagID = diag::err_forward_ref_enum;
12932*67e74705SXin Li Diag(Loc, DiagID);
12933*67e74705SXin Li
12934*67e74705SXin Li // If this is a forward-declared reference to an enumeration, make a
12935*67e74705SXin Li // note of it; we won't actually be introducing the declaration into
12936*67e74705SXin Li // the declaration context.
12937*67e74705SXin Li if (TUK == TUK_Reference)
12938*67e74705SXin Li IsForwardReference = true;
12939*67e74705SXin Li }
12940*67e74705SXin Li }
12941*67e74705SXin Li
12942*67e74705SXin Li if (EnumUnderlying) {
12943*67e74705SXin Li EnumDecl *ED = cast<EnumDecl>(New);
12944*67e74705SXin Li if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12945*67e74705SXin Li ED->setIntegerTypeSourceInfo(TI);
12946*67e74705SXin Li else
12947*67e74705SXin Li ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12948*67e74705SXin Li ED->setPromotionType(ED->getIntegerType());
12949*67e74705SXin Li }
12950*67e74705SXin Li } else {
12951*67e74705SXin Li // struct/union/class
12952*67e74705SXin Li
12953*67e74705SXin Li // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12954*67e74705SXin Li // struct X { int A; } D; D should chain to X.
12955*67e74705SXin Li if (getLangOpts().CPlusPlus) {
12956*67e74705SXin Li // FIXME: Look for a way to use RecordDecl for simple structs.
12957*67e74705SXin Li New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12958*67e74705SXin Li cast_or_null<CXXRecordDecl>(PrevDecl));
12959*67e74705SXin Li
12960*67e74705SXin Li if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12961*67e74705SXin Li StdBadAlloc = cast<CXXRecordDecl>(New);
12962*67e74705SXin Li } else
12963*67e74705SXin Li New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12964*67e74705SXin Li cast_or_null<RecordDecl>(PrevDecl));
12965*67e74705SXin Li }
12966*67e74705SXin Li
12967*67e74705SXin Li // C++11 [dcl.type]p3:
12968*67e74705SXin Li // A type-specifier-seq shall not define a class or enumeration [...].
12969*67e74705SXin Li if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12970*67e74705SXin Li Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12971*67e74705SXin Li << Context.getTagDeclType(New);
12972*67e74705SXin Li Invalid = true;
12973*67e74705SXin Li }
12974*67e74705SXin Li
12975*67e74705SXin Li // Maybe add qualifier info.
12976*67e74705SXin Li if (SS.isNotEmpty()) {
12977*67e74705SXin Li if (SS.isSet()) {
12978*67e74705SXin Li // If this is either a declaration or a definition, check the
12979*67e74705SXin Li // nested-name-specifier against the current context. We don't do this
12980*67e74705SXin Li // for explicit specializations, because they have similar checking
12981*67e74705SXin Li // (with more specific diagnostics) in the call to
12982*67e74705SXin Li // CheckMemberSpecialization, below.
12983*67e74705SXin Li if (!isExplicitSpecialization &&
12984*67e74705SXin Li (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12985*67e74705SXin Li diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12986*67e74705SXin Li Invalid = true;
12987*67e74705SXin Li
12988*67e74705SXin Li New->setQualifierInfo(SS.getWithLocInContext(Context));
12989*67e74705SXin Li if (TemplateParameterLists.size() > 0) {
12990*67e74705SXin Li New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12991*67e74705SXin Li }
12992*67e74705SXin Li }
12993*67e74705SXin Li else
12994*67e74705SXin Li Invalid = true;
12995*67e74705SXin Li }
12996*67e74705SXin Li
12997*67e74705SXin Li if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12998*67e74705SXin Li // Add alignment attributes if necessary; these attributes are checked when
12999*67e74705SXin Li // the ASTContext lays out the structure.
13000*67e74705SXin Li //
13001*67e74705SXin Li // It is important for implementing the correct semantics that this
13002*67e74705SXin Li // happen here (in act on tag decl). The #pragma pack stack is
13003*67e74705SXin Li // maintained as a result of parser callbacks which can occur at
13004*67e74705SXin Li // many points during the parsing of a struct declaration (because
13005*67e74705SXin Li // the #pragma tokens are effectively skipped over during the
13006*67e74705SXin Li // parsing of the struct).
13007*67e74705SXin Li if (TUK == TUK_Definition) {
13008*67e74705SXin Li AddAlignmentAttributesForRecord(RD);
13009*67e74705SXin Li AddMsStructLayoutForRecord(RD);
13010*67e74705SXin Li }
13011*67e74705SXin Li }
13012*67e74705SXin Li
13013*67e74705SXin Li if (ModulePrivateLoc.isValid()) {
13014*67e74705SXin Li if (isExplicitSpecialization)
13015*67e74705SXin Li Diag(New->getLocation(), diag::err_module_private_specialization)
13016*67e74705SXin Li << 2
13017*67e74705SXin Li << FixItHint::CreateRemoval(ModulePrivateLoc);
13018*67e74705SXin Li // __module_private__ does not apply to local classes. However, we only
13019*67e74705SXin Li // diagnose this as an error when the declaration specifiers are
13020*67e74705SXin Li // freestanding. Here, we just ignore the __module_private__.
13021*67e74705SXin Li else if (!SearchDC->isFunctionOrMethod())
13022*67e74705SXin Li New->setModulePrivate();
13023*67e74705SXin Li }
13024*67e74705SXin Li
13025*67e74705SXin Li // If this is a specialization of a member class (of a class template),
13026*67e74705SXin Li // check the specialization.
13027*67e74705SXin Li if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13028*67e74705SXin Li Invalid = true;
13029*67e74705SXin Li
13030*67e74705SXin Li // If we're declaring or defining a tag in function prototype scope in C,
13031*67e74705SXin Li // note that this type can only be used within the function and add it to
13032*67e74705SXin Li // the list of decls to inject into the function definition scope.
13033*67e74705SXin Li if ((Name || Kind == TTK_Enum) &&
13034*67e74705SXin Li getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13035*67e74705SXin Li if (getLangOpts().CPlusPlus) {
13036*67e74705SXin Li // C++ [dcl.fct]p6:
13037*67e74705SXin Li // Types shall not be defined in return or parameter types.
13038*67e74705SXin Li if (TUK == TUK_Definition && !IsTypeSpecifier) {
13039*67e74705SXin Li Diag(Loc, diag::err_type_defined_in_param_type)
13040*67e74705SXin Li << Name;
13041*67e74705SXin Li Invalid = true;
13042*67e74705SXin Li }
13043*67e74705SXin Li } else if (!PrevDecl) {
13044*67e74705SXin Li Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13045*67e74705SXin Li }
13046*67e74705SXin Li DeclsInPrototypeScope.push_back(New);
13047*67e74705SXin Li }
13048*67e74705SXin Li
13049*67e74705SXin Li if (Invalid)
13050*67e74705SXin Li New->setInvalidDecl();
13051*67e74705SXin Li
13052*67e74705SXin Li if (Attr)
13053*67e74705SXin Li ProcessDeclAttributeList(S, New, Attr);
13054*67e74705SXin Li
13055*67e74705SXin Li // Set the lexical context. If the tag has a C++ scope specifier, the
13056*67e74705SXin Li // lexical context will be different from the semantic context.
13057*67e74705SXin Li New->setLexicalDeclContext(CurContext);
13058*67e74705SXin Li
13059*67e74705SXin Li // Mark this as a friend decl if applicable.
13060*67e74705SXin Li // In Microsoft mode, a friend declaration also acts as a forward
13061*67e74705SXin Li // declaration so we always pass true to setObjectOfFriendDecl to make
13062*67e74705SXin Li // the tag name visible.
13063*67e74705SXin Li if (TUK == TUK_Friend)
13064*67e74705SXin Li New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13065*67e74705SXin Li
13066*67e74705SXin Li // Set the access specifier.
13067*67e74705SXin Li if (!Invalid && SearchDC->isRecord())
13068*67e74705SXin Li SetMemberAccessSpecifier(New, PrevDecl, AS);
13069*67e74705SXin Li
13070*67e74705SXin Li if (TUK == TUK_Definition)
13071*67e74705SXin Li New->startDefinition();
13072*67e74705SXin Li
13073*67e74705SXin Li // If this has an identifier, add it to the scope stack.
13074*67e74705SXin Li if (TUK == TUK_Friend) {
13075*67e74705SXin Li // We might be replacing an existing declaration in the lookup tables;
13076*67e74705SXin Li // if so, borrow its access specifier.
13077*67e74705SXin Li if (PrevDecl)
13078*67e74705SXin Li New->setAccess(PrevDecl->getAccess());
13079*67e74705SXin Li
13080*67e74705SXin Li DeclContext *DC = New->getDeclContext()->getRedeclContext();
13081*67e74705SXin Li DC->makeDeclVisibleInContext(New);
13082*67e74705SXin Li if (Name) // can be null along some error paths
13083*67e74705SXin Li if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13084*67e74705SXin Li PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13085*67e74705SXin Li } else if (Name) {
13086*67e74705SXin Li S = getNonFieldDeclScope(S);
13087*67e74705SXin Li PushOnScopeChains(New, S, !IsForwardReference);
13088*67e74705SXin Li if (IsForwardReference)
13089*67e74705SXin Li SearchDC->makeDeclVisibleInContext(New);
13090*67e74705SXin Li } else {
13091*67e74705SXin Li CurContext->addDecl(New);
13092*67e74705SXin Li }
13093*67e74705SXin Li
13094*67e74705SXin Li // If this is the C FILE type, notify the AST context.
13095*67e74705SXin Li if (IdentifierInfo *II = New->getIdentifier())
13096*67e74705SXin Li if (!New->isInvalidDecl() &&
13097*67e74705SXin Li New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13098*67e74705SXin Li II->isStr("FILE"))
13099*67e74705SXin Li Context.setFILEDecl(New);
13100*67e74705SXin Li
13101*67e74705SXin Li if (PrevDecl)
13102*67e74705SXin Li mergeDeclAttributes(New, PrevDecl);
13103*67e74705SXin Li
13104*67e74705SXin Li // If there's a #pragma GCC visibility in scope, set the visibility of this
13105*67e74705SXin Li // record.
13106*67e74705SXin Li AddPushedVisibilityAttribute(New);
13107*67e74705SXin Li
13108*67e74705SXin Li OwnedDecl = true;
13109*67e74705SXin Li // In C++, don't return an invalid declaration. We can't recover well from
13110*67e74705SXin Li // the cases where we make the type anonymous.
13111*67e74705SXin Li return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13112*67e74705SXin Li }
13113*67e74705SXin Li
ActOnTagStartDefinition(Scope * S,Decl * TagD)13114*67e74705SXin Li void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13115*67e74705SXin Li AdjustDeclIfTemplate(TagD);
13116*67e74705SXin Li TagDecl *Tag = cast<TagDecl>(TagD);
13117*67e74705SXin Li
13118*67e74705SXin Li // Enter the tag context.
13119*67e74705SXin Li PushDeclContext(S, Tag);
13120*67e74705SXin Li
13121*67e74705SXin Li ActOnDocumentableDecl(TagD);
13122*67e74705SXin Li
13123*67e74705SXin Li // If there's a #pragma GCC visibility in scope, set the visibility of this
13124*67e74705SXin Li // record.
13125*67e74705SXin Li AddPushedVisibilityAttribute(Tag);
13126*67e74705SXin Li }
13127*67e74705SXin Li
ActOnObjCContainerStartDefinition(Decl * IDecl)13128*67e74705SXin Li Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13129*67e74705SXin Li assert(isa<ObjCContainerDecl>(IDecl) &&
13130*67e74705SXin Li "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13131*67e74705SXin Li DeclContext *OCD = cast<DeclContext>(IDecl);
13132*67e74705SXin Li assert(getContainingDC(OCD) == CurContext &&
13133*67e74705SXin Li "The next DeclContext should be lexically contained in the current one.");
13134*67e74705SXin Li CurContext = OCD;
13135*67e74705SXin Li return IDecl;
13136*67e74705SXin Li }
13137*67e74705SXin Li
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,SourceLocation LBraceLoc)13138*67e74705SXin Li void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13139*67e74705SXin Li SourceLocation FinalLoc,
13140*67e74705SXin Li bool IsFinalSpelledSealed,
13141*67e74705SXin Li SourceLocation LBraceLoc) {
13142*67e74705SXin Li AdjustDeclIfTemplate(TagD);
13143*67e74705SXin Li CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13144*67e74705SXin Li
13145*67e74705SXin Li FieldCollector->StartClass();
13146*67e74705SXin Li
13147*67e74705SXin Li if (!Record->getIdentifier())
13148*67e74705SXin Li return;
13149*67e74705SXin Li
13150*67e74705SXin Li if (FinalLoc.isValid())
13151*67e74705SXin Li Record->addAttr(new (Context)
13152*67e74705SXin Li FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13153*67e74705SXin Li
13154*67e74705SXin Li // C++ [class]p2:
13155*67e74705SXin Li // [...] The class-name is also inserted into the scope of the
13156*67e74705SXin Li // class itself; this is known as the injected-class-name. For
13157*67e74705SXin Li // purposes of access checking, the injected-class-name is treated
13158*67e74705SXin Li // as if it were a public member name.
13159*67e74705SXin Li CXXRecordDecl *InjectedClassName
13160*67e74705SXin Li = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13161*67e74705SXin Li Record->getLocStart(), Record->getLocation(),
13162*67e74705SXin Li Record->getIdentifier(),
13163*67e74705SXin Li /*PrevDecl=*/nullptr,
13164*67e74705SXin Li /*DelayTypeCreation=*/true);
13165*67e74705SXin Li Context.getTypeDeclType(InjectedClassName, Record);
13166*67e74705SXin Li InjectedClassName->setImplicit();
13167*67e74705SXin Li InjectedClassName->setAccess(AS_public);
13168*67e74705SXin Li if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13169*67e74705SXin Li InjectedClassName->setDescribedClassTemplate(Template);
13170*67e74705SXin Li PushOnScopeChains(InjectedClassName, S);
13171*67e74705SXin Li assert(InjectedClassName->isInjectedClassName() &&
13172*67e74705SXin Li "Broken injected-class-name");
13173*67e74705SXin Li }
13174*67e74705SXin Li
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceLocation RBraceLoc)13175*67e74705SXin Li void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13176*67e74705SXin Li SourceLocation RBraceLoc) {
13177*67e74705SXin Li AdjustDeclIfTemplate(TagD);
13178*67e74705SXin Li TagDecl *Tag = cast<TagDecl>(TagD);
13179*67e74705SXin Li Tag->setRBraceLoc(RBraceLoc);
13180*67e74705SXin Li
13181*67e74705SXin Li // Make sure we "complete" the definition even it is invalid.
13182*67e74705SXin Li if (Tag->isBeingDefined()) {
13183*67e74705SXin Li assert(Tag->isInvalidDecl() && "We should already have completed it");
13184*67e74705SXin Li if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13185*67e74705SXin Li RD->completeDefinition();
13186*67e74705SXin Li }
13187*67e74705SXin Li
13188*67e74705SXin Li if (isa<CXXRecordDecl>(Tag))
13189*67e74705SXin Li FieldCollector->FinishClass();
13190*67e74705SXin Li
13191*67e74705SXin Li // Exit this scope of this tag's definition.
13192*67e74705SXin Li PopDeclContext();
13193*67e74705SXin Li
13194*67e74705SXin Li if (getCurLexicalContext()->isObjCContainer() &&
13195*67e74705SXin Li Tag->getDeclContext()->isFileContext())
13196*67e74705SXin Li Tag->setTopLevelDeclInObjCContainer();
13197*67e74705SXin Li
13198*67e74705SXin Li // Notify the consumer that we've defined a tag.
13199*67e74705SXin Li if (!Tag->isInvalidDecl())
13200*67e74705SXin Li Consumer.HandleTagDeclDefinition(Tag);
13201*67e74705SXin Li }
13202*67e74705SXin Li
ActOnObjCContainerFinishDefinition()13203*67e74705SXin Li void Sema::ActOnObjCContainerFinishDefinition() {
13204*67e74705SXin Li // Exit this scope of this interface definition.
13205*67e74705SXin Li PopDeclContext();
13206*67e74705SXin Li }
13207*67e74705SXin Li
ActOnObjCTemporaryExitContainerContext(DeclContext * DC)13208*67e74705SXin Li void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13209*67e74705SXin Li assert(DC == CurContext && "Mismatch of container contexts");
13210*67e74705SXin Li OriginalLexicalContext = DC;
13211*67e74705SXin Li ActOnObjCContainerFinishDefinition();
13212*67e74705SXin Li }
13213*67e74705SXin Li
ActOnObjCReenterContainerContext(DeclContext * DC)13214*67e74705SXin Li void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13215*67e74705SXin Li ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13216*67e74705SXin Li OriginalLexicalContext = nullptr;
13217*67e74705SXin Li }
13218*67e74705SXin Li
ActOnTagDefinitionError(Scope * S,Decl * TagD)13219*67e74705SXin Li void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13220*67e74705SXin Li AdjustDeclIfTemplate(TagD);
13221*67e74705SXin Li TagDecl *Tag = cast<TagDecl>(TagD);
13222*67e74705SXin Li Tag->setInvalidDecl();
13223*67e74705SXin Li
13224*67e74705SXin Li // Make sure we "complete" the definition even it is invalid.
13225*67e74705SXin Li if (Tag->isBeingDefined()) {
13226*67e74705SXin Li if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13227*67e74705SXin Li RD->completeDefinition();
13228*67e74705SXin Li }
13229*67e74705SXin Li
13230*67e74705SXin Li // We're undoing ActOnTagStartDefinition here, not
13231*67e74705SXin Li // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13232*67e74705SXin Li // the FieldCollector.
13233*67e74705SXin Li
13234*67e74705SXin Li PopDeclContext();
13235*67e74705SXin Li }
13236*67e74705SXin Li
13237*67e74705SXin Li // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth,bool * ZeroWidth)13238*67e74705SXin Li ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13239*67e74705SXin Li IdentifierInfo *FieldName,
13240*67e74705SXin Li QualType FieldTy, bool IsMsStruct,
13241*67e74705SXin Li Expr *BitWidth, bool *ZeroWidth) {
13242*67e74705SXin Li // Default to true; that shouldn't confuse checks for emptiness
13243*67e74705SXin Li if (ZeroWidth)
13244*67e74705SXin Li *ZeroWidth = true;
13245*67e74705SXin Li
13246*67e74705SXin Li // C99 6.7.2.1p4 - verify the field type.
13247*67e74705SXin Li // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13248*67e74705SXin Li if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13249*67e74705SXin Li // Handle incomplete types with specific error.
13250*67e74705SXin Li if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13251*67e74705SXin Li return ExprError();
13252*67e74705SXin Li if (FieldName)
13253*67e74705SXin Li return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13254*67e74705SXin Li << FieldName << FieldTy << BitWidth->getSourceRange();
13255*67e74705SXin Li return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13256*67e74705SXin Li << FieldTy << BitWidth->getSourceRange();
13257*67e74705SXin Li } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13258*67e74705SXin Li UPPC_BitFieldWidth))
13259*67e74705SXin Li return ExprError();
13260*67e74705SXin Li
13261*67e74705SXin Li // If the bit-width is type- or value-dependent, don't try to check
13262*67e74705SXin Li // it now.
13263*67e74705SXin Li if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13264*67e74705SXin Li return BitWidth;
13265*67e74705SXin Li
13266*67e74705SXin Li llvm::APSInt Value;
13267*67e74705SXin Li ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13268*67e74705SXin Li if (ICE.isInvalid())
13269*67e74705SXin Li return ICE;
13270*67e74705SXin Li BitWidth = ICE.get();
13271*67e74705SXin Li
13272*67e74705SXin Li if (Value != 0 && ZeroWidth)
13273*67e74705SXin Li *ZeroWidth = false;
13274*67e74705SXin Li
13275*67e74705SXin Li // Zero-width bitfield is ok for anonymous field.
13276*67e74705SXin Li if (Value == 0 && FieldName)
13277*67e74705SXin Li return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13278*67e74705SXin Li
13279*67e74705SXin Li if (Value.isSigned() && Value.isNegative()) {
13280*67e74705SXin Li if (FieldName)
13281*67e74705SXin Li return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13282*67e74705SXin Li << FieldName << Value.toString(10);
13283*67e74705SXin Li return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13284*67e74705SXin Li << Value.toString(10);
13285*67e74705SXin Li }
13286*67e74705SXin Li
13287*67e74705SXin Li if (!FieldTy->isDependentType()) {
13288*67e74705SXin Li uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13289*67e74705SXin Li uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13290*67e74705SXin Li bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13291*67e74705SXin Li
13292*67e74705SXin Li // Over-wide bitfields are an error in C or when using the MSVC bitfield
13293*67e74705SXin Li // ABI.
13294*67e74705SXin Li bool CStdConstraintViolation =
13295*67e74705SXin Li BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13296*67e74705SXin Li bool MSBitfieldViolation =
13297*67e74705SXin Li Value.ugt(TypeStorageSize) &&
13298*67e74705SXin Li (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13299*67e74705SXin Li if (CStdConstraintViolation || MSBitfieldViolation) {
13300*67e74705SXin Li unsigned DiagWidth =
13301*67e74705SXin Li CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13302*67e74705SXin Li if (FieldName)
13303*67e74705SXin Li return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13304*67e74705SXin Li << FieldName << (unsigned)Value.getZExtValue()
13305*67e74705SXin Li << !CStdConstraintViolation << DiagWidth;
13306*67e74705SXin Li
13307*67e74705SXin Li return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13308*67e74705SXin Li << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13309*67e74705SXin Li << DiagWidth;
13310*67e74705SXin Li }
13311*67e74705SXin Li
13312*67e74705SXin Li // Warn on types where the user might conceivably expect to get all
13313*67e74705SXin Li // specified bits as value bits: that's all integral types other than
13314*67e74705SXin Li // 'bool'.
13315*67e74705SXin Li if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13316*67e74705SXin Li if (FieldName)
13317*67e74705SXin Li Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13318*67e74705SXin Li << FieldName << (unsigned)Value.getZExtValue()
13319*67e74705SXin Li << (unsigned)TypeWidth;
13320*67e74705SXin Li else
13321*67e74705SXin Li Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13322*67e74705SXin Li << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13323*67e74705SXin Li }
13324*67e74705SXin Li }
13325*67e74705SXin Li
13326*67e74705SXin Li return BitWidth;
13327*67e74705SXin Li }
13328*67e74705SXin Li
13329*67e74705SXin Li /// ActOnField - Each field of a C struct/union is passed into this in order
13330*67e74705SXin Li /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)13331*67e74705SXin Li Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13332*67e74705SXin Li Declarator &D, Expr *BitfieldWidth) {
13333*67e74705SXin Li FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13334*67e74705SXin Li DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13335*67e74705SXin Li /*InitStyle=*/ICIS_NoInit, AS_public);
13336*67e74705SXin Li return Res;
13337*67e74705SXin Li }
13338*67e74705SXin Li
13339*67e74705SXin Li /// HandleField - Analyze a field of a C struct or a C++ data member.
13340*67e74705SXin Li ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)13341*67e74705SXin Li FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13342*67e74705SXin Li SourceLocation DeclStart,
13343*67e74705SXin Li Declarator &D, Expr *BitWidth,
13344*67e74705SXin Li InClassInitStyle InitStyle,
13345*67e74705SXin Li AccessSpecifier AS) {
13346*67e74705SXin Li IdentifierInfo *II = D.getIdentifier();
13347*67e74705SXin Li SourceLocation Loc = DeclStart;
13348*67e74705SXin Li if (II) Loc = D.getIdentifierLoc();
13349*67e74705SXin Li
13350*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13351*67e74705SXin Li QualType T = TInfo->getType();
13352*67e74705SXin Li if (getLangOpts().CPlusPlus) {
13353*67e74705SXin Li CheckExtraCXXDefaultArguments(D);
13354*67e74705SXin Li
13355*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13356*67e74705SXin Li UPPC_DataMemberType)) {
13357*67e74705SXin Li D.setInvalidType();
13358*67e74705SXin Li T = Context.IntTy;
13359*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13360*67e74705SXin Li }
13361*67e74705SXin Li }
13362*67e74705SXin Li
13363*67e74705SXin Li // TR 18037 does not allow fields to be declared with address spaces.
13364*67e74705SXin Li if (T.getQualifiers().hasAddressSpace()) {
13365*67e74705SXin Li Diag(Loc, diag::err_field_with_address_space);
13366*67e74705SXin Li D.setInvalidType();
13367*67e74705SXin Li }
13368*67e74705SXin Li
13369*67e74705SXin Li // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13370*67e74705SXin Li // used as structure or union field: image, sampler, event or block types.
13371*67e74705SXin Li if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13372*67e74705SXin Li T->isSamplerT() || T->isBlockPointerType())) {
13373*67e74705SXin Li Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13374*67e74705SXin Li D.setInvalidType();
13375*67e74705SXin Li }
13376*67e74705SXin Li
13377*67e74705SXin Li DiagnoseFunctionSpecifiers(D.getDeclSpec());
13378*67e74705SXin Li
13379*67e74705SXin Li if (D.getDeclSpec().isInlineSpecified())
13380*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13381*67e74705SXin Li << getLangOpts().CPlusPlus1z;
13382*67e74705SXin Li if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13383*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13384*67e74705SXin Li diag::err_invalid_thread)
13385*67e74705SXin Li << DeclSpec::getSpecifierName(TSCS);
13386*67e74705SXin Li
13387*67e74705SXin Li // Check to see if this name was declared as a member previously
13388*67e74705SXin Li NamedDecl *PrevDecl = nullptr;
13389*67e74705SXin Li LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13390*67e74705SXin Li LookupName(Previous, S);
13391*67e74705SXin Li switch (Previous.getResultKind()) {
13392*67e74705SXin Li case LookupResult::Found:
13393*67e74705SXin Li case LookupResult::FoundUnresolvedValue:
13394*67e74705SXin Li PrevDecl = Previous.getAsSingle<NamedDecl>();
13395*67e74705SXin Li break;
13396*67e74705SXin Li
13397*67e74705SXin Li case LookupResult::FoundOverloaded:
13398*67e74705SXin Li PrevDecl = Previous.getRepresentativeDecl();
13399*67e74705SXin Li break;
13400*67e74705SXin Li
13401*67e74705SXin Li case LookupResult::NotFound:
13402*67e74705SXin Li case LookupResult::NotFoundInCurrentInstantiation:
13403*67e74705SXin Li case LookupResult::Ambiguous:
13404*67e74705SXin Li break;
13405*67e74705SXin Li }
13406*67e74705SXin Li Previous.suppressDiagnostics();
13407*67e74705SXin Li
13408*67e74705SXin Li if (PrevDecl && PrevDecl->isTemplateParameter()) {
13409*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
13410*67e74705SXin Li DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13411*67e74705SXin Li // Just pretend that we didn't see the previous declaration.
13412*67e74705SXin Li PrevDecl = nullptr;
13413*67e74705SXin Li }
13414*67e74705SXin Li
13415*67e74705SXin Li if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13416*67e74705SXin Li PrevDecl = nullptr;
13417*67e74705SXin Li
13418*67e74705SXin Li bool Mutable
13419*67e74705SXin Li = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13420*67e74705SXin Li SourceLocation TSSL = D.getLocStart();
13421*67e74705SXin Li FieldDecl *NewFD
13422*67e74705SXin Li = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13423*67e74705SXin Li TSSL, AS, PrevDecl, &D);
13424*67e74705SXin Li
13425*67e74705SXin Li if (NewFD->isInvalidDecl())
13426*67e74705SXin Li Record->setInvalidDecl();
13427*67e74705SXin Li
13428*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified())
13429*67e74705SXin Li NewFD->setModulePrivate();
13430*67e74705SXin Li
13431*67e74705SXin Li if (NewFD->isInvalidDecl() && PrevDecl) {
13432*67e74705SXin Li // Don't introduce NewFD into scope; there's already something
13433*67e74705SXin Li // with the same name in the same scope.
13434*67e74705SXin Li } else if (II) {
13435*67e74705SXin Li PushOnScopeChains(NewFD, S);
13436*67e74705SXin Li } else
13437*67e74705SXin Li Record->addDecl(NewFD);
13438*67e74705SXin Li
13439*67e74705SXin Li return NewFD;
13440*67e74705SXin Li }
13441*67e74705SXin Li
13442*67e74705SXin Li /// \brief Build a new FieldDecl and check its well-formedness.
13443*67e74705SXin Li ///
13444*67e74705SXin Li /// This routine builds a new FieldDecl given the fields name, type,
13445*67e74705SXin Li /// record, etc. \p PrevDecl should refer to any previous declaration
13446*67e74705SXin Li /// with the same name and in the same scope as the field to be
13447*67e74705SXin Li /// created.
13448*67e74705SXin Li ///
13449*67e74705SXin Li /// \returns a new FieldDecl.
13450*67e74705SXin Li ///
13451*67e74705SXin Li /// \todo The Declarator argument is a hack. It will be removed once
CheckFieldDecl(DeclarationName Name,QualType T,TypeSourceInfo * TInfo,RecordDecl * Record,SourceLocation Loc,bool Mutable,Expr * BitWidth,InClassInitStyle InitStyle,SourceLocation TSSL,AccessSpecifier AS,NamedDecl * PrevDecl,Declarator * D)13452*67e74705SXin Li FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13453*67e74705SXin Li TypeSourceInfo *TInfo,
13454*67e74705SXin Li RecordDecl *Record, SourceLocation Loc,
13455*67e74705SXin Li bool Mutable, Expr *BitWidth,
13456*67e74705SXin Li InClassInitStyle InitStyle,
13457*67e74705SXin Li SourceLocation TSSL,
13458*67e74705SXin Li AccessSpecifier AS, NamedDecl *PrevDecl,
13459*67e74705SXin Li Declarator *D) {
13460*67e74705SXin Li IdentifierInfo *II = Name.getAsIdentifierInfo();
13461*67e74705SXin Li bool InvalidDecl = false;
13462*67e74705SXin Li if (D) InvalidDecl = D->isInvalidType();
13463*67e74705SXin Li
13464*67e74705SXin Li // If we receive a broken type, recover by assuming 'int' and
13465*67e74705SXin Li // marking this declaration as invalid.
13466*67e74705SXin Li if (T.isNull()) {
13467*67e74705SXin Li InvalidDecl = true;
13468*67e74705SXin Li T = Context.IntTy;
13469*67e74705SXin Li }
13470*67e74705SXin Li
13471*67e74705SXin Li QualType EltTy = Context.getBaseElementType(T);
13472*67e74705SXin Li if (!EltTy->isDependentType()) {
13473*67e74705SXin Li if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13474*67e74705SXin Li // Fields of incomplete type force their record to be invalid.
13475*67e74705SXin Li Record->setInvalidDecl();
13476*67e74705SXin Li InvalidDecl = true;
13477*67e74705SXin Li } else {
13478*67e74705SXin Li NamedDecl *Def;
13479*67e74705SXin Li EltTy->isIncompleteType(&Def);
13480*67e74705SXin Li if (Def && Def->isInvalidDecl()) {
13481*67e74705SXin Li Record->setInvalidDecl();
13482*67e74705SXin Li InvalidDecl = true;
13483*67e74705SXin Li }
13484*67e74705SXin Li }
13485*67e74705SXin Li }
13486*67e74705SXin Li
13487*67e74705SXin Li // OpenCL v1.2 s6.9.c: bitfields are not supported.
13488*67e74705SXin Li if (BitWidth && getLangOpts().OpenCL) {
13489*67e74705SXin Li Diag(Loc, diag::err_opencl_bitfields);
13490*67e74705SXin Li InvalidDecl = true;
13491*67e74705SXin Li }
13492*67e74705SXin Li
13493*67e74705SXin Li // C99 6.7.2.1p8: A member of a structure or union may have any type other
13494*67e74705SXin Li // than a variably modified type.
13495*67e74705SXin Li if (!InvalidDecl && T->isVariablyModifiedType()) {
13496*67e74705SXin Li bool SizeIsNegative;
13497*67e74705SXin Li llvm::APSInt Oversized;
13498*67e74705SXin Li
13499*67e74705SXin Li TypeSourceInfo *FixedTInfo =
13500*67e74705SXin Li TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13501*67e74705SXin Li SizeIsNegative,
13502*67e74705SXin Li Oversized);
13503*67e74705SXin Li if (FixedTInfo) {
13504*67e74705SXin Li Diag(Loc, diag::warn_illegal_constant_array_size);
13505*67e74705SXin Li TInfo = FixedTInfo;
13506*67e74705SXin Li T = FixedTInfo->getType();
13507*67e74705SXin Li } else {
13508*67e74705SXin Li if (SizeIsNegative)
13509*67e74705SXin Li Diag(Loc, diag::err_typecheck_negative_array_size);
13510*67e74705SXin Li else if (Oversized.getBoolValue())
13511*67e74705SXin Li Diag(Loc, diag::err_array_too_large)
13512*67e74705SXin Li << Oversized.toString(10);
13513*67e74705SXin Li else
13514*67e74705SXin Li Diag(Loc, diag::err_typecheck_field_variable_size);
13515*67e74705SXin Li InvalidDecl = true;
13516*67e74705SXin Li }
13517*67e74705SXin Li }
13518*67e74705SXin Li
13519*67e74705SXin Li // Fields can not have abstract class types
13520*67e74705SXin Li if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13521*67e74705SXin Li diag::err_abstract_type_in_decl,
13522*67e74705SXin Li AbstractFieldType))
13523*67e74705SXin Li InvalidDecl = true;
13524*67e74705SXin Li
13525*67e74705SXin Li bool ZeroWidth = false;
13526*67e74705SXin Li if (InvalidDecl)
13527*67e74705SXin Li BitWidth = nullptr;
13528*67e74705SXin Li // If this is declared as a bit-field, check the bit-field.
13529*67e74705SXin Li if (BitWidth) {
13530*67e74705SXin Li BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13531*67e74705SXin Li &ZeroWidth).get();
13532*67e74705SXin Li if (!BitWidth) {
13533*67e74705SXin Li InvalidDecl = true;
13534*67e74705SXin Li BitWidth = nullptr;
13535*67e74705SXin Li ZeroWidth = false;
13536*67e74705SXin Li }
13537*67e74705SXin Li }
13538*67e74705SXin Li
13539*67e74705SXin Li // Check that 'mutable' is consistent with the type of the declaration.
13540*67e74705SXin Li if (!InvalidDecl && Mutable) {
13541*67e74705SXin Li unsigned DiagID = 0;
13542*67e74705SXin Li if (T->isReferenceType())
13543*67e74705SXin Li DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13544*67e74705SXin Li : diag::err_mutable_reference;
13545*67e74705SXin Li else if (T.isConstQualified())
13546*67e74705SXin Li DiagID = diag::err_mutable_const;
13547*67e74705SXin Li
13548*67e74705SXin Li if (DiagID) {
13549*67e74705SXin Li SourceLocation ErrLoc = Loc;
13550*67e74705SXin Li if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13551*67e74705SXin Li ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13552*67e74705SXin Li Diag(ErrLoc, DiagID);
13553*67e74705SXin Li if (DiagID != diag::ext_mutable_reference) {
13554*67e74705SXin Li Mutable = false;
13555*67e74705SXin Li InvalidDecl = true;
13556*67e74705SXin Li }
13557*67e74705SXin Li }
13558*67e74705SXin Li }
13559*67e74705SXin Li
13560*67e74705SXin Li // C++11 [class.union]p8 (DR1460):
13561*67e74705SXin Li // At most one variant member of a union may have a
13562*67e74705SXin Li // brace-or-equal-initializer.
13563*67e74705SXin Li if (InitStyle != ICIS_NoInit)
13564*67e74705SXin Li checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13565*67e74705SXin Li
13566*67e74705SXin Li FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13567*67e74705SXin Li BitWidth, Mutable, InitStyle);
13568*67e74705SXin Li if (InvalidDecl)
13569*67e74705SXin Li NewFD->setInvalidDecl();
13570*67e74705SXin Li
13571*67e74705SXin Li if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13572*67e74705SXin Li Diag(Loc, diag::err_duplicate_member) << II;
13573*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13574*67e74705SXin Li NewFD->setInvalidDecl();
13575*67e74705SXin Li }
13576*67e74705SXin Li
13577*67e74705SXin Li if (!InvalidDecl && getLangOpts().CPlusPlus) {
13578*67e74705SXin Li if (Record->isUnion()) {
13579*67e74705SXin Li if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13580*67e74705SXin Li CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13581*67e74705SXin Li if (RDecl->getDefinition()) {
13582*67e74705SXin Li // C++ [class.union]p1: An object of a class with a non-trivial
13583*67e74705SXin Li // constructor, a non-trivial copy constructor, a non-trivial
13584*67e74705SXin Li // destructor, or a non-trivial copy assignment operator
13585*67e74705SXin Li // cannot be a member of a union, nor can an array of such
13586*67e74705SXin Li // objects.
13587*67e74705SXin Li if (CheckNontrivialField(NewFD))
13588*67e74705SXin Li NewFD->setInvalidDecl();
13589*67e74705SXin Li }
13590*67e74705SXin Li }
13591*67e74705SXin Li
13592*67e74705SXin Li // C++ [class.union]p1: If a union contains a member of reference type,
13593*67e74705SXin Li // the program is ill-formed, except when compiling with MSVC extensions
13594*67e74705SXin Li // enabled.
13595*67e74705SXin Li if (EltTy->isReferenceType()) {
13596*67e74705SXin Li Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13597*67e74705SXin Li diag::ext_union_member_of_reference_type :
13598*67e74705SXin Li diag::err_union_member_of_reference_type)
13599*67e74705SXin Li << NewFD->getDeclName() << EltTy;
13600*67e74705SXin Li if (!getLangOpts().MicrosoftExt)
13601*67e74705SXin Li NewFD->setInvalidDecl();
13602*67e74705SXin Li }
13603*67e74705SXin Li }
13604*67e74705SXin Li }
13605*67e74705SXin Li
13606*67e74705SXin Li // FIXME: We need to pass in the attributes given an AST
13607*67e74705SXin Li // representation, not a parser representation.
13608*67e74705SXin Li if (D) {
13609*67e74705SXin Li // FIXME: The current scope is almost... but not entirely... correct here.
13610*67e74705SXin Li ProcessDeclAttributes(getCurScope(), NewFD, *D);
13611*67e74705SXin Li
13612*67e74705SXin Li if (NewFD->hasAttrs())
13613*67e74705SXin Li CheckAlignasUnderalignment(NewFD);
13614*67e74705SXin Li }
13615*67e74705SXin Li
13616*67e74705SXin Li // In auto-retain/release, infer strong retension for fields of
13617*67e74705SXin Li // retainable type.
13618*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13619*67e74705SXin Li NewFD->setInvalidDecl();
13620*67e74705SXin Li
13621*67e74705SXin Li if (T.isObjCGCWeak())
13622*67e74705SXin Li Diag(Loc, diag::warn_attribute_weak_on_field);
13623*67e74705SXin Li
13624*67e74705SXin Li NewFD->setAccess(AS);
13625*67e74705SXin Li return NewFD;
13626*67e74705SXin Li }
13627*67e74705SXin Li
CheckNontrivialField(FieldDecl * FD)13628*67e74705SXin Li bool Sema::CheckNontrivialField(FieldDecl *FD) {
13629*67e74705SXin Li assert(FD);
13630*67e74705SXin Li assert(getLangOpts().CPlusPlus && "valid check only for C++");
13631*67e74705SXin Li
13632*67e74705SXin Li if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13633*67e74705SXin Li return false;
13634*67e74705SXin Li
13635*67e74705SXin Li QualType EltTy = Context.getBaseElementType(FD->getType());
13636*67e74705SXin Li if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13637*67e74705SXin Li CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13638*67e74705SXin Li if (RDecl->getDefinition()) {
13639*67e74705SXin Li // We check for copy constructors before constructors
13640*67e74705SXin Li // because otherwise we'll never get complaints about
13641*67e74705SXin Li // copy constructors.
13642*67e74705SXin Li
13643*67e74705SXin Li CXXSpecialMember member = CXXInvalid;
13644*67e74705SXin Li // We're required to check for any non-trivial constructors. Since the
13645*67e74705SXin Li // implicit default constructor is suppressed if there are any
13646*67e74705SXin Li // user-declared constructors, we just need to check that there is a
13647*67e74705SXin Li // trivial default constructor and a trivial copy constructor. (We don't
13648*67e74705SXin Li // worry about move constructors here, since this is a C++98 check.)
13649*67e74705SXin Li if (RDecl->hasNonTrivialCopyConstructor())
13650*67e74705SXin Li member = CXXCopyConstructor;
13651*67e74705SXin Li else if (!RDecl->hasTrivialDefaultConstructor())
13652*67e74705SXin Li member = CXXDefaultConstructor;
13653*67e74705SXin Li else if (RDecl->hasNonTrivialCopyAssignment())
13654*67e74705SXin Li member = CXXCopyAssignment;
13655*67e74705SXin Li else if (RDecl->hasNonTrivialDestructor())
13656*67e74705SXin Li member = CXXDestructor;
13657*67e74705SXin Li
13658*67e74705SXin Li if (member != CXXInvalid) {
13659*67e74705SXin Li if (!getLangOpts().CPlusPlus11 &&
13660*67e74705SXin Li getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13661*67e74705SXin Li // Objective-C++ ARC: it is an error to have a non-trivial field of
13662*67e74705SXin Li // a union. However, system headers in Objective-C programs
13663*67e74705SXin Li // occasionally have Objective-C lifetime objects within unions,
13664*67e74705SXin Li // and rather than cause the program to fail, we make those
13665*67e74705SXin Li // members unavailable.
13666*67e74705SXin Li SourceLocation Loc = FD->getLocation();
13667*67e74705SXin Li if (getSourceManager().isInSystemHeader(Loc)) {
13668*67e74705SXin Li if (!FD->hasAttr<UnavailableAttr>())
13669*67e74705SXin Li FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13670*67e74705SXin Li UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13671*67e74705SXin Li return false;
13672*67e74705SXin Li }
13673*67e74705SXin Li }
13674*67e74705SXin Li
13675*67e74705SXin Li Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13676*67e74705SXin Li diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13677*67e74705SXin Li diag::err_illegal_union_or_anon_struct_member)
13678*67e74705SXin Li << FD->getParent()->isUnion() << FD->getDeclName() << member;
13679*67e74705SXin Li DiagnoseNontrivial(RDecl, member);
13680*67e74705SXin Li return !getLangOpts().CPlusPlus11;
13681*67e74705SXin Li }
13682*67e74705SXin Li }
13683*67e74705SXin Li }
13684*67e74705SXin Li
13685*67e74705SXin Li return false;
13686*67e74705SXin Li }
13687*67e74705SXin Li
13688*67e74705SXin Li /// TranslateIvarVisibility - Translate visibility from a token ID to an
13689*67e74705SXin Li /// AST enum value.
13690*67e74705SXin Li static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)13691*67e74705SXin Li TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13692*67e74705SXin Li switch (ivarVisibility) {
13693*67e74705SXin Li default: llvm_unreachable("Unknown visitibility kind");
13694*67e74705SXin Li case tok::objc_private: return ObjCIvarDecl::Private;
13695*67e74705SXin Li case tok::objc_public: return ObjCIvarDecl::Public;
13696*67e74705SXin Li case tok::objc_protected: return ObjCIvarDecl::Protected;
13697*67e74705SXin Li case tok::objc_package: return ObjCIvarDecl::Package;
13698*67e74705SXin Li }
13699*67e74705SXin Li }
13700*67e74705SXin Li
13701*67e74705SXin Li /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13702*67e74705SXin Li /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)13703*67e74705SXin Li Decl *Sema::ActOnIvar(Scope *S,
13704*67e74705SXin Li SourceLocation DeclStart,
13705*67e74705SXin Li Declarator &D, Expr *BitfieldWidth,
13706*67e74705SXin Li tok::ObjCKeywordKind Visibility) {
13707*67e74705SXin Li
13708*67e74705SXin Li IdentifierInfo *II = D.getIdentifier();
13709*67e74705SXin Li Expr *BitWidth = (Expr*)BitfieldWidth;
13710*67e74705SXin Li SourceLocation Loc = DeclStart;
13711*67e74705SXin Li if (II) Loc = D.getIdentifierLoc();
13712*67e74705SXin Li
13713*67e74705SXin Li // FIXME: Unnamed fields can be handled in various different ways, for
13714*67e74705SXin Li // example, unnamed unions inject all members into the struct namespace!
13715*67e74705SXin Li
13716*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13717*67e74705SXin Li QualType T = TInfo->getType();
13718*67e74705SXin Li
13719*67e74705SXin Li if (BitWidth) {
13720*67e74705SXin Li // 6.7.2.1p3, 6.7.2.1p4
13721*67e74705SXin Li BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13722*67e74705SXin Li if (!BitWidth)
13723*67e74705SXin Li D.setInvalidType();
13724*67e74705SXin Li } else {
13725*67e74705SXin Li // Not a bitfield.
13726*67e74705SXin Li
13727*67e74705SXin Li // validate II.
13728*67e74705SXin Li
13729*67e74705SXin Li }
13730*67e74705SXin Li if (T->isReferenceType()) {
13731*67e74705SXin Li Diag(Loc, diag::err_ivar_reference_type);
13732*67e74705SXin Li D.setInvalidType();
13733*67e74705SXin Li }
13734*67e74705SXin Li // C99 6.7.2.1p8: A member of a structure or union may have any type other
13735*67e74705SXin Li // than a variably modified type.
13736*67e74705SXin Li else if (T->isVariablyModifiedType()) {
13737*67e74705SXin Li Diag(Loc, diag::err_typecheck_ivar_variable_size);
13738*67e74705SXin Li D.setInvalidType();
13739*67e74705SXin Li }
13740*67e74705SXin Li
13741*67e74705SXin Li // Get the visibility (access control) for this ivar.
13742*67e74705SXin Li ObjCIvarDecl::AccessControl ac =
13743*67e74705SXin Li Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13744*67e74705SXin Li : ObjCIvarDecl::None;
13745*67e74705SXin Li // Must set ivar's DeclContext to its enclosing interface.
13746*67e74705SXin Li ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13747*67e74705SXin Li if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13748*67e74705SXin Li return nullptr;
13749*67e74705SXin Li ObjCContainerDecl *EnclosingContext;
13750*67e74705SXin Li if (ObjCImplementationDecl *IMPDecl =
13751*67e74705SXin Li dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13752*67e74705SXin Li if (LangOpts.ObjCRuntime.isFragile()) {
13753*67e74705SXin Li // Case of ivar declared in an implementation. Context is that of its class.
13754*67e74705SXin Li EnclosingContext = IMPDecl->getClassInterface();
13755*67e74705SXin Li assert(EnclosingContext && "Implementation has no class interface!");
13756*67e74705SXin Li }
13757*67e74705SXin Li else
13758*67e74705SXin Li EnclosingContext = EnclosingDecl;
13759*67e74705SXin Li } else {
13760*67e74705SXin Li if (ObjCCategoryDecl *CDecl =
13761*67e74705SXin Li dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13762*67e74705SXin Li if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13763*67e74705SXin Li Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13764*67e74705SXin Li return nullptr;
13765*67e74705SXin Li }
13766*67e74705SXin Li }
13767*67e74705SXin Li EnclosingContext = EnclosingDecl;
13768*67e74705SXin Li }
13769*67e74705SXin Li
13770*67e74705SXin Li // Construct the decl.
13771*67e74705SXin Li ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13772*67e74705SXin Li DeclStart, Loc, II, T,
13773*67e74705SXin Li TInfo, ac, (Expr *)BitfieldWidth);
13774*67e74705SXin Li
13775*67e74705SXin Li if (II) {
13776*67e74705SXin Li NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13777*67e74705SXin Li ForRedeclaration);
13778*67e74705SXin Li if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13779*67e74705SXin Li && !isa<TagDecl>(PrevDecl)) {
13780*67e74705SXin Li Diag(Loc, diag::err_duplicate_member) << II;
13781*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13782*67e74705SXin Li NewID->setInvalidDecl();
13783*67e74705SXin Li }
13784*67e74705SXin Li }
13785*67e74705SXin Li
13786*67e74705SXin Li // Process attributes attached to the ivar.
13787*67e74705SXin Li ProcessDeclAttributes(S, NewID, D);
13788*67e74705SXin Li
13789*67e74705SXin Li if (D.isInvalidType())
13790*67e74705SXin Li NewID->setInvalidDecl();
13791*67e74705SXin Li
13792*67e74705SXin Li // In ARC, infer 'retaining' for ivars of retainable type.
13793*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13794*67e74705SXin Li NewID->setInvalidDecl();
13795*67e74705SXin Li
13796*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified())
13797*67e74705SXin Li NewID->setModulePrivate();
13798*67e74705SXin Li
13799*67e74705SXin Li if (II) {
13800*67e74705SXin Li // FIXME: When interfaces are DeclContexts, we'll need to add
13801*67e74705SXin Li // these to the interface.
13802*67e74705SXin Li S->AddDecl(NewID);
13803*67e74705SXin Li IdResolver.AddDecl(NewID);
13804*67e74705SXin Li }
13805*67e74705SXin Li
13806*67e74705SXin Li if (LangOpts.ObjCRuntime.isNonFragile() &&
13807*67e74705SXin Li !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13808*67e74705SXin Li Diag(Loc, diag::warn_ivars_in_interface);
13809*67e74705SXin Li
13810*67e74705SXin Li return NewID;
13811*67e74705SXin Li }
13812*67e74705SXin Li
13813*67e74705SXin Li /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13814*67e74705SXin Li /// class and class extensions. For every class \@interface and class
13815*67e74705SXin Li /// extension \@interface, if the last ivar is a bitfield of any type,
13816*67e74705SXin Li /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)13817*67e74705SXin Li void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13818*67e74705SXin Li SmallVectorImpl<Decl *> &AllIvarDecls) {
13819*67e74705SXin Li if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13820*67e74705SXin Li return;
13821*67e74705SXin Li
13822*67e74705SXin Li Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13823*67e74705SXin Li ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13824*67e74705SXin Li
13825*67e74705SXin Li if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13826*67e74705SXin Li return;
13827*67e74705SXin Li ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13828*67e74705SXin Li if (!ID) {
13829*67e74705SXin Li if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13830*67e74705SXin Li if (!CD->IsClassExtension())
13831*67e74705SXin Li return;
13832*67e74705SXin Li }
13833*67e74705SXin Li // No need to add this to end of @implementation.
13834*67e74705SXin Li else
13835*67e74705SXin Li return;
13836*67e74705SXin Li }
13837*67e74705SXin Li // All conditions are met. Add a new bitfield to the tail end of ivars.
13838*67e74705SXin Li llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13839*67e74705SXin Li Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13840*67e74705SXin Li
13841*67e74705SXin Li Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13842*67e74705SXin Li DeclLoc, DeclLoc, nullptr,
13843*67e74705SXin Li Context.CharTy,
13844*67e74705SXin Li Context.getTrivialTypeSourceInfo(Context.CharTy,
13845*67e74705SXin Li DeclLoc),
13846*67e74705SXin Li ObjCIvarDecl::Private, BW,
13847*67e74705SXin Li true);
13848*67e74705SXin Li AllIvarDecls.push_back(Ivar);
13849*67e74705SXin Li }
13850*67e74705SXin Li
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,AttributeList * Attr)13851*67e74705SXin Li void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13852*67e74705SXin Li ArrayRef<Decl *> Fields, SourceLocation LBrac,
13853*67e74705SXin Li SourceLocation RBrac, AttributeList *Attr) {
13854*67e74705SXin Li assert(EnclosingDecl && "missing record or interface decl");
13855*67e74705SXin Li
13856*67e74705SXin Li // If this is an Objective-C @implementation or category and we have
13857*67e74705SXin Li // new fields here we should reset the layout of the interface since
13858*67e74705SXin Li // it will now change.
13859*67e74705SXin Li if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13860*67e74705SXin Li ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13861*67e74705SXin Li switch (DC->getKind()) {
13862*67e74705SXin Li default: break;
13863*67e74705SXin Li case Decl::ObjCCategory:
13864*67e74705SXin Li Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13865*67e74705SXin Li break;
13866*67e74705SXin Li case Decl::ObjCImplementation:
13867*67e74705SXin Li Context.
13868*67e74705SXin Li ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13869*67e74705SXin Li break;
13870*67e74705SXin Li }
13871*67e74705SXin Li }
13872*67e74705SXin Li
13873*67e74705SXin Li RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13874*67e74705SXin Li
13875*67e74705SXin Li // Start counting up the number of named members; make sure to include
13876*67e74705SXin Li // members of anonymous structs and unions in the total.
13877*67e74705SXin Li unsigned NumNamedMembers = 0;
13878*67e74705SXin Li if (Record) {
13879*67e74705SXin Li for (const auto *I : Record->decls()) {
13880*67e74705SXin Li if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13881*67e74705SXin Li if (IFD->getDeclName())
13882*67e74705SXin Li ++NumNamedMembers;
13883*67e74705SXin Li }
13884*67e74705SXin Li }
13885*67e74705SXin Li
13886*67e74705SXin Li // Verify that all the fields are okay.
13887*67e74705SXin Li SmallVector<FieldDecl*, 32> RecFields;
13888*67e74705SXin Li
13889*67e74705SXin Li bool ARCErrReported = false;
13890*67e74705SXin Li for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13891*67e74705SXin Li i != end; ++i) {
13892*67e74705SXin Li FieldDecl *FD = cast<FieldDecl>(*i);
13893*67e74705SXin Li
13894*67e74705SXin Li // Get the type for the field.
13895*67e74705SXin Li const Type *FDTy = FD->getType().getTypePtr();
13896*67e74705SXin Li
13897*67e74705SXin Li if (!FD->isAnonymousStructOrUnion()) {
13898*67e74705SXin Li // Remember all fields written by the user.
13899*67e74705SXin Li RecFields.push_back(FD);
13900*67e74705SXin Li }
13901*67e74705SXin Li
13902*67e74705SXin Li // If the field is already invalid for some reason, don't emit more
13903*67e74705SXin Li // diagnostics about it.
13904*67e74705SXin Li if (FD->isInvalidDecl()) {
13905*67e74705SXin Li EnclosingDecl->setInvalidDecl();
13906*67e74705SXin Li continue;
13907*67e74705SXin Li }
13908*67e74705SXin Li
13909*67e74705SXin Li // C99 6.7.2.1p2:
13910*67e74705SXin Li // A structure or union shall not contain a member with
13911*67e74705SXin Li // incomplete or function type (hence, a structure shall not
13912*67e74705SXin Li // contain an instance of itself, but may contain a pointer to
13913*67e74705SXin Li // an instance of itself), except that the last member of a
13914*67e74705SXin Li // structure with more than one named member may have incomplete
13915*67e74705SXin Li // array type; such a structure (and any union containing,
13916*67e74705SXin Li // possibly recursively, a member that is such a structure)
13917*67e74705SXin Li // shall not be a member of a structure or an element of an
13918*67e74705SXin Li // array.
13919*67e74705SXin Li if (FDTy->isFunctionType()) {
13920*67e74705SXin Li // Field declared as a function.
13921*67e74705SXin Li Diag(FD->getLocation(), diag::err_field_declared_as_function)
13922*67e74705SXin Li << FD->getDeclName();
13923*67e74705SXin Li FD->setInvalidDecl();
13924*67e74705SXin Li EnclosingDecl->setInvalidDecl();
13925*67e74705SXin Li continue;
13926*67e74705SXin Li } else if (FDTy->isIncompleteArrayType() && Record &&
13927*67e74705SXin Li ((i + 1 == Fields.end() && !Record->isUnion()) ||
13928*67e74705SXin Li ((getLangOpts().MicrosoftExt ||
13929*67e74705SXin Li getLangOpts().CPlusPlus) &&
13930*67e74705SXin Li (i + 1 == Fields.end() || Record->isUnion())))) {
13931*67e74705SXin Li // Flexible array member.
13932*67e74705SXin Li // Microsoft and g++ is more permissive regarding flexible array.
13933*67e74705SXin Li // It will accept flexible array in union and also
13934*67e74705SXin Li // as the sole element of a struct/class.
13935*67e74705SXin Li unsigned DiagID = 0;
13936*67e74705SXin Li if (Record->isUnion())
13937*67e74705SXin Li DiagID = getLangOpts().MicrosoftExt
13938*67e74705SXin Li ? diag::ext_flexible_array_union_ms
13939*67e74705SXin Li : getLangOpts().CPlusPlus
13940*67e74705SXin Li ? diag::ext_flexible_array_union_gnu
13941*67e74705SXin Li : diag::err_flexible_array_union;
13942*67e74705SXin Li else if (NumNamedMembers < 1)
13943*67e74705SXin Li DiagID = getLangOpts().MicrosoftExt
13944*67e74705SXin Li ? diag::ext_flexible_array_empty_aggregate_ms
13945*67e74705SXin Li : getLangOpts().CPlusPlus
13946*67e74705SXin Li ? diag::ext_flexible_array_empty_aggregate_gnu
13947*67e74705SXin Li : diag::err_flexible_array_empty_aggregate;
13948*67e74705SXin Li
13949*67e74705SXin Li if (DiagID)
13950*67e74705SXin Li Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13951*67e74705SXin Li << Record->getTagKind();
13952*67e74705SXin Li // While the layout of types that contain virtual bases is not specified
13953*67e74705SXin Li // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13954*67e74705SXin Li // virtual bases after the derived members. This would make a flexible
13955*67e74705SXin Li // array member declared at the end of an object not adjacent to the end
13956*67e74705SXin Li // of the type.
13957*67e74705SXin Li if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13958*67e74705SXin Li if (RD->getNumVBases() != 0)
13959*67e74705SXin Li Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13960*67e74705SXin Li << FD->getDeclName() << Record->getTagKind();
13961*67e74705SXin Li if (!getLangOpts().C99)
13962*67e74705SXin Li Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13963*67e74705SXin Li << FD->getDeclName() << Record->getTagKind();
13964*67e74705SXin Li
13965*67e74705SXin Li // If the element type has a non-trivial destructor, we would not
13966*67e74705SXin Li // implicitly destroy the elements, so disallow it for now.
13967*67e74705SXin Li //
13968*67e74705SXin Li // FIXME: GCC allows this. We should probably either implicitly delete
13969*67e74705SXin Li // the destructor of the containing class, or just allow this.
13970*67e74705SXin Li QualType BaseElem = Context.getBaseElementType(FD->getType());
13971*67e74705SXin Li if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13972*67e74705SXin Li Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13973*67e74705SXin Li << FD->getDeclName() << FD->getType();
13974*67e74705SXin Li FD->setInvalidDecl();
13975*67e74705SXin Li EnclosingDecl->setInvalidDecl();
13976*67e74705SXin Li continue;
13977*67e74705SXin Li }
13978*67e74705SXin Li // Okay, we have a legal flexible array member at the end of the struct.
13979*67e74705SXin Li Record->setHasFlexibleArrayMember(true);
13980*67e74705SXin Li } else if (!FDTy->isDependentType() &&
13981*67e74705SXin Li RequireCompleteType(FD->getLocation(), FD->getType(),
13982*67e74705SXin Li diag::err_field_incomplete)) {
13983*67e74705SXin Li // Incomplete type
13984*67e74705SXin Li FD->setInvalidDecl();
13985*67e74705SXin Li EnclosingDecl->setInvalidDecl();
13986*67e74705SXin Li continue;
13987*67e74705SXin Li } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13988*67e74705SXin Li if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13989*67e74705SXin Li // A type which contains a flexible array member is considered to be a
13990*67e74705SXin Li // flexible array member.
13991*67e74705SXin Li Record->setHasFlexibleArrayMember(true);
13992*67e74705SXin Li if (!Record->isUnion()) {
13993*67e74705SXin Li // If this is a struct/class and this is not the last element, reject
13994*67e74705SXin Li // it. Note that GCC supports variable sized arrays in the middle of
13995*67e74705SXin Li // structures.
13996*67e74705SXin Li if (i + 1 != Fields.end())
13997*67e74705SXin Li Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13998*67e74705SXin Li << FD->getDeclName() << FD->getType();
13999*67e74705SXin Li else {
14000*67e74705SXin Li // We support flexible arrays at the end of structs in
14001*67e74705SXin Li // other structs as an extension.
14002*67e74705SXin Li Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14003*67e74705SXin Li << FD->getDeclName();
14004*67e74705SXin Li }
14005*67e74705SXin Li }
14006*67e74705SXin Li }
14007*67e74705SXin Li if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14008*67e74705SXin Li RequireNonAbstractType(FD->getLocation(), FD->getType(),
14009*67e74705SXin Li diag::err_abstract_type_in_decl,
14010*67e74705SXin Li AbstractIvarType)) {
14011*67e74705SXin Li // Ivars can not have abstract class types
14012*67e74705SXin Li FD->setInvalidDecl();
14013*67e74705SXin Li }
14014*67e74705SXin Li if (Record && FDTTy->getDecl()->hasObjectMember())
14015*67e74705SXin Li Record->setHasObjectMember(true);
14016*67e74705SXin Li if (Record && FDTTy->getDecl()->hasVolatileMember())
14017*67e74705SXin Li Record->setHasVolatileMember(true);
14018*67e74705SXin Li } else if (FDTy->isObjCObjectType()) {
14019*67e74705SXin Li /// A field cannot be an Objective-c object
14020*67e74705SXin Li Diag(FD->getLocation(), diag::err_statically_allocated_object)
14021*67e74705SXin Li << FixItHint::CreateInsertion(FD->getLocation(), "*");
14022*67e74705SXin Li QualType T = Context.getObjCObjectPointerType(FD->getType());
14023*67e74705SXin Li FD->setType(T);
14024*67e74705SXin Li } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14025*67e74705SXin Li (!getLangOpts().CPlusPlus || Record->isUnion())) {
14026*67e74705SXin Li // It's an error in ARC if a field has lifetime.
14027*67e74705SXin Li // We don't want to report this in a system header, though,
14028*67e74705SXin Li // so we just make the field unavailable.
14029*67e74705SXin Li // FIXME: that's really not sufficient; we need to make the type
14030*67e74705SXin Li // itself invalid to, say, initialize or copy.
14031*67e74705SXin Li QualType T = FD->getType();
14032*67e74705SXin Li Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14033*67e74705SXin Li if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14034*67e74705SXin Li SourceLocation loc = FD->getLocation();
14035*67e74705SXin Li if (getSourceManager().isInSystemHeader(loc)) {
14036*67e74705SXin Li if (!FD->hasAttr<UnavailableAttr>()) {
14037*67e74705SXin Li FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14038*67e74705SXin Li UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14039*67e74705SXin Li }
14040*67e74705SXin Li } else {
14041*67e74705SXin Li Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14042*67e74705SXin Li << T->isBlockPointerType() << Record->getTagKind();
14043*67e74705SXin Li }
14044*67e74705SXin Li ARCErrReported = true;
14045*67e74705SXin Li }
14046*67e74705SXin Li } else if (getLangOpts().ObjC1 &&
14047*67e74705SXin Li getLangOpts().getGC() != LangOptions::NonGC &&
14048*67e74705SXin Li Record && !Record->hasObjectMember()) {
14049*67e74705SXin Li if (FD->getType()->isObjCObjectPointerType() ||
14050*67e74705SXin Li FD->getType().isObjCGCStrong())
14051*67e74705SXin Li Record->setHasObjectMember(true);
14052*67e74705SXin Li else if (Context.getAsArrayType(FD->getType())) {
14053*67e74705SXin Li QualType BaseType = Context.getBaseElementType(FD->getType());
14054*67e74705SXin Li if (BaseType->isRecordType() &&
14055*67e74705SXin Li BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14056*67e74705SXin Li Record->setHasObjectMember(true);
14057*67e74705SXin Li else if (BaseType->isObjCObjectPointerType() ||
14058*67e74705SXin Li BaseType.isObjCGCStrong())
14059*67e74705SXin Li Record->setHasObjectMember(true);
14060*67e74705SXin Li }
14061*67e74705SXin Li }
14062*67e74705SXin Li if (Record && FD->getType().isVolatileQualified())
14063*67e74705SXin Li Record->setHasVolatileMember(true);
14064*67e74705SXin Li // Keep track of the number of named members.
14065*67e74705SXin Li if (FD->getIdentifier())
14066*67e74705SXin Li ++NumNamedMembers;
14067*67e74705SXin Li }
14068*67e74705SXin Li
14069*67e74705SXin Li // Okay, we successfully defined 'Record'.
14070*67e74705SXin Li if (Record) {
14071*67e74705SXin Li bool Completed = false;
14072*67e74705SXin Li if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14073*67e74705SXin Li if (!CXXRecord->isInvalidDecl()) {
14074*67e74705SXin Li // Set access bits correctly on the directly-declared conversions.
14075*67e74705SXin Li for (CXXRecordDecl::conversion_iterator
14076*67e74705SXin Li I = CXXRecord->conversion_begin(),
14077*67e74705SXin Li E = CXXRecord->conversion_end(); I != E; ++I)
14078*67e74705SXin Li I.setAccess((*I)->getAccess());
14079*67e74705SXin Li }
14080*67e74705SXin Li
14081*67e74705SXin Li if (!CXXRecord->isDependentType()) {
14082*67e74705SXin Li if (CXXRecord->hasUserDeclaredDestructor()) {
14083*67e74705SXin Li // Adjust user-defined destructor exception spec.
14084*67e74705SXin Li if (getLangOpts().CPlusPlus11)
14085*67e74705SXin Li AdjustDestructorExceptionSpec(CXXRecord,
14086*67e74705SXin Li CXXRecord->getDestructor());
14087*67e74705SXin Li }
14088*67e74705SXin Li
14089*67e74705SXin Li if (!CXXRecord->isInvalidDecl()) {
14090*67e74705SXin Li // Add any implicitly-declared members to this class.
14091*67e74705SXin Li AddImplicitlyDeclaredMembersToClass(CXXRecord);
14092*67e74705SXin Li
14093*67e74705SXin Li // If we have virtual base classes, we may end up finding multiple
14094*67e74705SXin Li // final overriders for a given virtual function. Check for this
14095*67e74705SXin Li // problem now.
14096*67e74705SXin Li if (CXXRecord->getNumVBases()) {
14097*67e74705SXin Li CXXFinalOverriderMap FinalOverriders;
14098*67e74705SXin Li CXXRecord->getFinalOverriders(FinalOverriders);
14099*67e74705SXin Li
14100*67e74705SXin Li for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14101*67e74705SXin Li MEnd = FinalOverriders.end();
14102*67e74705SXin Li M != MEnd; ++M) {
14103*67e74705SXin Li for (OverridingMethods::iterator SO = M->second.begin(),
14104*67e74705SXin Li SOEnd = M->second.end();
14105*67e74705SXin Li SO != SOEnd; ++SO) {
14106*67e74705SXin Li assert(SO->second.size() > 0 &&
14107*67e74705SXin Li "Virtual function without overridding functions?");
14108*67e74705SXin Li if (SO->second.size() == 1)
14109*67e74705SXin Li continue;
14110*67e74705SXin Li
14111*67e74705SXin Li // C++ [class.virtual]p2:
14112*67e74705SXin Li // In a derived class, if a virtual member function of a base
14113*67e74705SXin Li // class subobject has more than one final overrider the
14114*67e74705SXin Li // program is ill-formed.
14115*67e74705SXin Li Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14116*67e74705SXin Li << (const NamedDecl *)M->first << Record;
14117*67e74705SXin Li Diag(M->first->getLocation(),
14118*67e74705SXin Li diag::note_overridden_virtual_function);
14119*67e74705SXin Li for (OverridingMethods::overriding_iterator
14120*67e74705SXin Li OM = SO->second.begin(),
14121*67e74705SXin Li OMEnd = SO->second.end();
14122*67e74705SXin Li OM != OMEnd; ++OM)
14123*67e74705SXin Li Diag(OM->Method->getLocation(), diag::note_final_overrider)
14124*67e74705SXin Li << (const NamedDecl *)M->first << OM->Method->getParent();
14125*67e74705SXin Li
14126*67e74705SXin Li Record->setInvalidDecl();
14127*67e74705SXin Li }
14128*67e74705SXin Li }
14129*67e74705SXin Li CXXRecord->completeDefinition(&FinalOverriders);
14130*67e74705SXin Li Completed = true;
14131*67e74705SXin Li }
14132*67e74705SXin Li }
14133*67e74705SXin Li }
14134*67e74705SXin Li }
14135*67e74705SXin Li
14136*67e74705SXin Li if (!Completed)
14137*67e74705SXin Li Record->completeDefinition();
14138*67e74705SXin Li
14139*67e74705SXin Li if (Record->hasAttrs()) {
14140*67e74705SXin Li CheckAlignasUnderalignment(Record);
14141*67e74705SXin Li
14142*67e74705SXin Li if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14143*67e74705SXin Li checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14144*67e74705SXin Li IA->getRange(), IA->getBestCase(),
14145*67e74705SXin Li IA->getSemanticSpelling());
14146*67e74705SXin Li }
14147*67e74705SXin Li
14148*67e74705SXin Li // Check if the structure/union declaration is a type that can have zero
14149*67e74705SXin Li // size in C. For C this is a language extension, for C++ it may cause
14150*67e74705SXin Li // compatibility problems.
14151*67e74705SXin Li bool CheckForZeroSize;
14152*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
14153*67e74705SXin Li CheckForZeroSize = true;
14154*67e74705SXin Li } else {
14155*67e74705SXin Li // For C++ filter out types that cannot be referenced in C code.
14156*67e74705SXin Li CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14157*67e74705SXin Li CheckForZeroSize =
14158*67e74705SXin Li CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14159*67e74705SXin Li !CXXRecord->isDependentType() &&
14160*67e74705SXin Li CXXRecord->isCLike();
14161*67e74705SXin Li }
14162*67e74705SXin Li if (CheckForZeroSize) {
14163*67e74705SXin Li bool ZeroSize = true;
14164*67e74705SXin Li bool IsEmpty = true;
14165*67e74705SXin Li unsigned NonBitFields = 0;
14166*67e74705SXin Li for (RecordDecl::field_iterator I = Record->field_begin(),
14167*67e74705SXin Li E = Record->field_end();
14168*67e74705SXin Li (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14169*67e74705SXin Li IsEmpty = false;
14170*67e74705SXin Li if (I->isUnnamedBitfield()) {
14171*67e74705SXin Li if (I->getBitWidthValue(Context) > 0)
14172*67e74705SXin Li ZeroSize = false;
14173*67e74705SXin Li } else {
14174*67e74705SXin Li ++NonBitFields;
14175*67e74705SXin Li QualType FieldType = I->getType();
14176*67e74705SXin Li if (FieldType->isIncompleteType() ||
14177*67e74705SXin Li !Context.getTypeSizeInChars(FieldType).isZero())
14178*67e74705SXin Li ZeroSize = false;
14179*67e74705SXin Li }
14180*67e74705SXin Li }
14181*67e74705SXin Li
14182*67e74705SXin Li // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14183*67e74705SXin Li // allowed in C++, but warn if its declaration is inside
14184*67e74705SXin Li // extern "C" block.
14185*67e74705SXin Li if (ZeroSize) {
14186*67e74705SXin Li Diag(RecLoc, getLangOpts().CPlusPlus ?
14187*67e74705SXin Li diag::warn_zero_size_struct_union_in_extern_c :
14188*67e74705SXin Li diag::warn_zero_size_struct_union_compat)
14189*67e74705SXin Li << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14190*67e74705SXin Li }
14191*67e74705SXin Li
14192*67e74705SXin Li // Structs without named members are extension in C (C99 6.7.2.1p7),
14193*67e74705SXin Li // but are accepted by GCC.
14194*67e74705SXin Li if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14195*67e74705SXin Li Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14196*67e74705SXin Li diag::ext_no_named_members_in_struct_union)
14197*67e74705SXin Li << Record->isUnion();
14198*67e74705SXin Li }
14199*67e74705SXin Li }
14200*67e74705SXin Li } else {
14201*67e74705SXin Li ObjCIvarDecl **ClsFields =
14202*67e74705SXin Li reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14203*67e74705SXin Li if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14204*67e74705SXin Li ID->setEndOfDefinitionLoc(RBrac);
14205*67e74705SXin Li // Add ivar's to class's DeclContext.
14206*67e74705SXin Li for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14207*67e74705SXin Li ClsFields[i]->setLexicalDeclContext(ID);
14208*67e74705SXin Li ID->addDecl(ClsFields[i]);
14209*67e74705SXin Li }
14210*67e74705SXin Li // Must enforce the rule that ivars in the base classes may not be
14211*67e74705SXin Li // duplicates.
14212*67e74705SXin Li if (ID->getSuperClass())
14213*67e74705SXin Li DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14214*67e74705SXin Li } else if (ObjCImplementationDecl *IMPDecl =
14215*67e74705SXin Li dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14216*67e74705SXin Li assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14217*67e74705SXin Li for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14218*67e74705SXin Li // Ivar declared in @implementation never belongs to the implementation.
14219*67e74705SXin Li // Only it is in implementation's lexical context.
14220*67e74705SXin Li ClsFields[I]->setLexicalDeclContext(IMPDecl);
14221*67e74705SXin Li CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14222*67e74705SXin Li IMPDecl->setIvarLBraceLoc(LBrac);
14223*67e74705SXin Li IMPDecl->setIvarRBraceLoc(RBrac);
14224*67e74705SXin Li } else if (ObjCCategoryDecl *CDecl =
14225*67e74705SXin Li dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14226*67e74705SXin Li // case of ivars in class extension; all other cases have been
14227*67e74705SXin Li // reported as errors elsewhere.
14228*67e74705SXin Li // FIXME. Class extension does not have a LocEnd field.
14229*67e74705SXin Li // CDecl->setLocEnd(RBrac);
14230*67e74705SXin Li // Add ivar's to class extension's DeclContext.
14231*67e74705SXin Li // Diagnose redeclaration of private ivars.
14232*67e74705SXin Li ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14233*67e74705SXin Li for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14234*67e74705SXin Li if (IDecl) {
14235*67e74705SXin Li if (const ObjCIvarDecl *ClsIvar =
14236*67e74705SXin Li IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14237*67e74705SXin Li Diag(ClsFields[i]->getLocation(),
14238*67e74705SXin Li diag::err_duplicate_ivar_declaration);
14239*67e74705SXin Li Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14240*67e74705SXin Li continue;
14241*67e74705SXin Li }
14242*67e74705SXin Li for (const auto *Ext : IDecl->known_extensions()) {
14243*67e74705SXin Li if (const ObjCIvarDecl *ClsExtIvar
14244*67e74705SXin Li = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14245*67e74705SXin Li Diag(ClsFields[i]->getLocation(),
14246*67e74705SXin Li diag::err_duplicate_ivar_declaration);
14247*67e74705SXin Li Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14248*67e74705SXin Li continue;
14249*67e74705SXin Li }
14250*67e74705SXin Li }
14251*67e74705SXin Li }
14252*67e74705SXin Li ClsFields[i]->setLexicalDeclContext(CDecl);
14253*67e74705SXin Li CDecl->addDecl(ClsFields[i]);
14254*67e74705SXin Li }
14255*67e74705SXin Li CDecl->setIvarLBraceLoc(LBrac);
14256*67e74705SXin Li CDecl->setIvarRBraceLoc(RBrac);
14257*67e74705SXin Li }
14258*67e74705SXin Li }
14259*67e74705SXin Li
14260*67e74705SXin Li if (Attr)
14261*67e74705SXin Li ProcessDeclAttributeList(S, Record, Attr);
14262*67e74705SXin Li }
14263*67e74705SXin Li
14264*67e74705SXin Li /// \brief Determine whether the given integral value is representable within
14265*67e74705SXin Li /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)14266*67e74705SXin Li static bool isRepresentableIntegerValue(ASTContext &Context,
14267*67e74705SXin Li llvm::APSInt &Value,
14268*67e74705SXin Li QualType T) {
14269*67e74705SXin Li assert(T->isIntegralType(Context) && "Integral type required!");
14270*67e74705SXin Li unsigned BitWidth = Context.getIntWidth(T);
14271*67e74705SXin Li
14272*67e74705SXin Li if (Value.isUnsigned() || Value.isNonNegative()) {
14273*67e74705SXin Li if (T->isSignedIntegerOrEnumerationType())
14274*67e74705SXin Li --BitWidth;
14275*67e74705SXin Li return Value.getActiveBits() <= BitWidth;
14276*67e74705SXin Li }
14277*67e74705SXin Li return Value.getMinSignedBits() <= BitWidth;
14278*67e74705SXin Li }
14279*67e74705SXin Li
14280*67e74705SXin Li // \brief Given an integral type, return the next larger integral type
14281*67e74705SXin Li // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)14282*67e74705SXin Li static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14283*67e74705SXin Li // FIXME: Int128/UInt128 support, which also needs to be introduced into
14284*67e74705SXin Li // enum checking below.
14285*67e74705SXin Li assert(T->isIntegralType(Context) && "Integral type required!");
14286*67e74705SXin Li const unsigned NumTypes = 4;
14287*67e74705SXin Li QualType SignedIntegralTypes[NumTypes] = {
14288*67e74705SXin Li Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14289*67e74705SXin Li };
14290*67e74705SXin Li QualType UnsignedIntegralTypes[NumTypes] = {
14291*67e74705SXin Li Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14292*67e74705SXin Li Context.UnsignedLongLongTy
14293*67e74705SXin Li };
14294*67e74705SXin Li
14295*67e74705SXin Li unsigned BitWidth = Context.getTypeSize(T);
14296*67e74705SXin Li QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14297*67e74705SXin Li : UnsignedIntegralTypes;
14298*67e74705SXin Li for (unsigned I = 0; I != NumTypes; ++I)
14299*67e74705SXin Li if (Context.getTypeSize(Types[I]) > BitWidth)
14300*67e74705SXin Li return Types[I];
14301*67e74705SXin Li
14302*67e74705SXin Li return QualType();
14303*67e74705SXin Li }
14304*67e74705SXin Li
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)14305*67e74705SXin Li EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14306*67e74705SXin Li EnumConstantDecl *LastEnumConst,
14307*67e74705SXin Li SourceLocation IdLoc,
14308*67e74705SXin Li IdentifierInfo *Id,
14309*67e74705SXin Li Expr *Val) {
14310*67e74705SXin Li unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14311*67e74705SXin Li llvm::APSInt EnumVal(IntWidth);
14312*67e74705SXin Li QualType EltTy;
14313*67e74705SXin Li
14314*67e74705SXin Li if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14315*67e74705SXin Li Val = nullptr;
14316*67e74705SXin Li
14317*67e74705SXin Li if (Val)
14318*67e74705SXin Li Val = DefaultLvalueConversion(Val).get();
14319*67e74705SXin Li
14320*67e74705SXin Li if (Val) {
14321*67e74705SXin Li if (Enum->isDependentType() || Val->isTypeDependent())
14322*67e74705SXin Li EltTy = Context.DependentTy;
14323*67e74705SXin Li else {
14324*67e74705SXin Li SourceLocation ExpLoc;
14325*67e74705SXin Li if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14326*67e74705SXin Li !getLangOpts().MSVCCompat) {
14327*67e74705SXin Li // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14328*67e74705SXin Li // constant-expression in the enumerator-definition shall be a converted
14329*67e74705SXin Li // constant expression of the underlying type.
14330*67e74705SXin Li EltTy = Enum->getIntegerType();
14331*67e74705SXin Li ExprResult Converted =
14332*67e74705SXin Li CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14333*67e74705SXin Li CCEK_Enumerator);
14334*67e74705SXin Li if (Converted.isInvalid())
14335*67e74705SXin Li Val = nullptr;
14336*67e74705SXin Li else
14337*67e74705SXin Li Val = Converted.get();
14338*67e74705SXin Li } else if (!Val->isValueDependent() &&
14339*67e74705SXin Li !(Val = VerifyIntegerConstantExpression(Val,
14340*67e74705SXin Li &EnumVal).get())) {
14341*67e74705SXin Li // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14342*67e74705SXin Li } else {
14343*67e74705SXin Li if (Enum->isFixed()) {
14344*67e74705SXin Li EltTy = Enum->getIntegerType();
14345*67e74705SXin Li
14346*67e74705SXin Li // In Obj-C and Microsoft mode, require the enumeration value to be
14347*67e74705SXin Li // representable in the underlying type of the enumeration. In C++11,
14348*67e74705SXin Li // we perform a non-narrowing conversion as part of converted constant
14349*67e74705SXin Li // expression checking.
14350*67e74705SXin Li if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14351*67e74705SXin Li if (getLangOpts().MSVCCompat) {
14352*67e74705SXin Li Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14353*67e74705SXin Li Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14354*67e74705SXin Li } else
14355*67e74705SXin Li Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14356*67e74705SXin Li } else
14357*67e74705SXin Li Val = ImpCastExprToType(Val, EltTy,
14358*67e74705SXin Li EltTy->isBooleanType() ?
14359*67e74705SXin Li CK_IntegralToBoolean : CK_IntegralCast)
14360*67e74705SXin Li .get();
14361*67e74705SXin Li } else if (getLangOpts().CPlusPlus) {
14362*67e74705SXin Li // C++11 [dcl.enum]p5:
14363*67e74705SXin Li // If the underlying type is not fixed, the type of each enumerator
14364*67e74705SXin Li // is the type of its initializing value:
14365*67e74705SXin Li // - If an initializer is specified for an enumerator, the
14366*67e74705SXin Li // initializing value has the same type as the expression.
14367*67e74705SXin Li EltTy = Val->getType();
14368*67e74705SXin Li } else {
14369*67e74705SXin Li // C99 6.7.2.2p2:
14370*67e74705SXin Li // The expression that defines the value of an enumeration constant
14371*67e74705SXin Li // shall be an integer constant expression that has a value
14372*67e74705SXin Li // representable as an int.
14373*67e74705SXin Li
14374*67e74705SXin Li // Complain if the value is not representable in an int.
14375*67e74705SXin Li if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14376*67e74705SXin Li Diag(IdLoc, diag::ext_enum_value_not_int)
14377*67e74705SXin Li << EnumVal.toString(10) << Val->getSourceRange()
14378*67e74705SXin Li << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14379*67e74705SXin Li else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14380*67e74705SXin Li // Force the type of the expression to 'int'.
14381*67e74705SXin Li Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14382*67e74705SXin Li }
14383*67e74705SXin Li EltTy = Val->getType();
14384*67e74705SXin Li }
14385*67e74705SXin Li }
14386*67e74705SXin Li }
14387*67e74705SXin Li }
14388*67e74705SXin Li
14389*67e74705SXin Li if (!Val) {
14390*67e74705SXin Li if (Enum->isDependentType())
14391*67e74705SXin Li EltTy = Context.DependentTy;
14392*67e74705SXin Li else if (!LastEnumConst) {
14393*67e74705SXin Li // C++0x [dcl.enum]p5:
14394*67e74705SXin Li // If the underlying type is not fixed, the type of each enumerator
14395*67e74705SXin Li // is the type of its initializing value:
14396*67e74705SXin Li // - If no initializer is specified for the first enumerator, the
14397*67e74705SXin Li // initializing value has an unspecified integral type.
14398*67e74705SXin Li //
14399*67e74705SXin Li // GCC uses 'int' for its unspecified integral type, as does
14400*67e74705SXin Li // C99 6.7.2.2p3.
14401*67e74705SXin Li if (Enum->isFixed()) {
14402*67e74705SXin Li EltTy = Enum->getIntegerType();
14403*67e74705SXin Li }
14404*67e74705SXin Li else {
14405*67e74705SXin Li EltTy = Context.IntTy;
14406*67e74705SXin Li }
14407*67e74705SXin Li } else {
14408*67e74705SXin Li // Assign the last value + 1.
14409*67e74705SXin Li EnumVal = LastEnumConst->getInitVal();
14410*67e74705SXin Li ++EnumVal;
14411*67e74705SXin Li EltTy = LastEnumConst->getType();
14412*67e74705SXin Li
14413*67e74705SXin Li // Check for overflow on increment.
14414*67e74705SXin Li if (EnumVal < LastEnumConst->getInitVal()) {
14415*67e74705SXin Li // C++0x [dcl.enum]p5:
14416*67e74705SXin Li // If the underlying type is not fixed, the type of each enumerator
14417*67e74705SXin Li // is the type of its initializing value:
14418*67e74705SXin Li //
14419*67e74705SXin Li // - Otherwise the type of the initializing value is the same as
14420*67e74705SXin Li // the type of the initializing value of the preceding enumerator
14421*67e74705SXin Li // unless the incremented value is not representable in that type,
14422*67e74705SXin Li // in which case the type is an unspecified integral type
14423*67e74705SXin Li // sufficient to contain the incremented value. If no such type
14424*67e74705SXin Li // exists, the program is ill-formed.
14425*67e74705SXin Li QualType T = getNextLargerIntegralType(Context, EltTy);
14426*67e74705SXin Li if (T.isNull() || Enum->isFixed()) {
14427*67e74705SXin Li // There is no integral type larger enough to represent this
14428*67e74705SXin Li // value. Complain, then allow the value to wrap around.
14429*67e74705SXin Li EnumVal = LastEnumConst->getInitVal();
14430*67e74705SXin Li EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14431*67e74705SXin Li ++EnumVal;
14432*67e74705SXin Li if (Enum->isFixed())
14433*67e74705SXin Li // When the underlying type is fixed, this is ill-formed.
14434*67e74705SXin Li Diag(IdLoc, diag::err_enumerator_wrapped)
14435*67e74705SXin Li << EnumVal.toString(10)
14436*67e74705SXin Li << EltTy;
14437*67e74705SXin Li else
14438*67e74705SXin Li Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14439*67e74705SXin Li << EnumVal.toString(10);
14440*67e74705SXin Li } else {
14441*67e74705SXin Li EltTy = T;
14442*67e74705SXin Li }
14443*67e74705SXin Li
14444*67e74705SXin Li // Retrieve the last enumerator's value, extent that type to the
14445*67e74705SXin Li // type that is supposed to be large enough to represent the incremented
14446*67e74705SXin Li // value, then increment.
14447*67e74705SXin Li EnumVal = LastEnumConst->getInitVal();
14448*67e74705SXin Li EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14449*67e74705SXin Li EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14450*67e74705SXin Li ++EnumVal;
14451*67e74705SXin Li
14452*67e74705SXin Li // If we're not in C++, diagnose the overflow of enumerator values,
14453*67e74705SXin Li // which in C99 means that the enumerator value is not representable in
14454*67e74705SXin Li // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14455*67e74705SXin Li // permits enumerator values that are representable in some larger
14456*67e74705SXin Li // integral type.
14457*67e74705SXin Li if (!getLangOpts().CPlusPlus && !T.isNull())
14458*67e74705SXin Li Diag(IdLoc, diag::warn_enum_value_overflow);
14459*67e74705SXin Li } else if (!getLangOpts().CPlusPlus &&
14460*67e74705SXin Li !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14461*67e74705SXin Li // Enforce C99 6.7.2.2p2 even when we compute the next value.
14462*67e74705SXin Li Diag(IdLoc, diag::ext_enum_value_not_int)
14463*67e74705SXin Li << EnumVal.toString(10) << 1;
14464*67e74705SXin Li }
14465*67e74705SXin Li }
14466*67e74705SXin Li }
14467*67e74705SXin Li
14468*67e74705SXin Li if (!EltTy->isDependentType()) {
14469*67e74705SXin Li // Make the enumerator value match the signedness and size of the
14470*67e74705SXin Li // enumerator's type.
14471*67e74705SXin Li EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14472*67e74705SXin Li EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14473*67e74705SXin Li }
14474*67e74705SXin Li
14475*67e74705SXin Li return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14476*67e74705SXin Li Val, EnumVal);
14477*67e74705SXin Li }
14478*67e74705SXin Li
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)14479*67e74705SXin Li Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14480*67e74705SXin Li SourceLocation IILoc) {
14481*67e74705SXin Li if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14482*67e74705SXin Li !getLangOpts().CPlusPlus)
14483*67e74705SXin Li return SkipBodyInfo();
14484*67e74705SXin Li
14485*67e74705SXin Li // We have an anonymous enum definition. Look up the first enumerator to
14486*67e74705SXin Li // determine if we should merge the definition with an existing one and
14487*67e74705SXin Li // skip the body.
14488*67e74705SXin Li NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14489*67e74705SXin Li ForRedeclaration);
14490*67e74705SXin Li auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14491*67e74705SXin Li if (!PrevECD)
14492*67e74705SXin Li return SkipBodyInfo();
14493*67e74705SXin Li
14494*67e74705SXin Li EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14495*67e74705SXin Li NamedDecl *Hidden;
14496*67e74705SXin Li if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14497*67e74705SXin Li SkipBodyInfo Skip;
14498*67e74705SXin Li Skip.Previous = Hidden;
14499*67e74705SXin Li return Skip;
14500*67e74705SXin Li }
14501*67e74705SXin Li
14502*67e74705SXin Li return SkipBodyInfo();
14503*67e74705SXin Li }
14504*67e74705SXin Li
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,AttributeList * Attr,SourceLocation EqualLoc,Expr * Val)14505*67e74705SXin Li Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14506*67e74705SXin Li SourceLocation IdLoc, IdentifierInfo *Id,
14507*67e74705SXin Li AttributeList *Attr,
14508*67e74705SXin Li SourceLocation EqualLoc, Expr *Val) {
14509*67e74705SXin Li EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14510*67e74705SXin Li EnumConstantDecl *LastEnumConst =
14511*67e74705SXin Li cast_or_null<EnumConstantDecl>(lastEnumConst);
14512*67e74705SXin Li
14513*67e74705SXin Li // The scope passed in may not be a decl scope. Zip up the scope tree until
14514*67e74705SXin Li // we find one that is.
14515*67e74705SXin Li S = getNonFieldDeclScope(S);
14516*67e74705SXin Li
14517*67e74705SXin Li // Verify that there isn't already something declared with this name in this
14518*67e74705SXin Li // scope.
14519*67e74705SXin Li NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14520*67e74705SXin Li ForRedeclaration);
14521*67e74705SXin Li if (PrevDecl && PrevDecl->isTemplateParameter()) {
14522*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
14523*67e74705SXin Li DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14524*67e74705SXin Li // Just pretend that we didn't see the previous declaration.
14525*67e74705SXin Li PrevDecl = nullptr;
14526*67e74705SXin Li }
14527*67e74705SXin Li
14528*67e74705SXin Li // C++ [class.mem]p15:
14529*67e74705SXin Li // If T is the name of a class, then each of the following shall have a name
14530*67e74705SXin Li // different from T:
14531*67e74705SXin Li // - every enumerator of every member of class T that is an unscoped
14532*67e74705SXin Li // enumerated type
14533*67e74705SXin Li if (!TheEnumDecl->isScoped())
14534*67e74705SXin Li DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14535*67e74705SXin Li DeclarationNameInfo(Id, IdLoc));
14536*67e74705SXin Li
14537*67e74705SXin Li EnumConstantDecl *New =
14538*67e74705SXin Li CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14539*67e74705SXin Li if (!New)
14540*67e74705SXin Li return nullptr;
14541*67e74705SXin Li
14542*67e74705SXin Li if (PrevDecl) {
14543*67e74705SXin Li // When in C++, we may get a TagDecl with the same name; in this case the
14544*67e74705SXin Li // enum constant will 'hide' the tag.
14545*67e74705SXin Li assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14546*67e74705SXin Li "Received TagDecl when not in C++!");
14547*67e74705SXin Li if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14548*67e74705SXin Li shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14549*67e74705SXin Li if (isa<EnumConstantDecl>(PrevDecl))
14550*67e74705SXin Li Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14551*67e74705SXin Li else
14552*67e74705SXin Li Diag(IdLoc, diag::err_redefinition) << Id;
14553*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14554*67e74705SXin Li return nullptr;
14555*67e74705SXin Li }
14556*67e74705SXin Li }
14557*67e74705SXin Li
14558*67e74705SXin Li // Process attributes.
14559*67e74705SXin Li if (Attr) ProcessDeclAttributeList(S, New, Attr);
14560*67e74705SXin Li
14561*67e74705SXin Li // Register this decl in the current scope stack.
14562*67e74705SXin Li New->setAccess(TheEnumDecl->getAccess());
14563*67e74705SXin Li PushOnScopeChains(New, S);
14564*67e74705SXin Li
14565*67e74705SXin Li ActOnDocumentableDecl(New);
14566*67e74705SXin Li
14567*67e74705SXin Li return New;
14568*67e74705SXin Li }
14569*67e74705SXin Li
14570*67e74705SXin Li // Returns true when the enum initial expression does not trigger the
14571*67e74705SXin Li // duplicate enum warning. A few common cases are exempted as follows:
14572*67e74705SXin Li // Element2 = Element1
14573*67e74705SXin Li // Element2 = Element1 + 1
14574*67e74705SXin Li // Element2 = Element1 - 1
14575*67e74705SXin Li // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)14576*67e74705SXin Li static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14577*67e74705SXin Li Expr *InitExpr = ECD->getInitExpr();
14578*67e74705SXin Li if (!InitExpr)
14579*67e74705SXin Li return true;
14580*67e74705SXin Li InitExpr = InitExpr->IgnoreImpCasts();
14581*67e74705SXin Li
14582*67e74705SXin Li if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14583*67e74705SXin Li if (!BO->isAdditiveOp())
14584*67e74705SXin Li return true;
14585*67e74705SXin Li IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14586*67e74705SXin Li if (!IL)
14587*67e74705SXin Li return true;
14588*67e74705SXin Li if (IL->getValue() != 1)
14589*67e74705SXin Li return true;
14590*67e74705SXin Li
14591*67e74705SXin Li InitExpr = BO->getLHS();
14592*67e74705SXin Li }
14593*67e74705SXin Li
14594*67e74705SXin Li // This checks if the elements are from the same enum.
14595*67e74705SXin Li DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14596*67e74705SXin Li if (!DRE)
14597*67e74705SXin Li return true;
14598*67e74705SXin Li
14599*67e74705SXin Li EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14600*67e74705SXin Li if (!EnumConstant)
14601*67e74705SXin Li return true;
14602*67e74705SXin Li
14603*67e74705SXin Li if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14604*67e74705SXin Li Enum)
14605*67e74705SXin Li return true;
14606*67e74705SXin Li
14607*67e74705SXin Li return false;
14608*67e74705SXin Li }
14609*67e74705SXin Li
14610*67e74705SXin Li namespace {
14611*67e74705SXin Li struct DupKey {
14612*67e74705SXin Li int64_t val;
14613*67e74705SXin Li bool isTombstoneOrEmptyKey;
DupKey__anon7a8358650b11::DupKey14614*67e74705SXin Li DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14615*67e74705SXin Li : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14616*67e74705SXin Li };
14617*67e74705SXin Li
GetDupKey(const llvm::APSInt & Val)14618*67e74705SXin Li static DupKey GetDupKey(const llvm::APSInt& Val) {
14619*67e74705SXin Li return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14620*67e74705SXin Li false);
14621*67e74705SXin Li }
14622*67e74705SXin Li
14623*67e74705SXin Li struct DenseMapInfoDupKey {
getEmptyKey__anon7a8358650b11::DenseMapInfoDupKey14624*67e74705SXin Li static DupKey getEmptyKey() { return DupKey(0, true); }
getTombstoneKey__anon7a8358650b11::DenseMapInfoDupKey14625*67e74705SXin Li static DupKey getTombstoneKey() { return DupKey(1, true); }
getHashValue__anon7a8358650b11::DenseMapInfoDupKey14626*67e74705SXin Li static unsigned getHashValue(const DupKey Key) {
14627*67e74705SXin Li return (unsigned)(Key.val * 37);
14628*67e74705SXin Li }
isEqual__anon7a8358650b11::DenseMapInfoDupKey14629*67e74705SXin Li static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14630*67e74705SXin Li return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14631*67e74705SXin Li LHS.val == RHS.val;
14632*67e74705SXin Li }
14633*67e74705SXin Li };
14634*67e74705SXin Li } // end anonymous namespace
14635*67e74705SXin Li
14636*67e74705SXin Li // Emits a warning when an element is implicitly set a value that
14637*67e74705SXin Li // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)14638*67e74705SXin Li static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14639*67e74705SXin Li EnumDecl *Enum,
14640*67e74705SXin Li QualType EnumType) {
14641*67e74705SXin Li if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14642*67e74705SXin Li return;
14643*67e74705SXin Li // Avoid anonymous enums
14644*67e74705SXin Li if (!Enum->getIdentifier())
14645*67e74705SXin Li return;
14646*67e74705SXin Li
14647*67e74705SXin Li // Only check for small enums.
14648*67e74705SXin Li if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14649*67e74705SXin Li return;
14650*67e74705SXin Li
14651*67e74705SXin Li typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14652*67e74705SXin Li typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14653*67e74705SXin Li
14654*67e74705SXin Li typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14655*67e74705SXin Li typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14656*67e74705SXin Li ValueToVectorMap;
14657*67e74705SXin Li
14658*67e74705SXin Li DuplicatesVector DupVector;
14659*67e74705SXin Li ValueToVectorMap EnumMap;
14660*67e74705SXin Li
14661*67e74705SXin Li // Populate the EnumMap with all values represented by enum constants without
14662*67e74705SXin Li // an initialier.
14663*67e74705SXin Li for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14664*67e74705SXin Li EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14665*67e74705SXin Li
14666*67e74705SXin Li // Null EnumConstantDecl means a previous diagnostic has been emitted for
14667*67e74705SXin Li // this constant. Skip this enum since it may be ill-formed.
14668*67e74705SXin Li if (!ECD) {
14669*67e74705SXin Li return;
14670*67e74705SXin Li }
14671*67e74705SXin Li
14672*67e74705SXin Li if (ECD->getInitExpr())
14673*67e74705SXin Li continue;
14674*67e74705SXin Li
14675*67e74705SXin Li DupKey Key = GetDupKey(ECD->getInitVal());
14676*67e74705SXin Li DeclOrVector &Entry = EnumMap[Key];
14677*67e74705SXin Li
14678*67e74705SXin Li // First time encountering this value.
14679*67e74705SXin Li if (Entry.isNull())
14680*67e74705SXin Li Entry = ECD;
14681*67e74705SXin Li }
14682*67e74705SXin Li
14683*67e74705SXin Li // Create vectors for any values that has duplicates.
14684*67e74705SXin Li for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14685*67e74705SXin Li EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14686*67e74705SXin Li if (!ValidDuplicateEnum(ECD, Enum))
14687*67e74705SXin Li continue;
14688*67e74705SXin Li
14689*67e74705SXin Li DupKey Key = GetDupKey(ECD->getInitVal());
14690*67e74705SXin Li
14691*67e74705SXin Li DeclOrVector& Entry = EnumMap[Key];
14692*67e74705SXin Li if (Entry.isNull())
14693*67e74705SXin Li continue;
14694*67e74705SXin Li
14695*67e74705SXin Li if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14696*67e74705SXin Li // Ensure constants are different.
14697*67e74705SXin Li if (D == ECD)
14698*67e74705SXin Li continue;
14699*67e74705SXin Li
14700*67e74705SXin Li // Create new vector and push values onto it.
14701*67e74705SXin Li ECDVector *Vec = new ECDVector();
14702*67e74705SXin Li Vec->push_back(D);
14703*67e74705SXin Li Vec->push_back(ECD);
14704*67e74705SXin Li
14705*67e74705SXin Li // Update entry to point to the duplicates vector.
14706*67e74705SXin Li Entry = Vec;
14707*67e74705SXin Li
14708*67e74705SXin Li // Store the vector somewhere we can consult later for quick emission of
14709*67e74705SXin Li // diagnostics.
14710*67e74705SXin Li DupVector.push_back(Vec);
14711*67e74705SXin Li continue;
14712*67e74705SXin Li }
14713*67e74705SXin Li
14714*67e74705SXin Li ECDVector *Vec = Entry.get<ECDVector*>();
14715*67e74705SXin Li // Make sure constants are not added more than once.
14716*67e74705SXin Li if (*Vec->begin() == ECD)
14717*67e74705SXin Li continue;
14718*67e74705SXin Li
14719*67e74705SXin Li Vec->push_back(ECD);
14720*67e74705SXin Li }
14721*67e74705SXin Li
14722*67e74705SXin Li // Emit diagnostics.
14723*67e74705SXin Li for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14724*67e74705SXin Li DupVectorEnd = DupVector.end();
14725*67e74705SXin Li DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14726*67e74705SXin Li ECDVector *Vec = *DupVectorIter;
14727*67e74705SXin Li assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14728*67e74705SXin Li
14729*67e74705SXin Li // Emit warning for one enum constant.
14730*67e74705SXin Li ECDVector::iterator I = Vec->begin();
14731*67e74705SXin Li S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14732*67e74705SXin Li << (*I)->getName() << (*I)->getInitVal().toString(10)
14733*67e74705SXin Li << (*I)->getSourceRange();
14734*67e74705SXin Li ++I;
14735*67e74705SXin Li
14736*67e74705SXin Li // Emit one note for each of the remaining enum constants with
14737*67e74705SXin Li // the same value.
14738*67e74705SXin Li for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14739*67e74705SXin Li S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14740*67e74705SXin Li << (*I)->getName() << (*I)->getInitVal().toString(10)
14741*67e74705SXin Li << (*I)->getSourceRange();
14742*67e74705SXin Li delete Vec;
14743*67e74705SXin Li }
14744*67e74705SXin Li }
14745*67e74705SXin Li
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const14746*67e74705SXin Li bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14747*67e74705SXin Li bool AllowMask) const {
14748*67e74705SXin Li assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14749*67e74705SXin Li assert(ED->isCompleteDefinition() && "expected enum definition");
14750*67e74705SXin Li
14751*67e74705SXin Li auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14752*67e74705SXin Li llvm::APInt &FlagBits = R.first->second;
14753*67e74705SXin Li
14754*67e74705SXin Li if (R.second) {
14755*67e74705SXin Li for (auto *E : ED->enumerators()) {
14756*67e74705SXin Li const auto &EVal = E->getInitVal();
14757*67e74705SXin Li // Only single-bit enumerators introduce new flag values.
14758*67e74705SXin Li if (EVal.isPowerOf2())
14759*67e74705SXin Li FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14760*67e74705SXin Li }
14761*67e74705SXin Li }
14762*67e74705SXin Li
14763*67e74705SXin Li // A value is in a flag enum if either its bits are a subset of the enum's
14764*67e74705SXin Li // flag bits (the first condition) or we are allowing masks and the same is
14765*67e74705SXin Li // true of its complement (the second condition). When masks are allowed, we
14766*67e74705SXin Li // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14767*67e74705SXin Li //
14768*67e74705SXin Li // While it's true that any value could be used as a mask, the assumption is
14769*67e74705SXin Li // that a mask will have all of the insignificant bits set. Anything else is
14770*67e74705SXin Li // likely a logic error.
14771*67e74705SXin Li llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14772*67e74705SXin Li return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14773*67e74705SXin Li }
14774*67e74705SXin Li
ActOnEnumBody(SourceLocation EnumLoc,SourceLocation LBraceLoc,SourceLocation RBraceLoc,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,AttributeList * Attr)14775*67e74705SXin Li void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14776*67e74705SXin Li SourceLocation RBraceLoc, Decl *EnumDeclX,
14777*67e74705SXin Li ArrayRef<Decl *> Elements,
14778*67e74705SXin Li Scope *S, AttributeList *Attr) {
14779*67e74705SXin Li EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14780*67e74705SXin Li QualType EnumType = Context.getTypeDeclType(Enum);
14781*67e74705SXin Li
14782*67e74705SXin Li if (Attr)
14783*67e74705SXin Li ProcessDeclAttributeList(S, Enum, Attr);
14784*67e74705SXin Li
14785*67e74705SXin Li if (Enum->isDependentType()) {
14786*67e74705SXin Li for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14787*67e74705SXin Li EnumConstantDecl *ECD =
14788*67e74705SXin Li cast_or_null<EnumConstantDecl>(Elements[i]);
14789*67e74705SXin Li if (!ECD) continue;
14790*67e74705SXin Li
14791*67e74705SXin Li ECD->setType(EnumType);
14792*67e74705SXin Li }
14793*67e74705SXin Li
14794*67e74705SXin Li Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14795*67e74705SXin Li return;
14796*67e74705SXin Li }
14797*67e74705SXin Li
14798*67e74705SXin Li // TODO: If the result value doesn't fit in an int, it must be a long or long
14799*67e74705SXin Li // long value. ISO C does not support this, but GCC does as an extension,
14800*67e74705SXin Li // emit a warning.
14801*67e74705SXin Li unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14802*67e74705SXin Li unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14803*67e74705SXin Li unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14804*67e74705SXin Li
14805*67e74705SXin Li // Verify that all the values are okay, compute the size of the values, and
14806*67e74705SXin Li // reverse the list.
14807*67e74705SXin Li unsigned NumNegativeBits = 0;
14808*67e74705SXin Li unsigned NumPositiveBits = 0;
14809*67e74705SXin Li
14810*67e74705SXin Li // Keep track of whether all elements have type int.
14811*67e74705SXin Li bool AllElementsInt = true;
14812*67e74705SXin Li
14813*67e74705SXin Li for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14814*67e74705SXin Li EnumConstantDecl *ECD =
14815*67e74705SXin Li cast_or_null<EnumConstantDecl>(Elements[i]);
14816*67e74705SXin Li if (!ECD) continue; // Already issued a diagnostic.
14817*67e74705SXin Li
14818*67e74705SXin Li const llvm::APSInt &InitVal = ECD->getInitVal();
14819*67e74705SXin Li
14820*67e74705SXin Li // Keep track of the size of positive and negative values.
14821*67e74705SXin Li if (InitVal.isUnsigned() || InitVal.isNonNegative())
14822*67e74705SXin Li NumPositiveBits = std::max(NumPositiveBits,
14823*67e74705SXin Li (unsigned)InitVal.getActiveBits());
14824*67e74705SXin Li else
14825*67e74705SXin Li NumNegativeBits = std::max(NumNegativeBits,
14826*67e74705SXin Li (unsigned)InitVal.getMinSignedBits());
14827*67e74705SXin Li
14828*67e74705SXin Li // Keep track of whether every enum element has type int (very commmon).
14829*67e74705SXin Li if (AllElementsInt)
14830*67e74705SXin Li AllElementsInt = ECD->getType() == Context.IntTy;
14831*67e74705SXin Li }
14832*67e74705SXin Li
14833*67e74705SXin Li // Figure out the type that should be used for this enum.
14834*67e74705SXin Li QualType BestType;
14835*67e74705SXin Li unsigned BestWidth;
14836*67e74705SXin Li
14837*67e74705SXin Li // C++0x N3000 [conv.prom]p3:
14838*67e74705SXin Li // An rvalue of an unscoped enumeration type whose underlying
14839*67e74705SXin Li // type is not fixed can be converted to an rvalue of the first
14840*67e74705SXin Li // of the following types that can represent all the values of
14841*67e74705SXin Li // the enumeration: int, unsigned int, long int, unsigned long
14842*67e74705SXin Li // int, long long int, or unsigned long long int.
14843*67e74705SXin Li // C99 6.4.4.3p2:
14844*67e74705SXin Li // An identifier declared as an enumeration constant has type int.
14845*67e74705SXin Li // The C99 rule is modified by a gcc extension
14846*67e74705SXin Li QualType BestPromotionType;
14847*67e74705SXin Li
14848*67e74705SXin Li bool Packed = Enum->hasAttr<PackedAttr>();
14849*67e74705SXin Li // -fshort-enums is the equivalent to specifying the packed attribute on all
14850*67e74705SXin Li // enum definitions.
14851*67e74705SXin Li if (LangOpts.ShortEnums)
14852*67e74705SXin Li Packed = true;
14853*67e74705SXin Li
14854*67e74705SXin Li if (Enum->isFixed()) {
14855*67e74705SXin Li BestType = Enum->getIntegerType();
14856*67e74705SXin Li if (BestType->isPromotableIntegerType())
14857*67e74705SXin Li BestPromotionType = Context.getPromotedIntegerType(BestType);
14858*67e74705SXin Li else
14859*67e74705SXin Li BestPromotionType = BestType;
14860*67e74705SXin Li
14861*67e74705SXin Li BestWidth = Context.getIntWidth(BestType);
14862*67e74705SXin Li }
14863*67e74705SXin Li else if (NumNegativeBits) {
14864*67e74705SXin Li // If there is a negative value, figure out the smallest integer type (of
14865*67e74705SXin Li // int/long/longlong) that fits.
14866*67e74705SXin Li // If it's packed, check also if it fits a char or a short.
14867*67e74705SXin Li if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14868*67e74705SXin Li BestType = Context.SignedCharTy;
14869*67e74705SXin Li BestWidth = CharWidth;
14870*67e74705SXin Li } else if (Packed && NumNegativeBits <= ShortWidth &&
14871*67e74705SXin Li NumPositiveBits < ShortWidth) {
14872*67e74705SXin Li BestType = Context.ShortTy;
14873*67e74705SXin Li BestWidth = ShortWidth;
14874*67e74705SXin Li } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14875*67e74705SXin Li BestType = Context.IntTy;
14876*67e74705SXin Li BestWidth = IntWidth;
14877*67e74705SXin Li } else {
14878*67e74705SXin Li BestWidth = Context.getTargetInfo().getLongWidth();
14879*67e74705SXin Li
14880*67e74705SXin Li if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14881*67e74705SXin Li BestType = Context.LongTy;
14882*67e74705SXin Li } else {
14883*67e74705SXin Li BestWidth = Context.getTargetInfo().getLongLongWidth();
14884*67e74705SXin Li
14885*67e74705SXin Li if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14886*67e74705SXin Li Diag(Enum->getLocation(), diag::ext_enum_too_large);
14887*67e74705SXin Li BestType = Context.LongLongTy;
14888*67e74705SXin Li }
14889*67e74705SXin Li }
14890*67e74705SXin Li BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14891*67e74705SXin Li } else {
14892*67e74705SXin Li // If there is no negative value, figure out the smallest type that fits
14893*67e74705SXin Li // all of the enumerator values.
14894*67e74705SXin Li // If it's packed, check also if it fits a char or a short.
14895*67e74705SXin Li if (Packed && NumPositiveBits <= CharWidth) {
14896*67e74705SXin Li BestType = Context.UnsignedCharTy;
14897*67e74705SXin Li BestPromotionType = Context.IntTy;
14898*67e74705SXin Li BestWidth = CharWidth;
14899*67e74705SXin Li } else if (Packed && NumPositiveBits <= ShortWidth) {
14900*67e74705SXin Li BestType = Context.UnsignedShortTy;
14901*67e74705SXin Li BestPromotionType = Context.IntTy;
14902*67e74705SXin Li BestWidth = ShortWidth;
14903*67e74705SXin Li } else if (NumPositiveBits <= IntWidth) {
14904*67e74705SXin Li BestType = Context.UnsignedIntTy;
14905*67e74705SXin Li BestWidth = IntWidth;
14906*67e74705SXin Li BestPromotionType
14907*67e74705SXin Li = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14908*67e74705SXin Li ? Context.UnsignedIntTy : Context.IntTy;
14909*67e74705SXin Li } else if (NumPositiveBits <=
14910*67e74705SXin Li (BestWidth = Context.getTargetInfo().getLongWidth())) {
14911*67e74705SXin Li BestType = Context.UnsignedLongTy;
14912*67e74705SXin Li BestPromotionType
14913*67e74705SXin Li = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14914*67e74705SXin Li ? Context.UnsignedLongTy : Context.LongTy;
14915*67e74705SXin Li } else {
14916*67e74705SXin Li BestWidth = Context.getTargetInfo().getLongLongWidth();
14917*67e74705SXin Li assert(NumPositiveBits <= BestWidth &&
14918*67e74705SXin Li "How could an initializer get larger than ULL?");
14919*67e74705SXin Li BestType = Context.UnsignedLongLongTy;
14920*67e74705SXin Li BestPromotionType
14921*67e74705SXin Li = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14922*67e74705SXin Li ? Context.UnsignedLongLongTy : Context.LongLongTy;
14923*67e74705SXin Li }
14924*67e74705SXin Li }
14925*67e74705SXin Li
14926*67e74705SXin Li // Loop over all of the enumerator constants, changing their types to match
14927*67e74705SXin Li // the type of the enum if needed.
14928*67e74705SXin Li for (auto *D : Elements) {
14929*67e74705SXin Li auto *ECD = cast_or_null<EnumConstantDecl>(D);
14930*67e74705SXin Li if (!ECD) continue; // Already issued a diagnostic.
14931*67e74705SXin Li
14932*67e74705SXin Li // Standard C says the enumerators have int type, but we allow, as an
14933*67e74705SXin Li // extension, the enumerators to be larger than int size. If each
14934*67e74705SXin Li // enumerator value fits in an int, type it as an int, otherwise type it the
14935*67e74705SXin Li // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14936*67e74705SXin Li // that X has type 'int', not 'unsigned'.
14937*67e74705SXin Li
14938*67e74705SXin Li // Determine whether the value fits into an int.
14939*67e74705SXin Li llvm::APSInt InitVal = ECD->getInitVal();
14940*67e74705SXin Li
14941*67e74705SXin Li // If it fits into an integer type, force it. Otherwise force it to match
14942*67e74705SXin Li // the enum decl type.
14943*67e74705SXin Li QualType NewTy;
14944*67e74705SXin Li unsigned NewWidth;
14945*67e74705SXin Li bool NewSign;
14946*67e74705SXin Li if (!getLangOpts().CPlusPlus &&
14947*67e74705SXin Li !Enum->isFixed() &&
14948*67e74705SXin Li isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14949*67e74705SXin Li NewTy = Context.IntTy;
14950*67e74705SXin Li NewWidth = IntWidth;
14951*67e74705SXin Li NewSign = true;
14952*67e74705SXin Li } else if (ECD->getType() == BestType) {
14953*67e74705SXin Li // Already the right type!
14954*67e74705SXin Li if (getLangOpts().CPlusPlus)
14955*67e74705SXin Li // C++ [dcl.enum]p4: Following the closing brace of an
14956*67e74705SXin Li // enum-specifier, each enumerator has the type of its
14957*67e74705SXin Li // enumeration.
14958*67e74705SXin Li ECD->setType(EnumType);
14959*67e74705SXin Li continue;
14960*67e74705SXin Li } else {
14961*67e74705SXin Li NewTy = BestType;
14962*67e74705SXin Li NewWidth = BestWidth;
14963*67e74705SXin Li NewSign = BestType->isSignedIntegerOrEnumerationType();
14964*67e74705SXin Li }
14965*67e74705SXin Li
14966*67e74705SXin Li // Adjust the APSInt value.
14967*67e74705SXin Li InitVal = InitVal.extOrTrunc(NewWidth);
14968*67e74705SXin Li InitVal.setIsSigned(NewSign);
14969*67e74705SXin Li ECD->setInitVal(InitVal);
14970*67e74705SXin Li
14971*67e74705SXin Li // Adjust the Expr initializer and type.
14972*67e74705SXin Li if (ECD->getInitExpr() &&
14973*67e74705SXin Li !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14974*67e74705SXin Li ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14975*67e74705SXin Li CK_IntegralCast,
14976*67e74705SXin Li ECD->getInitExpr(),
14977*67e74705SXin Li /*base paths*/ nullptr,
14978*67e74705SXin Li VK_RValue));
14979*67e74705SXin Li if (getLangOpts().CPlusPlus)
14980*67e74705SXin Li // C++ [dcl.enum]p4: Following the closing brace of an
14981*67e74705SXin Li // enum-specifier, each enumerator has the type of its
14982*67e74705SXin Li // enumeration.
14983*67e74705SXin Li ECD->setType(EnumType);
14984*67e74705SXin Li else
14985*67e74705SXin Li ECD->setType(NewTy);
14986*67e74705SXin Li }
14987*67e74705SXin Li
14988*67e74705SXin Li Enum->completeDefinition(BestType, BestPromotionType,
14989*67e74705SXin Li NumPositiveBits, NumNegativeBits);
14990*67e74705SXin Li
14991*67e74705SXin Li CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14992*67e74705SXin Li
14993*67e74705SXin Li if (Enum->hasAttr<FlagEnumAttr>()) {
14994*67e74705SXin Li for (Decl *D : Elements) {
14995*67e74705SXin Li EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14996*67e74705SXin Li if (!ECD) continue; // Already issued a diagnostic.
14997*67e74705SXin Li
14998*67e74705SXin Li llvm::APSInt InitVal = ECD->getInitVal();
14999*67e74705SXin Li if (InitVal != 0 && !InitVal.isPowerOf2() &&
15000*67e74705SXin Li !IsValueInFlagEnum(Enum, InitVal, true))
15001*67e74705SXin Li Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15002*67e74705SXin Li << ECD << Enum;
15003*67e74705SXin Li }
15004*67e74705SXin Li }
15005*67e74705SXin Li
15006*67e74705SXin Li // Now that the enum type is defined, ensure it's not been underaligned.
15007*67e74705SXin Li if (Enum->hasAttrs())
15008*67e74705SXin Li CheckAlignasUnderalignment(Enum);
15009*67e74705SXin Li }
15010*67e74705SXin Li
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)15011*67e74705SXin Li Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15012*67e74705SXin Li SourceLocation StartLoc,
15013*67e74705SXin Li SourceLocation EndLoc) {
15014*67e74705SXin Li StringLiteral *AsmString = cast<StringLiteral>(expr);
15015*67e74705SXin Li
15016*67e74705SXin Li FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15017*67e74705SXin Li AsmString, StartLoc,
15018*67e74705SXin Li EndLoc);
15019*67e74705SXin Li CurContext->addDecl(New);
15020*67e74705SXin Li return New;
15021*67e74705SXin Li }
15022*67e74705SXin Li
checkModuleImportContext(Sema & S,Module * M,SourceLocation ImportLoc,DeclContext * DC,bool FromInclude=false)15023*67e74705SXin Li static void checkModuleImportContext(Sema &S, Module *M,
15024*67e74705SXin Li SourceLocation ImportLoc, DeclContext *DC,
15025*67e74705SXin Li bool FromInclude = false) {
15026*67e74705SXin Li SourceLocation ExternCLoc;
15027*67e74705SXin Li
15028*67e74705SXin Li if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15029*67e74705SXin Li switch (LSD->getLanguage()) {
15030*67e74705SXin Li case LinkageSpecDecl::lang_c:
15031*67e74705SXin Li if (ExternCLoc.isInvalid())
15032*67e74705SXin Li ExternCLoc = LSD->getLocStart();
15033*67e74705SXin Li break;
15034*67e74705SXin Li case LinkageSpecDecl::lang_cxx:
15035*67e74705SXin Li break;
15036*67e74705SXin Li }
15037*67e74705SXin Li DC = LSD->getParent();
15038*67e74705SXin Li }
15039*67e74705SXin Li
15040*67e74705SXin Li while (isa<LinkageSpecDecl>(DC))
15041*67e74705SXin Li DC = DC->getParent();
15042*67e74705SXin Li
15043*67e74705SXin Li if (!isa<TranslationUnitDecl>(DC)) {
15044*67e74705SXin Li S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15045*67e74705SXin Li ? diag::ext_module_import_not_at_top_level_noop
15046*67e74705SXin Li : diag::err_module_import_not_at_top_level_fatal)
15047*67e74705SXin Li << M->getFullModuleName() << DC;
15048*67e74705SXin Li S.Diag(cast<Decl>(DC)->getLocStart(),
15049*67e74705SXin Li diag::note_module_import_not_at_top_level) << DC;
15050*67e74705SXin Li } else if (!M->IsExternC && ExternCLoc.isValid()) {
15051*67e74705SXin Li S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15052*67e74705SXin Li << M->getFullModuleName();
15053*67e74705SXin Li S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15054*67e74705SXin Li }
15055*67e74705SXin Li }
15056*67e74705SXin Li
diagnoseMisplacedModuleImport(Module * M,SourceLocation ImportLoc)15057*67e74705SXin Li void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15058*67e74705SXin Li return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15059*67e74705SXin Li }
15060*67e74705SXin Li
ActOnModuleImport(SourceLocation AtLoc,SourceLocation ImportLoc,ModuleIdPath Path)15061*67e74705SXin Li DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
15062*67e74705SXin Li SourceLocation ImportLoc,
15063*67e74705SXin Li ModuleIdPath Path) {
15064*67e74705SXin Li Module *Mod =
15065*67e74705SXin Li getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15066*67e74705SXin Li /*IsIncludeDirective=*/false);
15067*67e74705SXin Li if (!Mod)
15068*67e74705SXin Li return true;
15069*67e74705SXin Li
15070*67e74705SXin Li VisibleModules.setVisible(Mod, ImportLoc);
15071*67e74705SXin Li
15072*67e74705SXin Li checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15073*67e74705SXin Li
15074*67e74705SXin Li // FIXME: we should support importing a submodule within a different submodule
15075*67e74705SXin Li // of the same top-level module. Until we do, make it an error rather than
15076*67e74705SXin Li // silently ignoring the import.
15077*67e74705SXin Li if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
15078*67e74705SXin Li Diag(ImportLoc, getLangOpts().CompilingModule
15079*67e74705SXin Li ? diag::err_module_self_import
15080*67e74705SXin Li : diag::err_module_import_in_implementation)
15081*67e74705SXin Li << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15082*67e74705SXin Li
15083*67e74705SXin Li SmallVector<SourceLocation, 2> IdentifierLocs;
15084*67e74705SXin Li Module *ModCheck = Mod;
15085*67e74705SXin Li for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15086*67e74705SXin Li // If we've run out of module parents, just drop the remaining identifiers.
15087*67e74705SXin Li // We need the length to be consistent.
15088*67e74705SXin Li if (!ModCheck)
15089*67e74705SXin Li break;
15090*67e74705SXin Li ModCheck = ModCheck->Parent;
15091*67e74705SXin Li
15092*67e74705SXin Li IdentifierLocs.push_back(Path[I].second);
15093*67e74705SXin Li }
15094*67e74705SXin Li
15095*67e74705SXin Li ImportDecl *Import = ImportDecl::Create(Context,
15096*67e74705SXin Li Context.getTranslationUnitDecl(),
15097*67e74705SXin Li AtLoc.isValid()? AtLoc : ImportLoc,
15098*67e74705SXin Li Mod, IdentifierLocs);
15099*67e74705SXin Li Context.getTranslationUnitDecl()->addDecl(Import);
15100*67e74705SXin Li return Import;
15101*67e74705SXin Li }
15102*67e74705SXin Li
ActOnModuleInclude(SourceLocation DirectiveLoc,Module * Mod)15103*67e74705SXin Li void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15104*67e74705SXin Li checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15105*67e74705SXin Li
15106*67e74705SXin Li // Determine whether we're in the #include buffer for a module. The #includes
15107*67e74705SXin Li // in that buffer do not qualify as module imports; they're just an
15108*67e74705SXin Li // implementation detail of us building the module.
15109*67e74705SXin Li //
15110*67e74705SXin Li // FIXME: Should we even get ActOnModuleInclude calls for those?
15111*67e74705SXin Li bool IsInModuleIncludes =
15112*67e74705SXin Li TUKind == TU_Module &&
15113*67e74705SXin Li getSourceManager().isWrittenInMainFile(DirectiveLoc);
15114*67e74705SXin Li
15115*67e74705SXin Li // Similarly, if we're in the implementation of a module, don't
15116*67e74705SXin Li // synthesize an illegal module import. FIXME: Why not?
15117*67e74705SXin Li bool ShouldAddImport =
15118*67e74705SXin Li !IsInModuleIncludes &&
15119*67e74705SXin Li (getLangOpts().CompilingModule ||
15120*67e74705SXin Li getLangOpts().CurrentModule.empty() ||
15121*67e74705SXin Li getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15122*67e74705SXin Li
15123*67e74705SXin Li // If this module import was due to an inclusion directive, create an
15124*67e74705SXin Li // implicit import declaration to capture it in the AST.
15125*67e74705SXin Li if (ShouldAddImport) {
15126*67e74705SXin Li TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15127*67e74705SXin Li ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15128*67e74705SXin Li DirectiveLoc, Mod,
15129*67e74705SXin Li DirectiveLoc);
15130*67e74705SXin Li TU->addDecl(ImportD);
15131*67e74705SXin Li Consumer.HandleImplicitImportDecl(ImportD);
15132*67e74705SXin Li }
15133*67e74705SXin Li
15134*67e74705SXin Li getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15135*67e74705SXin Li VisibleModules.setVisible(Mod, DirectiveLoc);
15136*67e74705SXin Li }
15137*67e74705SXin Li
ActOnModuleBegin(SourceLocation DirectiveLoc,Module * Mod)15138*67e74705SXin Li void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15139*67e74705SXin Li checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15140*67e74705SXin Li
15141*67e74705SXin Li if (getLangOpts().ModulesLocalVisibility)
15142*67e74705SXin Li VisibleModulesStack.push_back(std::move(VisibleModules));
15143*67e74705SXin Li VisibleModules.setVisible(Mod, DirectiveLoc);
15144*67e74705SXin Li }
15145*67e74705SXin Li
ActOnModuleEnd(SourceLocation DirectiveLoc,Module * Mod)15146*67e74705SXin Li void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15147*67e74705SXin Li checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15148*67e74705SXin Li
15149*67e74705SXin Li if (getLangOpts().ModulesLocalVisibility) {
15150*67e74705SXin Li VisibleModules = std::move(VisibleModulesStack.back());
15151*67e74705SXin Li VisibleModulesStack.pop_back();
15152*67e74705SXin Li VisibleModules.setVisible(Mod, DirectiveLoc);
15153*67e74705SXin Li // Leaving a module hides namespace names, so our visible namespace cache
15154*67e74705SXin Li // is now out of date.
15155*67e74705SXin Li VisibleNamespaceCache.clear();
15156*67e74705SXin Li }
15157*67e74705SXin Li }
15158*67e74705SXin Li
createImplicitModuleImportForErrorRecovery(SourceLocation Loc,Module * Mod)15159*67e74705SXin Li void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15160*67e74705SXin Li Module *Mod) {
15161*67e74705SXin Li // Bail if we're not allowed to implicitly import a module here.
15162*67e74705SXin Li if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15163*67e74705SXin Li return;
15164*67e74705SXin Li
15165*67e74705SXin Li // Create the implicit import declaration.
15166*67e74705SXin Li TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15167*67e74705SXin Li ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15168*67e74705SXin Li Loc, Mod, Loc);
15169*67e74705SXin Li TU->addDecl(ImportD);
15170*67e74705SXin Li Consumer.HandleImplicitImportDecl(ImportD);
15171*67e74705SXin Li
15172*67e74705SXin Li // Make the module visible.
15173*67e74705SXin Li getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15174*67e74705SXin Li VisibleModules.setVisible(Mod, Loc);
15175*67e74705SXin Li }
15176*67e74705SXin Li
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)15177*67e74705SXin Li void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15178*67e74705SXin Li IdentifierInfo* AliasName,
15179*67e74705SXin Li SourceLocation PragmaLoc,
15180*67e74705SXin Li SourceLocation NameLoc,
15181*67e74705SXin Li SourceLocation AliasNameLoc) {
15182*67e74705SXin Li NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15183*67e74705SXin Li LookupOrdinaryName);
15184*67e74705SXin Li AsmLabelAttr *Attr =
15185*67e74705SXin Li AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15186*67e74705SXin Li
15187*67e74705SXin Li // If a declaration that:
15188*67e74705SXin Li // 1) declares a function or a variable
15189*67e74705SXin Li // 2) has external linkage
15190*67e74705SXin Li // already exists, add a label attribute to it.
15191*67e74705SXin Li if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15192*67e74705SXin Li if (isDeclExternC(PrevDecl))
15193*67e74705SXin Li PrevDecl->addAttr(Attr);
15194*67e74705SXin Li else
15195*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15196*67e74705SXin Li << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15197*67e74705SXin Li // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15198*67e74705SXin Li } else
15199*67e74705SXin Li (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15200*67e74705SXin Li }
15201*67e74705SXin Li
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)15202*67e74705SXin Li void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15203*67e74705SXin Li SourceLocation PragmaLoc,
15204*67e74705SXin Li SourceLocation NameLoc) {
15205*67e74705SXin Li Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15206*67e74705SXin Li
15207*67e74705SXin Li if (PrevDecl) {
15208*67e74705SXin Li PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15209*67e74705SXin Li } else {
15210*67e74705SXin Li (void)WeakUndeclaredIdentifiers.insert(
15211*67e74705SXin Li std::pair<IdentifierInfo*,WeakInfo>
15212*67e74705SXin Li (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15213*67e74705SXin Li }
15214*67e74705SXin Li }
15215*67e74705SXin Li
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)15216*67e74705SXin Li void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15217*67e74705SXin Li IdentifierInfo* AliasName,
15218*67e74705SXin Li SourceLocation PragmaLoc,
15219*67e74705SXin Li SourceLocation NameLoc,
15220*67e74705SXin Li SourceLocation AliasNameLoc) {
15221*67e74705SXin Li Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15222*67e74705SXin Li LookupOrdinaryName);
15223*67e74705SXin Li WeakInfo W = WeakInfo(Name, NameLoc);
15224*67e74705SXin Li
15225*67e74705SXin Li if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15226*67e74705SXin Li if (!PrevDecl->hasAttr<AliasAttr>())
15227*67e74705SXin Li if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15228*67e74705SXin Li DeclApplyPragmaWeak(TUScope, ND, W);
15229*67e74705SXin Li } else {
15230*67e74705SXin Li (void)WeakUndeclaredIdentifiers.insert(
15231*67e74705SXin Li std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15232*67e74705SXin Li }
15233*67e74705SXin Li }
15234*67e74705SXin Li
getObjCDeclContext() const15235*67e74705SXin Li Decl *Sema::getObjCDeclContext() const {
15236*67e74705SXin Li return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15237*67e74705SXin Li }
15238*67e74705SXin Li
getCurContextAvailability() const15239*67e74705SXin Li AvailabilityResult Sema::getCurContextAvailability() const {
15240*67e74705SXin Li const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15241*67e74705SXin Li if (!D)
15242*67e74705SXin Li return AR_Available;
15243*67e74705SXin Li
15244*67e74705SXin Li // If we are within an Objective-C method, we should consult
15245*67e74705SXin Li // both the availability of the method as well as the
15246*67e74705SXin Li // enclosing class. If the class is (say) deprecated,
15247*67e74705SXin Li // the entire method is considered deprecated from the
15248*67e74705SXin Li // purpose of checking if the current context is deprecated.
15249*67e74705SXin Li if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15250*67e74705SXin Li AvailabilityResult R = MD->getAvailability();
15251*67e74705SXin Li if (R != AR_Available)
15252*67e74705SXin Li return R;
15253*67e74705SXin Li D = MD->getClassInterface();
15254*67e74705SXin Li }
15255*67e74705SXin Li // If we are within an Objective-c @implementation, it
15256*67e74705SXin Li // gets the same availability context as the @interface.
15257*67e74705SXin Li else if (const ObjCImplementationDecl *ID =
15258*67e74705SXin Li dyn_cast<ObjCImplementationDecl>(D)) {
15259*67e74705SXin Li D = ID->getClassInterface();
15260*67e74705SXin Li }
15261*67e74705SXin Li // Recover from user error.
15262*67e74705SXin Li return D ? D->getAvailability() : AR_Available;
15263*67e74705SXin Li }
15264