Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaDecl.cpp
Warning:line 17643, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaDecl.cpp
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NonTrivialTypeVisitor.h"
27#include "clang/AST/Randstruct.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/Basic/Builtins.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37#include "clang/Sema/CXXFieldCollector.h"
38#include "clang/Sema/DeclSpec.h"
39#include "clang/Sema/DelayedDiagnostic.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaInternal.h"
46#include "clang/Sema/Template.h"
47#include "llvm/ADT/SmallString.h"
48#include "llvm/ADT/Triple.h"
49#include <algorithm>
50#include <cstring>
51#include <functional>
52#include <unordered_map>
53
54using namespace clang;
55using namespace sema;
56
57Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58 if (OwnedType) {
59 Decl *Group[2] = { OwnedType, Ptr };
60 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61 }
62
63 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64}
65
66namespace {
67
68class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69 public:
70 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71 bool AllowTemplates = false,
72 bool AllowNonTemplates = true)
73 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75 WantExpressionKeywords = false;
76 WantCXXNamedCasts = false;
77 WantRemainingKeywords = false;
78 }
79
80 bool ValidateCandidate(const TypoCorrection &candidate) override {
81 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82 if (!AllowInvalidDecl && ND->isInvalidDecl())
83 return false;
84
85 if (getAsTypeTemplateDecl(ND))
86 return AllowTemplates;
87
88 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89 if (!IsType)
90 return false;
91
92 if (AllowNonTemplates)
93 return true;
94
95 // An injected-class-name of a class template (specialization) is valid
96 // as a template or as a non-template.
97 if (AllowTemplates) {
98 auto *RD = dyn_cast<CXXRecordDecl>(ND);
99 if (!RD || !RD->isInjectedClassName())
100 return false;
101 RD = cast<CXXRecordDecl>(RD->getDeclContext());
102 return RD->getDescribedClassTemplate() ||
103 isa<ClassTemplateSpecializationDecl>(RD);
104 }
105
106 return false;
107 }
108
109 return !WantClassName && candidate.isKeyword();
110 }
111
112 std::unique_ptr<CorrectionCandidateCallback> clone() override {
113 return std::make_unique<TypeNameValidatorCCC>(*this);
114 }
115
116 private:
117 bool AllowInvalidDecl;
118 bool WantClassName;
119 bool AllowTemplates;
120 bool AllowNonTemplates;
121};
122
123} // end anonymous namespace
124
125/// Determine whether the token kind starts a simple-type-specifier.
126bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127 switch (Kind) {
128 // FIXME: Take into account the current language when deciding whether a
129 // token kind is a valid type specifier
130 case tok::kw_short:
131 case tok::kw_long:
132 case tok::kw___int64:
133 case tok::kw___int128:
134 case tok::kw_signed:
135 case tok::kw_unsigned:
136 case tok::kw_void:
137 case tok::kw_char:
138 case tok::kw_int:
139 case tok::kw_half:
140 case tok::kw_float:
141 case tok::kw_double:
142 case tok::kw___bf16:
143 case tok::kw__Float16:
144 case tok::kw___float128:
145 case tok::kw___ibm128:
146 case tok::kw_wchar_t:
147 case tok::kw_bool:
148#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
149#include "clang/Basic/TransformTypeTraits.def"
150 case tok::kw___auto_type:
151 return true;
152
153 case tok::annot_typename:
154 case tok::kw_char16_t:
155 case tok::kw_char32_t:
156 case tok::kw_typeof:
157 case tok::annot_decltype:
158 case tok::kw_decltype:
159 return getLangOpts().CPlusPlus;
160
161 case tok::kw_char8_t:
162 return getLangOpts().Char8;
163
164 default:
165 break;
166 }
167
168 return false;
169}
170
171namespace {
172enum class UnqualifiedTypeNameLookupResult {
173 NotFound,
174 FoundNonType,
175 FoundType
176};
177} // end anonymous namespace
178
179/// Tries to perform unqualified lookup of the type decls in bases for
180/// dependent class.
181/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
182/// type decl, \a FoundType if only type decls are found.
183static UnqualifiedTypeNameLookupResult
184lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
185 SourceLocation NameLoc,
186 const CXXRecordDecl *RD) {
187 if (!RD->hasDefinition())
188 return UnqualifiedTypeNameLookupResult::NotFound;
189 // Look for type decls in base classes.
190 UnqualifiedTypeNameLookupResult FoundTypeDecl =
191 UnqualifiedTypeNameLookupResult::NotFound;
192 for (const auto &Base : RD->bases()) {
193 const CXXRecordDecl *BaseRD = nullptr;
194 if (auto *BaseTT = Base.getType()->getAs<TagType>())
195 BaseRD = BaseTT->getAsCXXRecordDecl();
196 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
197 // Look for type decls in dependent base classes that have known primary
198 // templates.
199 if (!TST || !TST->isDependentType())
200 continue;
201 auto *TD = TST->getTemplateName().getAsTemplateDecl();
202 if (!TD)
203 continue;
204 if (auto *BasePrimaryTemplate =
205 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
206 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = BasePrimaryTemplate;
208 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
209 if (const ClassTemplatePartialSpecializationDecl *PS =
210 CTD->findPartialSpecialization(Base.getType()))
211 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
212 BaseRD = PS;
213 }
214 }
215 }
216 if (BaseRD) {
217 for (NamedDecl *ND : BaseRD->lookup(&II)) {
218 if (!isa<TypeDecl>(ND))
219 return UnqualifiedTypeNameLookupResult::FoundNonType;
220 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
221 }
222 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
223 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
224 case UnqualifiedTypeNameLookupResult::FoundNonType:
225 return UnqualifiedTypeNameLookupResult::FoundNonType;
226 case UnqualifiedTypeNameLookupResult::FoundType:
227 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
228 break;
229 case UnqualifiedTypeNameLookupResult::NotFound:
230 break;
231 }
232 }
233 }
234 }
235
236 return FoundTypeDecl;
237}
238
239static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
240 const IdentifierInfo &II,
241 SourceLocation NameLoc) {
242 // Lookup in the parent class template context, if any.
243 const CXXRecordDecl *RD = nullptr;
244 UnqualifiedTypeNameLookupResult FoundTypeDecl =
245 UnqualifiedTypeNameLookupResult::NotFound;
246 for (DeclContext *DC = S.CurContext;
247 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
248 DC = DC->getParent()) {
249 // Look for type decls in dependent base classes that have known primary
250 // templates.
251 RD = dyn_cast<CXXRecordDecl>(DC);
252 if (RD && RD->getDescribedClassTemplate())
253 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
254 }
255 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
256 return nullptr;
257
258 // We found some types in dependent base classes. Recover as if the user
259 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
260 // lookup during template instantiation.
261 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
262
263 ASTContext &Context = S.Context;
264 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
265 cast<Type>(Context.getRecordType(RD)));
266 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
267
268 CXXScopeSpec SS;
269 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
270
271 TypeLocBuilder Builder;
272 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
273 DepTL.setNameLoc(NameLoc);
274 DepTL.setElaboratedKeywordLoc(SourceLocation());
275 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
276 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
277}
278
279/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
280static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
281 SourceLocation NameLoc,
282 bool WantNontrivialTypeSourceInfo = true) {
283 switch (T->getTypeClass()) {
284 case Type::DeducedTemplateSpecialization:
285 case Type::Enum:
286 case Type::InjectedClassName:
287 case Type::Record:
288 case Type::Typedef:
289 case Type::UnresolvedUsing:
290 case Type::Using:
291 break;
292 // These can never be qualified so an ElaboratedType node
293 // would carry no additional meaning.
294 case Type::ObjCInterface:
295 case Type::ObjCTypeParam:
296 case Type::TemplateTypeParm:
297 return ParsedType::make(T);
298 default:
299 llvm_unreachable("Unexpected Type Class")::llvm::llvm_unreachable_internal("Unexpected Type Class", "clang/lib/Sema/SemaDecl.cpp"
, 299)
;
300 }
301
302 if (!SS || SS->isEmpty())
303 return ParsedType::make(
304 S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
305
306 QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
307 if (!WantNontrivialTypeSourceInfo)
308 return ParsedType::make(ElTy);
309
310 TypeLocBuilder Builder;
311 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
312 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
313 ElabTL.setElaboratedKeywordLoc(SourceLocation());
314 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
315 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
316}
317
318/// If the identifier refers to a type name within this scope,
319/// return the declaration of that type.
320///
321/// This routine performs ordinary name lookup of the identifier II
322/// within the given scope, with optional C++ scope specifier SS, to
323/// determine whether the name refers to a type. If so, returns an
324/// opaque pointer (actually a QualType) corresponding to that
325/// type. Otherwise, returns NULL.
326ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
327 Scope *S, CXXScopeSpec *SS, bool isClassName,
328 bool HasTrailingDot, ParsedType ObjectTypePtr,
329 bool IsCtorOrDtorName,
330 bool WantNontrivialTypeSourceInfo,
331 bool IsClassTemplateDeductionContext,
332 ImplicitTypenameContext AllowImplicitTypename,
333 IdentifierInfo **CorrectedII) {
334 // FIXME: Consider allowing this outside C++1z mode as an extension.
335 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
336 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
337 !isClassName && !HasTrailingDot;
338
339 // Determine where we will perform name lookup.
340 DeclContext *LookupCtx = nullptr;
341 if (ObjectTypePtr) {
342 QualType ObjectType = ObjectTypePtr.get();
343 if (ObjectType->isRecordType())
344 LookupCtx = computeDeclContext(ObjectType);
345 } else if (SS && SS->isNotEmpty()) {
346 LookupCtx = computeDeclContext(*SS, false);
347
348 if (!LookupCtx) {
349 if (isDependentScopeSpecifier(*SS)) {
350 // C++ [temp.res]p3:
351 // A qualified-id that refers to a type and in which the
352 // nested-name-specifier depends on a template-parameter (14.6.2)
353 // shall be prefixed by the keyword typename to indicate that the
354 // qualified-id denotes a type, forming an
355 // elaborated-type-specifier (7.1.5.3).
356 //
357 // We therefore do not perform any name lookup if the result would
358 // refer to a member of an unknown specialization.
359 // In C++2a, in several contexts a 'typename' is not required. Also
360 // allow this as an extension.
361 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
362 !isClassName && !IsCtorOrDtorName)
363 return nullptr;
364 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
365 if (IsImplicitTypename) {
366 SourceLocation QualifiedLoc = SS->getRange().getBegin();
367 if (getLangOpts().CPlusPlus20)
368 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
369 else
370 Diag(QualifiedLoc, diag::ext_implicit_typename)
371 << SS->getScopeRep() << II.getName()
372 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
373 }
374
375 // We know from the grammar that this name refers to a type,
376 // so build a dependent node to describe the type.
377 if (WantNontrivialTypeSourceInfo)
378 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
379 (ImplicitTypenameContext)IsImplicitTypename)
380 .get();
381
382 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
383 QualType T =
384 CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
385 SourceLocation(), QualifierLoc, II, NameLoc);
386 return ParsedType::make(T);
387 }
388
389 return nullptr;
390 }
391
392 if (!LookupCtx->isDependentContext() &&
393 RequireCompleteDeclContext(*SS, LookupCtx))
394 return nullptr;
395 }
396
397 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
398 // lookup for class-names.
399 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
400 LookupOrdinaryName;
401 LookupResult Result(*this, &II, NameLoc, Kind);
402 if (LookupCtx) {
403 // Perform "qualified" name lookup into the declaration context we
404 // computed, which is either the type of the base of a member access
405 // expression or the declaration context associated with a prior
406 // nested-name-specifier.
407 LookupQualifiedName(Result, LookupCtx);
408
409 if (ObjectTypePtr && Result.empty()) {
410 // C++ [basic.lookup.classref]p3:
411 // If the unqualified-id is ~type-name, the type-name is looked up
412 // in the context of the entire postfix-expression. If the type T of
413 // the object expression is of a class type C, the type-name is also
414 // looked up in the scope of class C. At least one of the lookups shall
415 // find a name that refers to (possibly cv-qualified) T.
416 LookupName(Result, S);
417 }
418 } else {
419 // Perform unqualified name lookup.
420 LookupName(Result, S);
421
422 // For unqualified lookup in a class template in MSVC mode, look into
423 // dependent base classes where the primary class template is known.
424 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
425 if (ParsedType TypeInBase =
426 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
427 return TypeInBase;
428 }
429 }
430
431 NamedDecl *IIDecl = nullptr;
432 UsingShadowDecl *FoundUsingShadow = nullptr;
433 switch (Result.getResultKind()) {
434 case LookupResult::NotFound:
435 case LookupResult::NotFoundInCurrentInstantiation:
436 if (CorrectedII) {
437 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
438 AllowDeducedTemplate);
439 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
440 S, SS, CCC, CTK_ErrorRecovery);
441 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
442 TemplateTy Template;
443 bool MemberOfUnknownSpecialization;
444 UnqualifiedId TemplateName;
445 TemplateName.setIdentifier(NewII, NameLoc);
446 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
447 CXXScopeSpec NewSS, *NewSSPtr = SS;
448 if (SS && NNS) {
449 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
450 NewSSPtr = &NewSS;
451 }
452 if (Correction && (NNS || NewII != &II) &&
453 // Ignore a correction to a template type as the to-be-corrected
454 // identifier is not a template (typo correction for template names
455 // is handled elsewhere).
456 !(getLangOpts().CPlusPlus && NewSSPtr &&
457 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
458 Template, MemberOfUnknownSpecialization))) {
459 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
460 isClassName, HasTrailingDot, ObjectTypePtr,
461 IsCtorOrDtorName,
462 WantNontrivialTypeSourceInfo,
463 IsClassTemplateDeductionContext);
464 if (Ty) {
465 diagnoseTypo(Correction,
466 PDiag(diag::err_unknown_type_or_class_name_suggest)
467 << Result.getLookupName() << isClassName);
468 if (SS && NNS)
469 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
470 *CorrectedII = NewII;
471 return Ty;
472 }
473 }
474 }
475 // If typo correction failed or was not performed, fall through
476 [[fallthrough]];
477 case LookupResult::FoundOverloaded:
478 case LookupResult::FoundUnresolvedValue:
479 Result.suppressDiagnostics();
480 return nullptr;
481
482 case LookupResult::Ambiguous:
483 // Recover from type-hiding ambiguities by hiding the type. We'll
484 // do the lookup again when looking for an object, and we can
485 // diagnose the error then. If we don't do this, then the error
486 // about hiding the type will be immediately followed by an error
487 // that only makes sense if the identifier was treated like a type.
488 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
489 Result.suppressDiagnostics();
490 return nullptr;
491 }
492
493 // Look to see if we have a type anywhere in the list of results.
494 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
495 Res != ResEnd; ++Res) {
496 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
497 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
498 RealRes) ||
499 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
500 if (!IIDecl ||
501 // Make the selection of the recovery decl deterministic.
502 RealRes->getLocation() < IIDecl->getLocation()) {
503 IIDecl = RealRes;
504 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
505 }
506 }
507 }
508
509 if (!IIDecl) {
510 // None of the entities we found is a type, so there is no way
511 // to even assume that the result is a type. In this case, don't
512 // complain about the ambiguity. The parser will either try to
513 // perform this lookup again (e.g., as an object name), which
514 // will produce the ambiguity, or will complain that it expected
515 // a type name.
516 Result.suppressDiagnostics();
517 return nullptr;
518 }
519
520 // We found a type within the ambiguous lookup; diagnose the
521 // ambiguity and then return that type. This might be the right
522 // answer, or it might not be, but it suppresses any attempt to
523 // perform the name lookup again.
524 break;
525
526 case LookupResult::Found:
527 IIDecl = Result.getFoundDecl();
528 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
529 break;
530 }
531
532 assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl"
) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "clang/lib/Sema/SemaDecl.cpp", 532, __extension__ __PRETTY_FUNCTION__
))
;
533
534 QualType T;
535 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
536 // C++ [class.qual]p2: A lookup that would find the injected-class-name
537 // instead names the constructors of the class, except when naming a class.
538 // This is ill-formed when we're not actually forming a ctor or dtor name.
539 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
540 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
541 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
542 FoundRD->isInjectedClassName() &&
543 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
544 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
545 << &II << /*Type*/1;
546
547 DiagnoseUseOfDecl(IIDecl, NameLoc);
548
549 T = Context.getTypeDeclType(TD);
550 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
551 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
552 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
553 if (!HasTrailingDot)
554 T = Context.getObjCInterfaceType(IDecl);
555 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
556 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
557 (void)DiagnoseUseOfDecl(UD, NameLoc);
558 // Recover with 'int'
559 return ParsedType::make(Context.IntTy);
560 } else if (AllowDeducedTemplate) {
561 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
562 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD)(static_cast <bool> (!FoundUsingShadow || FoundUsingShadow
->getTargetDecl() == TD) ? void (0) : __assert_fail ("!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD"
, "clang/lib/Sema/SemaDecl.cpp", 562, __extension__ __PRETTY_FUNCTION__
))
;
563 TemplateName Template =
564 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
565 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
566 false);
567 // Don't wrap in a further UsingType.
568 FoundUsingShadow = nullptr;
569 }
570 }
571
572 if (T.isNull()) {
573 // If it's not plausibly a type, suppress diagnostics.
574 Result.suppressDiagnostics();
575 return nullptr;
576 }
577
578 if (FoundUsingShadow)
579 T = Context.getUsingType(FoundUsingShadow, T);
580
581 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
582}
583
584// Builds a fake NNS for the given decl context.
585static NestedNameSpecifier *
586synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
587 for (;; DC = DC->getLookupParent()) {
588 DC = DC->getPrimaryContext();
589 auto *ND = dyn_cast<NamespaceDecl>(DC);
590 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
591 return NestedNameSpecifier::Create(Context, nullptr, ND);
592 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
593 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
594 RD->getTypeForDecl());
595 else if (isa<TranslationUnitDecl>(DC))
596 return NestedNameSpecifier::GlobalSpecifier(Context);
597 }
598 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "clang/lib/Sema/SemaDecl.cpp", 598)
;
599}
600
601/// Find the parent class with dependent bases of the innermost enclosing method
602/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
603/// up allowing unqualified dependent type names at class-level, which MSVC
604/// correctly rejects.
605static const CXXRecordDecl *
606findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
607 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
608 DC = DC->getPrimaryContext();
609 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
610 if (MD->getParent()->hasAnyDependentBases())
611 return MD->getParent();
612 }
613 return nullptr;
614}
615
616ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
617 SourceLocation NameLoc,
618 bool IsTemplateTypeArg) {
619 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")(static_cast <bool> (getLangOpts().MSVCCompat &&
"shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail
("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "clang/lib/Sema/SemaDecl.cpp", 619, __extension__ __PRETTY_FUNCTION__
))
;
620
621 NestedNameSpecifier *NNS = nullptr;
622 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
623 // If we weren't able to parse a default template argument, delay lookup
624 // until instantiation time by making a non-dependent DependentTypeName. We
625 // pretend we saw a NestedNameSpecifier referring to the current scope, and
626 // lookup is retried.
627 // FIXME: This hurts our diagnostic quality, since we get errors like "no
628 // type named 'Foo' in 'current_namespace'" when the user didn't write any
629 // name specifiers.
630 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
631 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
632 } else if (const CXXRecordDecl *RD =
633 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
634 // Build a DependentNameType that will perform lookup into RD at
635 // instantiation time.
636 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
637 RD->getTypeForDecl());
638
639 // Diagnose that this identifier was undeclared, and retry the lookup during
640 // template instantiation.
641 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
642 << RD;
643 } else {
644 // This is not a situation that we should recover from.
645 return ParsedType();
646 }
647
648 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
649
650 // Build type location information. We synthesized the qualifier, so we have
651 // to build a fake NestedNameSpecifierLoc.
652 NestedNameSpecifierLocBuilder NNSLocBuilder;
653 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
654 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
655
656 TypeLocBuilder Builder;
657 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
658 DepTL.setNameLoc(NameLoc);
659 DepTL.setElaboratedKeywordLoc(SourceLocation());
660 DepTL.setQualifierLoc(QualifierLoc);
661 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
662}
663
664/// isTagName() - This method is called *for error recovery purposes only*
665/// to determine if the specified name is a valid tag name ("struct foo"). If
666/// so, this returns the TST for the tag corresponding to it (TST_enum,
667/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
668/// cases in C where the user forgot to specify the tag.
669DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
670 // Do a tag name lookup in this scope.
671 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
672 LookupName(R, S, false);
673 R.suppressDiagnostics();
674 if (R.getResultKind() == LookupResult::Found)
675 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
676 switch (TD->getTagKind()) {
677 case TTK_Struct: return DeclSpec::TST_struct;
678 case TTK_Interface: return DeclSpec::TST_interface;
679 case TTK_Union: return DeclSpec::TST_union;
680 case TTK_Class: return DeclSpec::TST_class;
681 case TTK_Enum: return DeclSpec::TST_enum;
682 }
683 }
684
685 return DeclSpec::TST_unspecified;
686}
687
688/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
689/// if a CXXScopeSpec's type is equal to the type of one of the base classes
690/// then downgrade the missing typename error to a warning.
691/// This is needed for MSVC compatibility; Example:
692/// @code
693/// template<class T> class A {
694/// public:
695/// typedef int TYPE;
696/// };
697/// template<class T> class B : public A<T> {
698/// public:
699/// A<T>::TYPE a; // no typename required because A<T> is a base class.
700/// };
701/// @endcode
702bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
703 if (CurContext->isRecord()) {
704 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
705 return true;
706
707 const Type *Ty = SS->getScopeRep()->getAsType();
708
709 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
710 for (const auto &Base : RD->bases())
711 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
712 return true;
713 return S->isFunctionPrototypeScope();
714 }
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716}
717
718void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
719 SourceLocation IILoc,
720 Scope *S,
721 CXXScopeSpec *SS,
722 ParsedType &SuggestedType,
723 bool IsTemplateName) {
724 // Don't report typename errors for editor placeholders.
725 if (II->isEditorPlaceholder())
726 return;
727 // We don't have anything to suggest (yet).
728 SuggestedType = nullptr;
729
730 // There may have been a typo in the name of the type. Look up typo
731 // results, in case we have something that we can suggest.
732 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
733 /*AllowTemplates=*/IsTemplateName,
734 /*AllowNonTemplates=*/!IsTemplateName);
735 if (TypoCorrection Corrected =
736 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
737 CCC, CTK_ErrorRecovery)) {
738 // FIXME: Support error recovery for the template-name case.
739 bool CanRecover = !IsTemplateName;
740 if (Corrected.isKeyword()) {
741 // We corrected to a keyword.
742 diagnoseTypo(Corrected,
743 PDiag(IsTemplateName ? diag::err_no_template_suggest
744 : diag::err_unknown_typename_suggest)
745 << II);
746 II = Corrected.getCorrectionAsIdentifierInfo();
747 } else {
748 // We found a similarly-named type or interface; suggest that.
749 if (!SS || !SS->isSet()) {
750 diagnoseTypo(Corrected,
751 PDiag(IsTemplateName ? diag::err_no_template_suggest
752 : diag::err_unknown_typename_suggest)
753 << II, CanRecover);
754 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
755 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
756 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
757 II->getName().equals(CorrectedStr);
758 diagnoseTypo(Corrected,
759 PDiag(IsTemplateName
760 ? diag::err_no_member_template_suggest
761 : diag::err_unknown_nested_typename_suggest)
762 << II << DC << DroppedSpecifier << SS->getRange(),
763 CanRecover);
764 } else {
765 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "clang/lib/Sema/SemaDecl.cpp", 765)
;
766 }
767
768 if (!CanRecover)
769 return;
770
771 CXXScopeSpec tmpSS;
772 if (Corrected.getCorrectionSpecifier())
773 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
774 SourceRange(IILoc));
775 // FIXME: Support class template argument deduction here.
776 SuggestedType =
777 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
778 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
779 /*IsCtorOrDtorName=*/false,
780 /*WantNontrivialTypeSourceInfo=*/true);
781 }
782 return;
783 }
784
785 if (getLangOpts().CPlusPlus && !IsTemplateName) {
786 // See if II is a class template that the user forgot to pass arguments to.
787 UnqualifiedId Name;
788 Name.setIdentifier(II, IILoc);
789 CXXScopeSpec EmptySS;
790 TemplateTy TemplateResult;
791 bool MemberOfUnknownSpecialization;
792 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
793 Name, nullptr, true, TemplateResult,
794 MemberOfUnknownSpecialization) == TNK_Type_template) {
795 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
796 return;
797 }
798 }
799
800 // FIXME: Should we move the logic that tries to recover from a missing tag
801 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
802
803 if (!SS || (!SS->isSet() && !SS->isInvalid()))
804 Diag(IILoc, IsTemplateName ? diag::err_no_template
805 : diag::err_unknown_typename)
806 << II;
807 else if (DeclContext *DC = computeDeclContext(*SS, false))
808 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
809 : diag::err_typename_nested_not_found)
810 << II << DC << SS->getRange();
811 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
812 SuggestedType =
813 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
814 } else if (isDependentScopeSpecifier(*SS)) {
815 unsigned DiagID = diag::err_typename_missing;
816 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
817 DiagID = diag::ext_typename_missing;
818
819 Diag(SS->getRange().getBegin(), DiagID)
820 << SS->getScopeRep() << II->getName()
821 << SourceRange(SS->getRange().getBegin(), IILoc)
822 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
823 SuggestedType = ActOnTypenameType(S, SourceLocation(),
824 *SS, *II, IILoc).get();
825 } else {
826 assert(SS && SS->isInvalid() &&(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "clang/lib/Sema/SemaDecl.cpp", 827, __extension__ __PRETTY_FUNCTION__
))
827 "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "clang/lib/Sema/SemaDecl.cpp", 827, __extension__ __PRETTY_FUNCTION__
))
;
828 }
829}
830
831/// Determine whether the given result set contains either a type name
832/// or
833static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
834 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
835 NextToken.is(tok::less);
836
837 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
838 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
839 return true;
840
841 if (CheckTemplate && isa<TemplateDecl>(*I))
842 return true;
843 }
844
845 return false;
846}
847
848static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
849 Scope *S, CXXScopeSpec &SS,
850 IdentifierInfo *&Name,
851 SourceLocation NameLoc) {
852 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
853 SemaRef.LookupParsedName(R, S, &SS);
854 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
855 StringRef FixItTagName;
856 switch (Tag->getTagKind()) {
857 case TTK_Class:
858 FixItTagName = "class ";
859 break;
860
861 case TTK_Enum:
862 FixItTagName = "enum ";
863 break;
864
865 case TTK_Struct:
866 FixItTagName = "struct ";
867 break;
868
869 case TTK_Interface:
870 FixItTagName = "__interface ";
871 break;
872
873 case TTK_Union:
874 FixItTagName = "union ";
875 break;
876 }
877
878 StringRef TagName = FixItTagName.drop_back();
879 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
880 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
881 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
882
883 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
884 I != IEnd; ++I)
885 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
886 << Name << TagName;
887
888 // Replace lookup results with just the tag decl.
889 Result.clear(Sema::LookupTagName);
890 SemaRef.LookupParsedName(Result, S, &SS);
891 return true;
892 }
893
894 return false;
895}
896
897Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
898 IdentifierInfo *&Name,
899 SourceLocation NameLoc,
900 const Token &NextToken,
901 CorrectionCandidateCallback *CCC) {
902 DeclarationNameInfo NameInfo(Name, NameLoc);
903 ObjCMethodDecl *CurMethod = getCurMethodDecl();
904
905 assert(NextToken.isNot(tok::coloncolon) &&(static_cast <bool> (NextToken.isNot(tok::coloncolon) &&
"parse nested name specifiers before calling ClassifyName") ?
void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "clang/lib/Sema/SemaDecl.cpp", 906, __extension__ __PRETTY_FUNCTION__
))
906 "parse nested name specifiers before calling ClassifyName")(static_cast <bool> (NextToken.isNot(tok::coloncolon) &&
"parse nested name specifiers before calling ClassifyName") ?
void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "clang/lib/Sema/SemaDecl.cpp", 906, __extension__ __PRETTY_FUNCTION__
))
;
907 if (getLangOpts().CPlusPlus && SS.isSet() &&
908 isCurrentClassName(*Name, S, &SS)) {
909 // Per [class.qual]p2, this names the constructors of SS, not the
910 // injected-class-name. We don't have a classification for that.
911 // There's not much point caching this result, since the parser
912 // will reject it later.
913 return NameClassification::Unknown();
914 }
915
916 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
917 LookupParsedName(Result, S, &SS, !CurMethod);
918
919 if (SS.isInvalid())
920 return NameClassification::Error();
921
922 // For unqualified lookup in a class template in MSVC mode, look into
923 // dependent base classes where the primary class template is known.
924 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
925 if (ParsedType TypeInBase =
926 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
927 return TypeInBase;
928 }
929
930 // Perform lookup for Objective-C instance variables (including automatically
931 // synthesized instance variables), if we're in an Objective-C method.
932 // FIXME: This lookup really, really needs to be folded in to the normal
933 // unqualified lookup mechanism.
934 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
935 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
936 if (Ivar.isInvalid())
937 return NameClassification::Error();
938 if (Ivar.isUsable())
939 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
940
941 // We defer builtin creation until after ivar lookup inside ObjC methods.
942 if (Result.empty())
943 LookupBuiltin(Result);
944 }
945
946 bool SecondTry = false;
947 bool IsFilteredTemplateName = false;
948
949Corrected:
950 switch (Result.getResultKind()) {
951 case LookupResult::NotFound:
952 // If an unqualified-id is followed by a '(', then we have a function
953 // call.
954 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
955 // In C++, this is an ADL-only call.
956 // FIXME: Reference?
957 if (getLangOpts().CPlusPlus)
958 return NameClassification::UndeclaredNonType();
959
960 // C90 6.3.2.2:
961 // If the expression that precedes the parenthesized argument list in a
962 // function call consists solely of an identifier, and if no
963 // declaration is visible for this identifier, the identifier is
964 // implicitly declared exactly as if, in the innermost block containing
965 // the function call, the declaration
966 //
967 // extern int identifier ();
968 //
969 // appeared.
970 //
971 // We also allow this in C99 as an extension. However, this is not
972 // allowed in all language modes as functions without prototypes may not
973 // be supported.
974 if (getLangOpts().implicitFunctionsAllowed()) {
975 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
976 return NameClassification::NonType(D);
977 }
978 }
979
980 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
981 // In C++20 onwards, this could be an ADL-only call to a function
982 // template, and we're required to assume that this is a template name.
983 //
984 // FIXME: Find a way to still do typo correction in this case.
985 TemplateName Template =
986 Context.getAssumedTemplateName(NameInfo.getName());
987 return NameClassification::UndeclaredTemplate(Template);
988 }
989
990 // In C, we first see whether there is a tag type by the same name, in
991 // which case it's likely that the user just forgot to write "enum",
992 // "struct", or "union".
993 if (!getLangOpts().CPlusPlus && !SecondTry &&
994 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
995 break;
996 }
997
998 // Perform typo correction to determine if there is another name that is
999 // close to this name.
1000 if (!SecondTry && CCC) {
1001 SecondTry = true;
1002 if (TypoCorrection Corrected =
1003 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1004 &SS, *CCC, CTK_ErrorRecovery)) {
1005 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1006 unsigned QualifiedDiag = diag::err_no_member_suggest;
1007
1008 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1009 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1010 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1011 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1012 UnqualifiedDiag = diag::err_no_template_suggest;
1013 QualifiedDiag = diag::err_no_member_template_suggest;
1014 } else if (UnderlyingFirstDecl &&
1015 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1016 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1017 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1018 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1019 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1020 }
1021
1022 if (SS.isEmpty()) {
1023 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1024 } else {// FIXME: is this even reachable? Test it.
1025 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1026 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1027 Name->getName().equals(CorrectedStr);
1028 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1029 << Name << computeDeclContext(SS, false)
1030 << DroppedSpecifier << SS.getRange());
1031 }
1032
1033 // Update the name, so that the caller has the new name.
1034 Name = Corrected.getCorrectionAsIdentifierInfo();
1035
1036 // Typo correction corrected to a keyword.
1037 if (Corrected.isKeyword())
1038 return Name;
1039
1040 // Also update the LookupResult...
1041 // FIXME: This should probably go away at some point
1042 Result.clear();
1043 Result.setLookupName(Corrected.getCorrection());
1044 if (FirstDecl)
1045 Result.addDecl(FirstDecl);
1046
1047 // If we found an Objective-C instance variable, let
1048 // LookupInObjCMethod build the appropriate expression to
1049 // reference the ivar.
1050 // FIXME: This is a gross hack.
1051 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1052 DeclResult R =
1053 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1054 if (R.isInvalid())
1055 return NameClassification::Error();
1056 if (R.isUsable())
1057 return NameClassification::NonType(Ivar);
1058 }
1059
1060 goto Corrected;
1061 }
1062 }
1063
1064 // We failed to correct; just fall through and let the parser deal with it.
1065 Result.suppressDiagnostics();
1066 return NameClassification::Unknown();
1067
1068 case LookupResult::NotFoundInCurrentInstantiation: {
1069 // We performed name lookup into the current instantiation, and there were
1070 // dependent bases, so we treat this result the same way as any other
1071 // dependent nested-name-specifier.
1072
1073 // C++ [temp.res]p2:
1074 // A name used in a template declaration or definition and that is
1075 // dependent on a template-parameter is assumed not to name a type
1076 // unless the applicable name lookup finds a type name or the name is
1077 // qualified by the keyword typename.
1078 //
1079 // FIXME: If the next token is '<', we might want to ask the parser to
1080 // perform some heroics to see if we actually have a
1081 // template-argument-list, which would indicate a missing 'template'
1082 // keyword here.
1083 return NameClassification::DependentNonType();
1084 }
1085
1086 case LookupResult::Found:
1087 case LookupResult::FoundOverloaded:
1088 case LookupResult::FoundUnresolvedValue:
1089 break;
1090
1091 case LookupResult::Ambiguous:
1092 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1093 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1094 /*AllowDependent=*/false)) {
1095 // C++ [temp.local]p3:
1096 // A lookup that finds an injected-class-name (10.2) can result in an
1097 // ambiguity in certain cases (for example, if it is found in more than
1098 // one base class). If all of the injected-class-names that are found
1099 // refer to specializations of the same class template, and if the name
1100 // is followed by a template-argument-list, the reference refers to the
1101 // class template itself and not a specialization thereof, and is not
1102 // ambiguous.
1103 //
1104 // This filtering can make an ambiguous result into an unambiguous one,
1105 // so try again after filtering out template names.
1106 FilterAcceptableTemplateNames(Result);
1107 if (!Result.isAmbiguous()) {
1108 IsFilteredTemplateName = true;
1109 break;
1110 }
1111 }
1112
1113 // Diagnose the ambiguity and return an error.
1114 return NameClassification::Error();
1115 }
1116
1117 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1118 (IsFilteredTemplateName ||
1119 hasAnyAcceptableTemplateNames(
1120 Result, /*AllowFunctionTemplates=*/true,
1121 /*AllowDependent=*/false,
1122 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1123 getLangOpts().CPlusPlus20))) {
1124 // C++ [temp.names]p3:
1125 // After name lookup (3.4) finds that a name is a template-name or that
1126 // an operator-function-id or a literal- operator-id refers to a set of
1127 // overloaded functions any member of which is a function template if
1128 // this is followed by a <, the < is always taken as the delimiter of a
1129 // template-argument-list and never as the less-than operator.
1130 // C++2a [temp.names]p2:
1131 // A name is also considered to refer to a template if it is an
1132 // unqualified-id followed by a < and name lookup finds either one
1133 // or more functions or finds nothing.
1134 if (!IsFilteredTemplateName)
1135 FilterAcceptableTemplateNames(Result);
1136
1137 bool IsFunctionTemplate;
1138 bool IsVarTemplate;
1139 TemplateName Template;
1140 if (Result.end() - Result.begin() > 1) {
1141 IsFunctionTemplate = true;
1142 Template = Context.getOverloadedTemplateName(Result.begin(),
1143 Result.end());
1144 } else if (!Result.empty()) {
1145 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1146 *Result.begin(), /*AllowFunctionTemplates=*/true,
1147 /*AllowDependent=*/false));
1148 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1149 IsVarTemplate = isa<VarTemplateDecl>(TD);
1150
1151 UsingShadowDecl *FoundUsingShadow =
1152 dyn_cast<UsingShadowDecl>(*Result.begin());
1153 assert(!FoundUsingShadow ||(static_cast <bool> (!FoundUsingShadow || TD == cast<
TemplateDecl>(FoundUsingShadow->getTargetDecl())) ? void
(0) : __assert_fail ("!FoundUsingShadow || TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())"
, "clang/lib/Sema/SemaDecl.cpp", 1154, __extension__ __PRETTY_FUNCTION__
))
1154 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()))(static_cast <bool> (!FoundUsingShadow || TD == cast<
TemplateDecl>(FoundUsingShadow->getTargetDecl())) ? void
(0) : __assert_fail ("!FoundUsingShadow || TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())"
, "clang/lib/Sema/SemaDecl.cpp", 1154, __extension__ __PRETTY_FUNCTION__
))
;
1155 Template =
1156 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1157 if (SS.isNotEmpty())
1158 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1159 /*TemplateKeyword=*/false,
1160 Template);
1161 } else {
1162 // All results were non-template functions. This is a function template
1163 // name.
1164 IsFunctionTemplate = true;
1165 Template = Context.getAssumedTemplateName(NameInfo.getName());
1166 }
1167
1168 if (IsFunctionTemplate) {
1169 // Function templates always go through overload resolution, at which
1170 // point we'll perform the various checks (e.g., accessibility) we need
1171 // to based on which function we selected.
1172 Result.suppressDiagnostics();
1173
1174 return NameClassification::FunctionTemplate(Template);
1175 }
1176
1177 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1178 : NameClassification::TypeTemplate(Template);
1179 }
1180
1181 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1182 QualType T = Context.getTypeDeclType(Type);
1183 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1184 T = Context.getUsingType(USD, T);
1185 return buildNamedType(*this, &SS, T, NameLoc);
1186 };
1187
1188 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1189 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1190 DiagnoseUseOfDecl(Type, NameLoc);
1191 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1192 return BuildTypeFor(Type, *Result.begin());
1193 }
1194
1195 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1196 if (!Class) {
1197 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1198 if (ObjCCompatibleAliasDecl *Alias =
1199 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1200 Class = Alias->getClassInterface();
1201 }
1202
1203 if (Class) {
1204 DiagnoseUseOfDecl(Class, NameLoc);
1205
1206 if (NextToken.is(tok::period)) {
1207 // Interface. <something> is parsed as a property reference expression.
1208 // Just return "unknown" as a fall-through for now.
1209 Result.suppressDiagnostics();
1210 return NameClassification::Unknown();
1211 }
1212
1213 QualType T = Context.getObjCInterfaceType(Class);
1214 return ParsedType::make(T);
1215 }
1216
1217 if (isa<ConceptDecl>(FirstDecl))
1218 return NameClassification::Concept(
1219 TemplateName(cast<TemplateDecl>(FirstDecl)));
1220
1221 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1222 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1223 return NameClassification::Error();
1224 }
1225
1226 // We can have a type template here if we're classifying a template argument.
1227 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1228 !isa<VarTemplateDecl>(FirstDecl))
1229 return NameClassification::TypeTemplate(
1230 TemplateName(cast<TemplateDecl>(FirstDecl)));
1231
1232 // Check for a tag type hidden by a non-type decl in a few cases where it
1233 // seems likely a type is wanted instead of the non-type that was found.
1234 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1235 if ((NextToken.is(tok::identifier) ||
1236 (NextIsOp &&
1237 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1238 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1239 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1240 DiagnoseUseOfDecl(Type, NameLoc);
1241 return BuildTypeFor(Type, *Result.begin());
1242 }
1243
1244 // If we already know which single declaration is referenced, just annotate
1245 // that declaration directly. Defer resolving even non-overloaded class
1246 // member accesses, as we need to defer certain access checks until we know
1247 // the context.
1248 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1249 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1250 return NameClassification::NonType(Result.getRepresentativeDecl());
1251
1252 // Otherwise, this is an overload set that we will need to resolve later.
1253 Result.suppressDiagnostics();
1254 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1255 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1256 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1257 Result.begin(), Result.end()));
1258}
1259
1260ExprResult
1261Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1262 SourceLocation NameLoc) {
1263 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")(static_cast <bool> (getLangOpts().CPlusPlus &&
"ADL-only call in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\""
, "clang/lib/Sema/SemaDecl.cpp", 1263, __extension__ __PRETTY_FUNCTION__
))
;
1264 CXXScopeSpec SS;
1265 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1266 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1267}
1268
1269ExprResult
1270Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1271 IdentifierInfo *Name,
1272 SourceLocation NameLoc,
1273 bool IsAddressOfOperand) {
1274 DeclarationNameInfo NameInfo(Name, NameLoc);
1275 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1276 NameInfo, IsAddressOfOperand,
1277 /*TemplateArgs=*/nullptr);
1278}
1279
1280ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1281 NamedDecl *Found,
1282 SourceLocation NameLoc,
1283 const Token &NextToken) {
1284 if (getCurMethodDecl() && SS.isEmpty())
1285 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1286 return BuildIvarRefExpr(S, NameLoc, Ivar);
1287
1288 // Reconstruct the lookup result.
1289 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1290 Result.addDecl(Found);
1291 Result.resolveKind();
1292
1293 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1294 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1295}
1296
1297ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1298 // For an implicit class member access, transform the result into a member
1299 // access expression if necessary.
1300 auto *ULE = cast<UnresolvedLookupExpr>(E);
1301 if ((*ULE->decls_begin())->isCXXClassMember()) {
1302 CXXScopeSpec SS;
1303 SS.Adopt(ULE->getQualifierLoc());
1304
1305 // Reconstruct the lookup result.
1306 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1307 LookupOrdinaryName);
1308 Result.setNamingClass(ULE->getNamingClass());
1309 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1310 Result.addDecl(*I, I.getAccess());
1311 Result.resolveKind();
1312 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1313 nullptr, S);
1314 }
1315
1316 // Otherwise, this is already in the form we needed, and no further checks
1317 // are necessary.
1318 return ULE;
1319}
1320
1321Sema::TemplateNameKindForDiagnostics
1322Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1323 auto *TD = Name.getAsTemplateDecl();
1324 if (!TD)
1325 return TemplateNameKindForDiagnostics::DependentTemplate;
1326 if (isa<ClassTemplateDecl>(TD))
1327 return TemplateNameKindForDiagnostics::ClassTemplate;
1328 if (isa<FunctionTemplateDecl>(TD))
1329 return TemplateNameKindForDiagnostics::FunctionTemplate;
1330 if (isa<VarTemplateDecl>(TD))
1331 return TemplateNameKindForDiagnostics::VarTemplate;
1332 if (isa<TypeAliasTemplateDecl>(TD))
1333 return TemplateNameKindForDiagnostics::AliasTemplate;
1334 if (isa<TemplateTemplateParmDecl>(TD))
1335 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1336 if (isa<ConceptDecl>(TD))
1337 return TemplateNameKindForDiagnostics::Concept;
1338 return TemplateNameKindForDiagnostics::DependentTemplate;
1339}
1340
1341void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1342 assert(DC->getLexicalParent() == CurContext &&(static_cast <bool> (DC->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "clang/lib/Sema/SemaDecl.cpp", 1343, __extension__ __PRETTY_FUNCTION__
))
1343 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (DC->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "clang/lib/Sema/SemaDecl.cpp", 1343, __extension__ __PRETTY_FUNCTION__
))
;
1344 CurContext = DC;
1345 S->setEntity(DC);
1346}
1347
1348void Sema::PopDeclContext() {
1349 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "clang/lib/Sema/SemaDecl.cpp", 1349, __extension__ __PRETTY_FUNCTION__
))
;
1350
1351 CurContext = CurContext->getLexicalParent();
1352 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "clang/lib/Sema/SemaDecl.cpp", 1352, __extension__ __PRETTY_FUNCTION__
))
;
1353}
1354
1355Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1356 Decl *D) {
1357 // Unlike PushDeclContext, the context to which we return is not necessarily
1358 // the containing DC of TD, because the new context will be some pre-existing
1359 // TagDecl definition instead of a fresh one.
1360 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1361 CurContext = cast<TagDecl>(D)->getDefinition();
1362 assert(CurContext && "skipping definition of undefined tag")(static_cast <bool> (CurContext && "skipping definition of undefined tag"
) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "clang/lib/Sema/SemaDecl.cpp", 1362, __extension__ __PRETTY_FUNCTION__
))
;
1363 // Start lookups from the parent of the current context; we don't want to look
1364 // into the pre-existing complete definition.
1365 S->setEntity(CurContext->getLookupParent());
1366 return Result;
1367}
1368
1369void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1370 CurContext = static_cast<decltype(CurContext)>(Context);
1371}
1372
1373/// EnterDeclaratorContext - Used when we must lookup names in the context
1374/// of a declarator's nested name specifier.
1375///
1376void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1377 // C++0x [basic.lookup.unqual]p13:
1378 // A name used in the definition of a static data member of class
1379 // X (after the qualified-id of the static member) is looked up as
1380 // if the name was used in a member function of X.
1381 // C++0x [basic.lookup.unqual]p14:
1382 // If a variable member of a namespace is defined outside of the
1383 // scope of its namespace then any name used in the definition of
1384 // the variable member (after the declarator-id) is looked up as
1385 // if the definition of the variable member occurred in its
1386 // namespace.
1387 // Both of these imply that we should push a scope whose context
1388 // is the semantic context of the declaration. We can't use
1389 // PushDeclContext here because that context is not necessarily
1390 // lexically contained in the current context. Fortunately,
1391 // the containing scope should have the appropriate information.
1392
1393 assert(!S->getEntity() && "scope already has entity")(static_cast <bool> (!S->getEntity() && "scope already has entity"
) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "clang/lib/Sema/SemaDecl.cpp", 1393, __extension__ __PRETTY_FUNCTION__
))
;
1394
1395#ifndef NDEBUG
1396 Scope *Ancestor = S->getParent();
1397 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1398 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")(static_cast <bool> (Ancestor->getEntity() == CurContext
&& "ancestor context mismatch") ? void (0) : __assert_fail
("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "clang/lib/Sema/SemaDecl.cpp", 1398, __extension__ __PRETTY_FUNCTION__
))
;
1399#endif
1400
1401 CurContext = DC;
1402 S->setEntity(DC);
1403
1404 if (S->getParent()->isTemplateParamScope()) {
1405 // Also set the corresponding entities for all immediately-enclosing
1406 // template parameter scopes.
1407 EnterTemplatedContext(S->getParent(), DC);
1408 }
1409}
1410
1411void Sema::ExitDeclaratorContext(Scope *S) {
1412 assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext &&
"Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "clang/lib/Sema/SemaDecl.cpp", 1412, __extension__ __PRETTY_FUNCTION__
))
;
1413
1414 // Switch back to the lexical context. The safety of this is
1415 // enforced by an assert in EnterDeclaratorContext.
1416 Scope *Ancestor = S->getParent();
1417 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1418 CurContext = Ancestor->getEntity();
1419
1420 // We don't need to do anything with the scope, which is going to
1421 // disappear.
1422}
1423
1424void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1425 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"expected to be initializing a template parameter scope") ? void
(0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "clang/lib/Sema/SemaDecl.cpp", 1426, __extension__ __PRETTY_FUNCTION__
))
1426 "expected to be initializing a template parameter scope")(static_cast <bool> (S->isTemplateParamScope() &&
"expected to be initializing a template parameter scope") ? void
(0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "clang/lib/Sema/SemaDecl.cpp", 1426, __extension__ __PRETTY_FUNCTION__
))
;
1427
1428 // C++20 [temp.local]p7:
1429 // In the definition of a member of a class template that appears outside
1430 // of the class template definition, the name of a member of the class
1431 // template hides the name of a template-parameter of any enclosing class
1432 // templates (but not a template-parameter of the member if the member is a
1433 // class or function template).
1434 // C++20 [temp.local]p9:
1435 // In the definition of a class template or in the definition of a member
1436 // of such a template that appears outside of the template definition, for
1437 // each non-dependent base class (13.8.2.1), if the name of the base class
1438 // or the name of a member of the base class is the same as the name of a
1439 // template-parameter, the base class name or member name hides the
1440 // template-parameter name (6.4.10).
1441 //
1442 // This means that a template parameter scope should be searched immediately
1443 // after searching the DeclContext for which it is a template parameter
1444 // scope. For example, for
1445 // template<typename T> template<typename U> template<typename V>
1446 // void N::A<T>::B<U>::f(...)
1447 // we search V then B<U> (and base classes) then U then A<T> (and base
1448 // classes) then T then N then ::.
1449 unsigned ScopeDepth = getTemplateDepth(S);
1450 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1451 DeclContext *SearchDCAfterScope = DC;
1452 for (; DC; DC = DC->getLookupParent()) {
1453 if (const TemplateParameterList *TPL =
1454 cast<Decl>(DC)->getDescribedTemplateParams()) {
1455 unsigned DCDepth = TPL->getDepth() + 1;
1456 if (DCDepth > ScopeDepth)
1457 continue;
1458 if (ScopeDepth == DCDepth)
1459 SearchDCAfterScope = DC = DC->getLookupParent();
1460 break;
1461 }
1462 }
1463 S->setLookupEntity(SearchDCAfterScope);
1464 }
1465}
1466
1467void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1468 // We assume that the caller has already called
1469 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1470 FunctionDecl *FD = D->getAsFunction();
1471 if (!FD)
1472 return;
1473
1474 // Same implementation as PushDeclContext, but enters the context
1475 // from the lexical parent, rather than the top-level class.
1476 assert(CurContext == FD->getLexicalParent() &&(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "clang/lib/Sema/SemaDecl.cpp", 1477, __extension__ __PRETTY_FUNCTION__
))
1477 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "clang/lib/Sema/SemaDecl.cpp", 1477, __extension__ __PRETTY_FUNCTION__
))
;
1478 CurContext = FD;
1479 S->setEntity(CurContext);
1480
1481 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1482 ParmVarDecl *Param = FD->getParamDecl(P);
1483 // If the parameter has an identifier, then add it to the scope
1484 if (Param->getIdentifier()) {
1485 S->AddDecl(Param);
1486 IdResolver.AddDecl(Param);
1487 }
1488 }
1489}
1490
1491void Sema::ActOnExitFunctionContext() {
1492 // Same implementation as PopDeclContext, but returns to the lexical parent,
1493 // rather than the top-level class.
1494 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "clang/lib/Sema/SemaDecl.cpp", 1494, __extension__ __PRETTY_FUNCTION__
))
;
1495 CurContext = CurContext->getLexicalParent();
1496 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "clang/lib/Sema/SemaDecl.cpp", 1496, __extension__ __PRETTY_FUNCTION__
))
;
1497}
1498
1499/// Determine whether overloading is allowed for a new function
1500/// declaration considering prior declarations of the same name.
1501///
1502/// This routine determines whether overloading is possible, not
1503/// whether a new declaration actually overloads a previous one.
1504/// It will return true in C++ (where overloads are alway permitted)
1505/// or, as a C extension, when either the new declaration or a
1506/// previous one is declared with the 'overloadable' attribute.
1507static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1508 ASTContext &Context,
1509 const FunctionDecl *New) {
1510 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1511 return true;
1512
1513 // Multiversion function declarations are not overloads in the
1514 // usual sense of that term, but lookup will report that an
1515 // overload set was found if more than one multiversion function
1516 // declaration is present for the same name. It is therefore
1517 // inadequate to assume that some prior declaration(s) had
1518 // the overloadable attribute; checking is required. Since one
1519 // declaration is permitted to omit the attribute, it is necessary
1520 // to check at least two; hence the 'any_of' check below. Note that
1521 // the overloadable attribute is implicitly added to declarations
1522 // that were required to have it but did not.
1523 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1524 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1525 return ND->hasAttr<OverloadableAttr>();
1526 });
1527 } else if (Previous.getResultKind() == LookupResult::Found)
1528 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1529
1530 return false;
1531}
1532
1533/// Add this decl to the scope shadowed decl chains.
1534void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1535 // Move up the scope chain until we find the nearest enclosing
1536 // non-transparent context. The declaration will be introduced into this
1537 // scope.
1538 while (S->getEntity() && S->getEntity()->isTransparentContext())
1539 S = S->getParent();
1540
1541 // Add scoped declarations into their context, so that they can be
1542 // found later. Declarations without a context won't be inserted
1543 // into any context.
1544 if (AddToContext)
1545 CurContext->addDecl(D);
1546
1547 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1548 // are function-local declarations.
1549 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1550 return;
1551
1552 // Template instantiations should also not be pushed into scope.
1553 if (isa<FunctionDecl>(D) &&
1554 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1555 return;
1556
1557 // If this replaces anything in the current scope,
1558 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1559 IEnd = IdResolver.end();
1560 for (; I != IEnd; ++I) {
1561 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1562 S->RemoveDecl(*I);
1563 IdResolver.RemoveDecl(*I);
1564
1565 // Should only need to replace one decl.
1566 break;
1567 }
1568 }
1569
1570 S->AddDecl(D);
1571
1572 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1573 // Implicitly-generated labels may end up getting generated in an order that
1574 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1575 // the label at the appropriate place in the identifier chain.
1576 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1577 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1578 if (IDC == CurContext) {
1579 if (!S->isDeclScope(*I))
1580 continue;
1581 } else if (IDC->Encloses(CurContext))
1582 break;
1583 }
1584
1585 IdResolver.InsertDeclAfter(I, D);
1586 } else {
1587 IdResolver.AddDecl(D);
1588 }
1589 warnOnReservedIdentifier(D);
1590}
1591
1592bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1593 bool AllowInlineNamespace) {
1594 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1595}
1596
1597Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1598 DeclContext *TargetDC = DC->getPrimaryContext();
1599 do {
1600 if (DeclContext *ScopeDC = S->getEntity())
1601 if (ScopeDC->getPrimaryContext() == TargetDC)
1602 return S;
1603 } while ((S = S->getParent()));
1604
1605 return nullptr;
1606}
1607
1608static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1609 DeclContext*,
1610 ASTContext&);
1611
1612/// Filters out lookup results that don't fall within the given scope
1613/// as determined by isDeclInScope.
1614void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1615 bool ConsiderLinkage,
1616 bool AllowInlineNamespace) {
1617 LookupResult::Filter F = R.makeFilter();
1618 while (F.hasNext()) {
1619 NamedDecl *D = F.next();
1620
1621 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1622 continue;
1623
1624 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1625 continue;
1626
1627 F.erase();
1628 }
1629
1630 F.done();
1631}
1632
1633/// We've determined that \p New is a redeclaration of \p Old. Check that they
1634/// have compatible owning modules.
1635bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1636 // [module.interface]p7:
1637 // A declaration is attached to a module as follows:
1638 // - If the declaration is a non-dependent friend declaration that nominates a
1639 // function with a declarator-id that is a qualified-id or template-id or that
1640 // nominates a class other than with an elaborated-type-specifier with neither
1641 // a nested-name-specifier nor a simple-template-id, it is attached to the
1642 // module to which the friend is attached ([basic.link]).
1643 if (New->getFriendObjectKind() &&
1644 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1645 New->setLocalOwningModule(Old->getOwningModule());
1646 makeMergedDefinitionVisible(New);
1647 return false;
1648 }
1649
1650 Module *NewM = New->getOwningModule();
1651 Module *OldM = Old->getOwningModule();
1652
1653 if (NewM && NewM->isPrivateModule())
1654 NewM = NewM->Parent;
1655 if (OldM && OldM->isPrivateModule())
1656 OldM = OldM->Parent;
1657
1658 if (NewM == OldM)
1659 return false;
1660
1661 // Partitions are part of the module, but a partition could import another
1662 // module, so verify that the PMIs agree.
1663 if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition()))
1664 return NewM->getPrimaryModuleInterfaceName() ==
1665 OldM->getPrimaryModuleInterfaceName();
1666
1667 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1668 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1669 if (NewIsModuleInterface || OldIsModuleInterface) {
1670 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1671 // if a declaration of D [...] appears in the purview of a module, all
1672 // other such declarations shall appear in the purview of the same module
1673 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1674 << New
1675 << NewIsModuleInterface
1676 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1677 << OldIsModuleInterface
1678 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1679 Diag(Old->getLocation(), diag::note_previous_declaration);
1680 New->setInvalidDecl();
1681 return true;
1682 }
1683
1684 return false;
1685}
1686
1687// [module.interface]p6:
1688// A redeclaration of an entity X is implicitly exported if X was introduced by
1689// an exported declaration; otherwise it shall not be exported.
1690bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1691 // [module.interface]p1:
1692 // An export-declaration shall inhabit a namespace scope.
1693 //
1694 // So it is meaningless to talk about redeclaration which is not at namespace
1695 // scope.
1696 if (!New->getLexicalDeclContext()
1697 ->getNonTransparentContext()
1698 ->isFileContext() ||
1699 !Old->getLexicalDeclContext()
1700 ->getNonTransparentContext()
1701 ->isFileContext())
1702 return false;
1703
1704 bool IsNewExported = New->isInExportDeclContext();
1705 bool IsOldExported = Old->isInExportDeclContext();
1706
1707 // It should be irrevelant if both of them are not exported.
1708 if (!IsNewExported && !IsOldExported)
1709 return false;
1710
1711 if (IsOldExported)
1712 return false;
1713
1714 assert(IsNewExported)(static_cast <bool> (IsNewExported) ? void (0) : __assert_fail
("IsNewExported", "clang/lib/Sema/SemaDecl.cpp", 1714, __extension__
__PRETTY_FUNCTION__))
;
1715
1716 auto Lk = Old->getFormalLinkage();
1717 int S = 0;
1718 if (Lk == Linkage::InternalLinkage)
1719 S = 1;
1720 else if (Lk == Linkage::ModuleLinkage)
1721 S = 2;
1722 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1723 Diag(Old->getLocation(), diag::note_previous_declaration);
1724 return true;
1725}
1726
1727// A wrapper function for checking the semantic restrictions of
1728// a redeclaration within a module.
1729bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1730 if (CheckRedeclarationModuleOwnership(New, Old))
1731 return true;
1732
1733 if (CheckRedeclarationExported(New, Old))
1734 return true;
1735
1736 return false;
1737}
1738
1739// Check the redefinition in C++20 Modules.
1740//
1741// [basic.def.odr]p14:
1742// For any definable item D with definitions in multiple translation units,
1743// - if D is a non-inline non-templated function or variable, or
1744// - if the definitions in different translation units do not satisfy the
1745// following requirements,
1746// the program is ill-formed; a diagnostic is required only if the definable
1747// item is attached to a named module and a prior definition is reachable at
1748// the point where a later definition occurs.
1749// - Each such definition shall not be attached to a named module
1750// ([module.unit]).
1751// - Each such definition shall consist of the same sequence of tokens, ...
1752// ...
1753//
1754// Return true if the redefinition is not allowed. Return false otherwise.
1755bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1756 const NamedDecl *Old) const {
1757 assert(getASTContext().isSameEntity(New, Old) &&(static_cast <bool> (getASTContext().isSameEntity(New, Old
) && "New and Old are not the same definition, we should diagnostic it "
"immediately instead of checking it.") ? void (0) : __assert_fail
("getASTContext().isSameEntity(New, Old) && \"New and Old are not the same definition, we should diagnostic it \" \"immediately instead of checking it.\""
, "clang/lib/Sema/SemaDecl.cpp", 1759, __extension__ __PRETTY_FUNCTION__
))
1758 "New and Old are not the same definition, we should diagnostic it "(static_cast <bool> (getASTContext().isSameEntity(New, Old
) && "New and Old are not the same definition, we should diagnostic it "
"immediately instead of checking it.") ? void (0) : __assert_fail
("getASTContext().isSameEntity(New, Old) && \"New and Old are not the same definition, we should diagnostic it \" \"immediately instead of checking it.\""
, "clang/lib/Sema/SemaDecl.cpp", 1759, __extension__ __PRETTY_FUNCTION__
))
1759 "immediately instead of checking it.")(static_cast <bool> (getASTContext().isSameEntity(New, Old
) && "New and Old are not the same definition, we should diagnostic it "
"immediately instead of checking it.") ? void (0) : __assert_fail
("getASTContext().isSameEntity(New, Old) && \"New and Old are not the same definition, we should diagnostic it \" \"immediately instead of checking it.\""
, "clang/lib/Sema/SemaDecl.cpp", 1759, __extension__ __PRETTY_FUNCTION__
))
;
1760 assert(const_cast<Sema *>(this)->isReachable(New) &&(static_cast <bool> (const_cast<Sema *>(this)->
isReachable(New) && const_cast<Sema *>(this)->
isReachable(Old) && "We shouldn't see unreachable definitions here."
) ? void (0) : __assert_fail ("const_cast<Sema *>(this)->isReachable(New) && const_cast<Sema *>(this)->isReachable(Old) && \"We shouldn't see unreachable definitions here.\""
, "clang/lib/Sema/SemaDecl.cpp", 1762, __extension__ __PRETTY_FUNCTION__
))
1761 const_cast<Sema *>(this)->isReachable(Old) &&(static_cast <bool> (const_cast<Sema *>(this)->
isReachable(New) && const_cast<Sema *>(this)->
isReachable(Old) && "We shouldn't see unreachable definitions here."
) ? void (0) : __assert_fail ("const_cast<Sema *>(this)->isReachable(New) && const_cast<Sema *>(this)->isReachable(Old) && \"We shouldn't see unreachable definitions here.\""
, "clang/lib/Sema/SemaDecl.cpp", 1762, __extension__ __PRETTY_FUNCTION__
))
1762 "We shouldn't see unreachable definitions here.")(static_cast <bool> (const_cast<Sema *>(this)->
isReachable(New) && const_cast<Sema *>(this)->
isReachable(Old) && "We shouldn't see unreachable definitions here."
) ? void (0) : __assert_fail ("const_cast<Sema *>(this)->isReachable(New) && const_cast<Sema *>(this)->isReachable(Old) && \"We shouldn't see unreachable definitions here.\""
, "clang/lib/Sema/SemaDecl.cpp", 1762, __extension__ __PRETTY_FUNCTION__
))
;
1763
1764 Module *NewM = New->getOwningModule();
1765 Module *OldM = Old->getOwningModule();
1766
1767 // We only checks for named modules here. The header like modules is skipped.
1768 // FIXME: This is not right if we import the header like modules in the module
1769 // purview.
1770 //
1771 // For example, assuming "header.h" provides definition for `D`.
1772 // ```C++
1773 // //--- M.cppm
1774 // export module M;
1775 // import "header.h"; // or #include "header.h" but import it by clang modules
1776 // actually.
1777 //
1778 // //--- Use.cpp
1779 // import M;
1780 // import "header.h"; // or uses clang modules.
1781 // ```
1782 //
1783 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1784 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1785 // reject it. But the current implementation couldn't detect the case since we
1786 // don't record the information about the importee modules.
1787 //
1788 // But this might not be painful in practice. Since the design of C++20 Named
1789 // Modules suggests us to use headers in global module fragment instead of
1790 // module purview.
1791 if (NewM && NewM->isHeaderLikeModule())
1792 NewM = nullptr;
1793 if (OldM && OldM->isHeaderLikeModule())
1794 OldM = nullptr;
1795
1796 if (!NewM && !OldM)
1797 return true;
1798
1799 // [basic.def.odr]p14.3
1800 // Each such definition shall not be attached to a named module
1801 // ([module.unit]).
1802 if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1803 return true;
1804
1805 // Then New and Old lives in the same TU if their share one same module unit.
1806 if (NewM)
1807 NewM = NewM->getTopLevelModule();
1808 if (OldM)
1809 OldM = OldM->getTopLevelModule();
1810 return OldM == NewM;
1811}
1812
1813static bool isUsingDecl(NamedDecl *D) {
1814 return isa<UsingShadowDecl>(D) ||
1815 isa<UnresolvedUsingTypenameDecl>(D) ||
1816 isa<UnresolvedUsingValueDecl>(D);
1817}
1818
1819/// Removes using shadow declarations from the lookup results.
1820static void RemoveUsingDecls(LookupResult &R) {
1821 LookupResult::Filter F = R.makeFilter();
1822 while (F.hasNext())
1823 if (isUsingDecl(F.next()))
1824 F.erase();
1825
1826 F.done();
1827}
1828
1829/// Check for this common pattern:
1830/// @code
1831/// class S {
1832/// S(const S&); // DO NOT IMPLEMENT
1833/// void operator=(const S&); // DO NOT IMPLEMENT
1834/// };
1835/// @endcode
1836static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1837 // FIXME: Should check for private access too but access is set after we get
1838 // the decl here.
1839 if (D->doesThisDeclarationHaveABody())
1840 return false;
1841
1842 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1843 return CD->isCopyConstructor();
1844 return D->isCopyAssignmentOperator();
1845}
1846
1847// We need this to handle
1848//
1849// typedef struct {
1850// void *foo() { return 0; }
1851// } A;
1852//
1853// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1854// for example. If 'A', foo will have external linkage. If we have '*A',
1855// foo will have no linkage. Since we can't know until we get to the end
1856// of the typedef, this function finds out if D might have non-external linkage.
1857// Callers should verify at the end of the TU if it D has external linkage or
1858// not.
1859bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1860 const DeclContext *DC = D->getDeclContext();
1861 while (!DC->isTranslationUnit()) {
1862 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1863 if (!RD->hasNameForLinkage())
1864 return true;
1865 }
1866 DC = DC->getParent();
1867 }
1868
1869 return !D->isExternallyVisible();
1870}
1871
1872// FIXME: This needs to be refactored; some other isInMainFile users want
1873// these semantics.
1874static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1875 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1876 return false;
1877 return S.SourceMgr.isInMainFile(Loc);
1878}
1879
1880bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1881 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/Sema/SemaDecl.cpp", 1881, __extension__ __PRETTY_FUNCTION__
))
;
1882
1883 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1884 return false;
1885
1886 // Ignore all entities declared within templates, and out-of-line definitions
1887 // of members of class templates.
1888 if (D->getDeclContext()->isDependentContext() ||
1889 D->getLexicalDeclContext()->isDependentContext())
1890 return false;
1891
1892 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1893 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1894 return false;
1895 // A non-out-of-line declaration of a member specialization was implicitly
1896 // instantiated; it's the out-of-line declaration that we're interested in.
1897 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1898 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1899 return false;
1900
1901 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1902 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1903 return false;
1904 } else {
1905 // 'static inline' functions are defined in headers; don't warn.
1906 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1907 return false;
1908 }
1909
1910 if (FD->doesThisDeclarationHaveABody() &&
1911 Context.DeclMustBeEmitted(FD))
1912 return false;
1913 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1914 // Constants and utility variables are defined in headers with internal
1915 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1916 // like "inline".)
1917 if (!isMainFileLoc(*this, VD->getLocation()))
1918 return false;
1919
1920 if (Context.DeclMustBeEmitted(VD))
1921 return false;
1922
1923 if (VD->isStaticDataMember() &&
1924 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1925 return false;
1926 if (VD->isStaticDataMember() &&
1927 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1928 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1929 return false;
1930
1931 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1932 return false;
1933 } else {
1934 return false;
1935 }
1936
1937 // Only warn for unused decls internal to the translation unit.
1938 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1939 // for inline functions defined in the main source file, for instance.
1940 return mightHaveNonExternalLinkage(D);
1941}
1942
1943void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1944 if (!D)
1945 return;
1946
1947 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1948 const FunctionDecl *First = FD->getFirstDecl();
1949 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1950 return; // First should already be in the vector.
1951 }
1952
1953 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1954 const VarDecl *First = VD->getFirstDecl();
1955 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1956 return; // First should already be in the vector.
1957 }
1958
1959 if (ShouldWarnIfUnusedFileScopedDecl(D))
1960 UnusedFileScopedDecls.push_back(D);
1961}
1962
1963static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1964 if (D->isInvalidDecl())
1965 return false;
1966
1967 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1968 // For a decomposition declaration, warn if none of the bindings are
1969 // referenced, instead of if the variable itself is referenced (which
1970 // it is, by the bindings' expressions).
1971 for (auto *BD : DD->bindings())
1972 if (BD->isReferenced())
1973 return false;
1974 } else if (!D->getDeclName()) {
1975 return false;
1976 } else if (D->isReferenced() || D->isUsed()) {
1977 return false;
1978 }
1979
1980 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1981 return false;
1982
1983 if (isa<LabelDecl>(D))
1984 return true;
1985
1986 // Except for labels, we only care about unused decls that are local to
1987 // functions.
1988 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1989 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1990 // For dependent types, the diagnostic is deferred.
1991 WithinFunction =
1992 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1993 if (!WithinFunction)
1994 return false;
1995
1996 if (isa<TypedefNameDecl>(D))
1997 return true;
1998
1999 // White-list anything that isn't a local variable.
2000 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2001 return false;
2002
2003 // Types of valid local variables should be complete, so this should succeed.
2004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2005
2006 const Expr *Init = VD->getInit();
2007 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2008 Init = Cleanups->getSubExpr();
2009
2010 const auto *Ty = VD->getType().getTypePtr();
2011
2012 // Only look at the outermost level of typedef.
2013 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2014 // Allow anything marked with __attribute__((unused)).
2015 if (TT->getDecl()->hasAttr<UnusedAttr>())
2016 return false;
2017 }
2018
2019 // Warn for reference variables whose initializtion performs lifetime
2020 // extension.
2021 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2022 if (MTE->getExtendingDecl()) {
2023 Ty = VD->getType().getNonReferenceType().getTypePtr();
2024 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2025 }
2026 }
2027
2028 // If we failed to complete the type for some reason, or if the type is
2029 // dependent, don't diagnose the variable.
2030 if (Ty->isIncompleteType() || Ty->isDependentType())
2031 return false;
2032
2033 // Look at the element type to ensure that the warning behaviour is
2034 // consistent for both scalars and arrays.
2035 Ty = Ty->getBaseElementTypeUnsafe();
2036
2037 if (const TagType *TT = Ty->getAs<TagType>()) {
2038 const TagDecl *Tag = TT->getDecl();
2039 if (Tag->hasAttr<UnusedAttr>())
2040 return false;
2041
2042 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2043 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2044 return false;
2045
2046 if (Init) {
2047 const CXXConstructExpr *Construct =
2048 dyn_cast<CXXConstructExpr>(Init);
2049 if (Construct && !Construct->isElidable()) {
2050 CXXConstructorDecl *CD = Construct->getConstructor();
2051 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2052 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2053 return false;
2054 }
2055
2056 // Suppress the warning if we don't know how this is constructed, and
2057 // it could possibly be non-trivial constructor.
2058 if (Init->isTypeDependent()) {
2059 for (const CXXConstructorDecl *Ctor : RD->ctors())
2060 if (!Ctor->isTrivial())
2061 return false;
2062 }
2063
2064 // Suppress the warning if the constructor is unresolved because
2065 // its arguments are dependent.
2066 if (isa<CXXUnresolvedConstructExpr>(Init))
2067 return false;
2068 }
2069 }
2070 }
2071
2072 // TODO: __attribute__((unused)) templates?
2073 }
2074
2075 return true;
2076}
2077
2078static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2079 FixItHint &Hint) {
2080 if (isa<LabelDecl>(D)) {
2081 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2082 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2083 true);
2084 if (AfterColon.isInvalid())
2085 return;
2086 Hint = FixItHint::CreateRemoval(
2087 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2088 }
2089}
2090
2091void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2092 if (D->getTypeForDecl()->isDependentType())
2093 return;
2094
2095 for (auto *TmpD : D->decls()) {
2096 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2097 DiagnoseUnusedDecl(T);
2098 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2099 DiagnoseUnusedNestedTypedefs(R);
2100 }
2101}
2102
2103/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2104/// unless they are marked attr(unused).
2105void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2106 if (!ShouldDiagnoseUnusedDecl(D))
2107 return;
2108
2109 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2110 // typedefs can be referenced later on, so the diagnostics are emitted
2111 // at end-of-translation-unit.
2112 UnusedLocalTypedefNameCandidates.insert(TD);
2113 return;
2114 }
2115
2116 FixItHint Hint;
2117 GenerateFixForUnusedDecl(D, Context, Hint);
2118
2119 unsigned DiagID;
2120 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2121 DiagID = diag::warn_unused_exception_param;
2122 else if (isa<LabelDecl>(D))
2123 DiagID = diag::warn_unused_label;
2124 else
2125 DiagID = diag::warn_unused_variable;
2126
2127 Diag(D->getLocation(), DiagID) << D << Hint;
2128}
2129
2130void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2131 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2132 // it's not really unused.
2133 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2134 VD->hasAttr<CleanupAttr>())
2135 return;
2136
2137 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2138
2139 if (Ty->isReferenceType() || Ty->isDependentType())
2140 return;
2141
2142 if (const TagType *TT = Ty->getAs<TagType>()) {
2143 const TagDecl *Tag = TT->getDecl();
2144 if (Tag->hasAttr<UnusedAttr>())
2145 return;
2146 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2147 // mimic gcc's behavior.
2148 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2149 if (!RD->hasAttr<WarnUnusedAttr>())
2150 return;
2151 }
2152 }
2153
2154 // Don't warn about __block Objective-C pointer variables, as they might
2155 // be assigned in the block but not used elsewhere for the purpose of lifetime
2156 // extension.
2157 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2158 return;
2159
2160 // Don't warn about Objective-C pointer variables with precise lifetime
2161 // semantics; they can be used to ensure ARC releases the object at a known
2162 // time, which may mean assignment but no other references.
2163 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2164 return;
2165
2166 auto iter = RefsMinusAssignments.find(VD);
2167 if (iter == RefsMinusAssignments.end())
2168 return;
2169
2170 assert(iter->getSecond() >= 0 &&(static_cast <bool> (iter->getSecond() >= 0 &&
"Found a negative number of references to a VarDecl") ? void
(0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\""
, "clang/lib/Sema/SemaDecl.cpp", 2171, __extension__ __PRETTY_FUNCTION__
))
2171 "Found a negative number of references to a VarDecl")(static_cast <bool> (iter->getSecond() >= 0 &&
"Found a negative number of references to a VarDecl") ? void
(0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\""
, "clang/lib/Sema/SemaDecl.cpp", 2171, __extension__ __PRETTY_FUNCTION__
))
;
2172 if (iter->getSecond() != 0)
2173 return;
2174 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2175 : diag::warn_unused_but_set_variable;
2176 Diag(VD->getLocation(), DiagID) << VD;
2177}
2178
2179static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2180 // Verify that we have no forward references left. If so, there was a goto
2181 // or address of a label taken, but no definition of it. Label fwd
2182 // definitions are indicated with a null substmt which is also not a resolved
2183 // MS inline assembly label name.
2184 bool Diagnose = false;
2185 if (L->isMSAsmLabel())
2186 Diagnose = !L->isResolvedMSAsmLabel();
2187 else
2188 Diagnose = L->getStmt() == nullptr;
2189 if (Diagnose)
2190 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2191}
2192
2193void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2194 S->applyNRVO();
2195
2196 if (S->decl_empty()) return;
2197 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "clang/lib/Sema/SemaDecl.cpp", 2198, __extension__ __PRETTY_FUNCTION__
))
2198 "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "clang/lib/Sema/SemaDecl.cpp", 2198, __extension__ __PRETTY_FUNCTION__
))
;
2199
2200 for (auto *TmpD : S->decls()) {
2201 assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??"
) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "clang/lib/Sema/SemaDecl.cpp", 2201, __extension__ __PRETTY_FUNCTION__
))
;
2202
2203 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) &&
"Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "clang/lib/Sema/SemaDecl.cpp", 2203, __extension__ __PRETTY_FUNCTION__
))
;
2204 NamedDecl *D = cast<NamedDecl>(TmpD);
2205
2206 // Diagnose unused variables in this scope.
2207 if (!S->hasUnrecoverableErrorOccurred()) {
2208 DiagnoseUnusedDecl(D);
2209 if (const auto *RD = dyn_cast<RecordDecl>(D))
2210 DiagnoseUnusedNestedTypedefs(RD);
2211 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2212 DiagnoseUnusedButSetDecl(VD);
2213 RefsMinusAssignments.erase(VD);
2214 }
2215 }
2216
2217 if (!D->getDeclName()) continue;
2218
2219 // If this was a forward reference to a label, verify it was defined.
2220 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2221 CheckPoppedLabel(LD, *this);
2222
2223 // Remove this name from our lexical scope, and warn on it if we haven't
2224 // already.
2225 IdResolver.RemoveDecl(D);
2226 auto ShadowI = ShadowingDecls.find(D);
2227 if (ShadowI != ShadowingDecls.end()) {
2228 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2229 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2230 << D << FD << FD->getParent();
2231 Diag(FD->getLocation(), diag::note_previous_declaration);
2232 }
2233 ShadowingDecls.erase(ShadowI);
2234 }
2235 }
2236}
2237
2238/// Look for an Objective-C class in the translation unit.
2239///
2240/// \param Id The name of the Objective-C class we're looking for. If
2241/// typo-correction fixes this name, the Id will be updated
2242/// to the fixed name.
2243///
2244/// \param IdLoc The location of the name in the translation unit.
2245///
2246/// \param DoTypoCorrection If true, this routine will attempt typo correction
2247/// if there is no class with the given name.
2248///
2249/// \returns The declaration of the named Objective-C class, or NULL if the
2250/// class could not be found.
2251ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2252 SourceLocation IdLoc,
2253 bool DoTypoCorrection) {
2254 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2255 // creation from this context.
2256 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2257
2258 if (!IDecl && DoTypoCorrection) {
2259 // Perform typo correction at the given location, but only if we
2260 // find an Objective-C class name.
2261 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2262 if (TypoCorrection C =
2263 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2264 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2265 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2266 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2267 Id = IDecl->getIdentifier();
2268 }
2269 }
2270 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2271 // This routine must always return a class definition, if any.
2272 if (Def && Def->getDefinition())
2273 Def = Def->getDefinition();
2274 return Def;
2275}
2276
2277/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2278/// from S, where a non-field would be declared. This routine copes
2279/// with the difference between C and C++ scoping rules in structs and
2280/// unions. For example, the following code is well-formed in C but
2281/// ill-formed in C++:
2282/// @code
2283/// struct S6 {
2284/// enum { BAR } e;
2285/// };
2286///
2287/// void test_S6() {
2288/// struct S6 a;
2289/// a.e = BAR;
2290/// }
2291/// @endcode
2292/// For the declaration of BAR, this routine will return a different
2293/// scope. The scope S will be the scope of the unnamed enumeration
2294/// within S6. In C++, this routine will return the scope associated
2295/// with S6, because the enumeration's scope is a transparent
2296/// context but structures can contain non-field names. In C, this
2297/// routine will return the translation unit scope, since the
2298/// enumeration's scope is a transparent context and structures cannot
2299/// contain non-field names.
2300Scope *Sema::getNonFieldDeclScope(Scope *S) {
2301 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2302 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2303 (S->isClassScope() && !getLangOpts().CPlusPlus))
2304 S = S->getParent();
2305 return S;
2306}
2307
2308static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2309 ASTContext::GetBuiltinTypeError Error) {
2310 switch (Error) {
2311 case ASTContext::GE_None:
2312 return "";
2313 case ASTContext::GE_Missing_type:
2314 return BuiltinInfo.getHeaderName(ID);
2315 case ASTContext::GE_Missing_stdio:
2316 return "stdio.h";
2317 case ASTContext::GE_Missing_setjmp:
2318 return "setjmp.h";
2319 case ASTContext::GE_Missing_ucontext:
2320 return "ucontext.h";
2321 }
2322 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "clang/lib/Sema/SemaDecl.cpp"
, 2322)
;
2323}
2324
2325FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2326 unsigned ID, SourceLocation Loc) {
2327 DeclContext *Parent = Context.getTranslationUnitDecl();
2328
2329 if (getLangOpts().CPlusPlus) {
2330 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2331 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2332 CLinkageDecl->setImplicit();
2333 Parent->addDecl(CLinkageDecl);
2334 Parent = CLinkageDecl;
2335 }
2336
2337 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2338 /*TInfo=*/nullptr, SC_Extern,
2339 getCurFPFeatures().isFPConstrained(),
2340 false, Type->isFunctionProtoType());
2341 New->setImplicit();
2342 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2343
2344 // Create Decl objects for each parameter, adding them to the
2345 // FunctionDecl.
2346 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2347 SmallVector<ParmVarDecl *, 16> Params;
2348 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2349 ParmVarDecl *parm = ParmVarDecl::Create(
2350 Context, New, SourceLocation(), SourceLocation(), nullptr,
2351 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2352 parm->setScopeInfo(0, i);
2353 Params.push_back(parm);
2354 }
2355 New->setParams(Params);
2356 }
2357
2358 AddKnownFunctionAttributes(New);
2359 return New;
2360}
2361
2362/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2363/// file scope. lazily create a decl for it. ForRedeclaration is true
2364/// if we're creating this built-in in anticipation of redeclaring the
2365/// built-in.
2366NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2367 Scope *S, bool ForRedeclaration,
2368 SourceLocation Loc) {
2369 LookupNecessaryTypesForBuiltin(S, ID);
2370
2371 ASTContext::GetBuiltinTypeError Error;
2372 QualType R = Context.GetBuiltinType(ID, Error);
2373 if (Error) {
2374 if (!ForRedeclaration)
2375 return nullptr;
2376
2377 // If we have a builtin without an associated type we should not emit a
2378 // warning when we were not able to find a type for it.
2379 if (Error == ASTContext::GE_Missing_type ||
2380 Context.BuiltinInfo.allowTypeMismatch(ID))
2381 return nullptr;
2382
2383 // If we could not find a type for setjmp it is because the jmp_buf type was
2384 // not defined prior to the setjmp declaration.
2385 if (Error == ASTContext::GE_Missing_setjmp) {
2386 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2387 << Context.BuiltinInfo.getName(ID);
2388 return nullptr;
2389 }
2390
2391 // Generally, we emit a warning that the declaration requires the
2392 // appropriate header.
2393 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2394 << getHeaderName(Context.BuiltinInfo, ID, Error)
2395 << Context.BuiltinInfo.getName(ID);
2396 return nullptr;
2397 }
2398
2399 if (!ForRedeclaration &&
2400 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2401 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2402 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2403 : diag::ext_implicit_lib_function_decl)
2404 << Context.BuiltinInfo.getName(ID) << R;
2405 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2406 Diag(Loc, diag::note_include_header_or_declare)
2407 << Header << Context.BuiltinInfo.getName(ID);
2408 }
2409
2410 if (R.isNull())
2411 return nullptr;
2412
2413 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2414 RegisterLocallyScopedExternCDecl(New, S);
2415
2416 // TUScope is the translation-unit scope to insert this function into.
2417 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2418 // relate Scopes to DeclContexts, and probably eliminate CurContext
2419 // entirely, but we're not there yet.
2420 DeclContext *SavedContext = CurContext;
2421 CurContext = New->getDeclContext();
2422 PushOnScopeChains(New, TUScope);
2423 CurContext = SavedContext;
2424 return New;
2425}
2426
2427/// Typedef declarations don't have linkage, but they still denote the same
2428/// entity if their types are the same.
2429/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2430/// isSameEntity.
2431static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2432 TypedefNameDecl *Decl,
2433 LookupResult &Previous) {
2434 // This is only interesting when modules are enabled.
2435 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2436 return;
2437
2438 // Empty sets are uninteresting.
2439 if (Previous.empty())
2440 return;
2441
2442 LookupResult::Filter Filter = Previous.makeFilter();
2443 while (Filter.hasNext()) {
2444 NamedDecl *Old = Filter.next();
2445
2446 // Non-hidden declarations are never ignored.
2447 if (S.isVisible(Old))
2448 continue;
2449
2450 // Declarations of the same entity are not ignored, even if they have
2451 // different linkages.
2452 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2453 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2454 Decl->getUnderlyingType()))
2455 continue;
2456
2457 // If both declarations give a tag declaration a typedef name for linkage
2458 // purposes, then they declare the same entity.
2459 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2460 Decl->getAnonDeclWithTypedefName())
2461 continue;
2462 }
2463
2464 Filter.erase();
2465 }
2466
2467 Filter.done();
2468}
2469
2470bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2471 QualType OldType;
2472 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2473 OldType = OldTypedef->getUnderlyingType();
2474 else
2475 OldType = Context.getTypeDeclType(Old);
2476 QualType NewType = New->getUnderlyingType();
2477
2478 if (NewType->isVariablyModifiedType()) {
2479 // Must not redefine a typedef with a variably-modified type.
2480 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2481 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2482 << Kind << NewType;
2483 if (Old->getLocation().isValid())
2484 notePreviousDefinition(Old, New->getLocation());
2485 New->setInvalidDecl();
2486 return true;
2487 }
2488
2489 if (OldType != NewType &&
2490 !OldType->isDependentType() &&
2491 !NewType->isDependentType() &&
2492 !Context.hasSameType(OldType, NewType)) {
2493 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2494 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2495 << Kind << NewType << OldType;
2496 if (Old->getLocation().isValid())
2497 notePreviousDefinition(Old, New->getLocation());
2498 New->setInvalidDecl();
2499 return true;
2500 }
2501 return false;
2502}
2503
2504/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2505/// same name and scope as a previous declaration 'Old'. Figure out
2506/// how to resolve this situation, merging decls or emitting
2507/// diagnostics as appropriate. If there was an error, set New to be invalid.
2508///
2509void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2510 LookupResult &OldDecls) {
2511 // If the new decl is known invalid already, don't bother doing any
2512 // merging checks.
2513 if (New->isInvalidDecl()) return;
2514
2515 // Allow multiple definitions for ObjC built-in typedefs.
2516 // FIXME: Verify the underlying types are equivalent!
2517 if (getLangOpts().ObjC) {
2518 const IdentifierInfo *TypeID = New->getIdentifier();
2519 switch (TypeID->getLength()) {
2520 default: break;
2521 case 2:
2522 {
2523 if (!TypeID->isStr("id"))
2524 break;
2525 QualType T = New->getUnderlyingType();
2526 if (!T->isPointerType())
2527 break;
2528 if (!T->isVoidPointerType()) {
2529 QualType PT = T->castAs<PointerType>()->getPointeeType();
2530 if (!PT->isStructureType())
2531 break;
2532 }
2533 Context.setObjCIdRedefinitionType(T);
2534 // Install the built-in type for 'id', ignoring the current definition.
2535 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2536 return;
2537 }
2538 case 5:
2539 if (!TypeID->isStr("Class"))
2540 break;
2541 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2542 // Install the built-in type for 'Class', ignoring the current definition.
2543 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2544 return;
2545 case 3:
2546 if (!TypeID->isStr("SEL"))
2547 break;
2548 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2549 // Install the built-in type for 'SEL', ignoring the current definition.
2550 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2551 return;
2552 }
2553 // Fall through - the typedef name was not a builtin type.
2554 }
2555
2556 // Verify the old decl was also a type.
2557 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2558 if (!Old) {
2559 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2560 << New->getDeclName();
2561
2562 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2563 if (OldD->getLocation().isValid())
2564 notePreviousDefinition(OldD, New->getLocation());
2565
2566 return New->setInvalidDecl();
2567 }
2568
2569 // If the old declaration is invalid, just give up here.
2570 if (Old->isInvalidDecl())
2571 return New->setInvalidDecl();
2572
2573 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2574 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2575 auto *NewTag = New->getAnonDeclWithTypedefName();
2576 NamedDecl *Hidden = nullptr;
2577 if (OldTag && NewTag &&
2578 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2579 !hasVisibleDefinition(OldTag, &Hidden)) {
2580 // There is a definition of this tag, but it is not visible. Use it
2581 // instead of our tag.
2582 New->setTypeForDecl(OldTD->getTypeForDecl());
2583 if (OldTD->isModed())
2584 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2585 OldTD->getUnderlyingType());
2586 else
2587 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2588
2589 // Make the old tag definition visible.
2590 makeMergedDefinitionVisible(Hidden);
2591
2592 // If this was an unscoped enumeration, yank all of its enumerators
2593 // out of the scope.
2594 if (isa<EnumDecl>(NewTag)) {
2595 Scope *EnumScope = getNonFieldDeclScope(S);
2596 for (auto *D : NewTag->decls()) {
2597 auto *ED = cast<EnumConstantDecl>(D);
2598 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "clang/lib/Sema/SemaDecl.cpp"
, 2598, __extension__ __PRETTY_FUNCTION__))
;
2599 EnumScope->RemoveDecl(ED);
2600 IdResolver.RemoveDecl(ED);
2601 ED->getLexicalDeclContext()->removeDecl(ED);
2602 }
2603 }
2604 }
2605 }
2606
2607 // If the typedef types are not identical, reject them in all languages and
2608 // with any extensions enabled.
2609 if (isIncompatibleTypedef(Old, New))
2610 return;
2611
2612 // The types match. Link up the redeclaration chain and merge attributes if
2613 // the old declaration was a typedef.
2614 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2615 New->setPreviousDecl(Typedef);
2616 mergeDeclAttributes(New, Old);
2617 }
2618
2619 if (getLangOpts().MicrosoftExt)
2620 return;
2621
2622 if (getLangOpts().CPlusPlus) {
2623 // C++ [dcl.typedef]p2:
2624 // In a given non-class scope, a typedef specifier can be used to
2625 // redefine the name of any type declared in that scope to refer
2626 // to the type to which it already refers.
2627 if (!isa<CXXRecordDecl>(CurContext))
2628 return;
2629
2630 // C++0x [dcl.typedef]p4:
2631 // In a given class scope, a typedef specifier can be used to redefine
2632 // any class-name declared in that scope that is not also a typedef-name
2633 // to refer to the type to which it already refers.
2634 //
2635 // This wording came in via DR424, which was a correction to the
2636 // wording in DR56, which accidentally banned code like:
2637 //
2638 // struct S {
2639 // typedef struct A { } A;
2640 // };
2641 //
2642 // in the C++03 standard. We implement the C++0x semantics, which
2643 // allow the above but disallow
2644 //
2645 // struct S {
2646 // typedef int I;
2647 // typedef int I;
2648 // };
2649 //
2650 // since that was the intent of DR56.
2651 if (!isa<TypedefNameDecl>(Old))
2652 return;
2653
2654 Diag(New->getLocation(), diag::err_redefinition)
2655 << New->getDeclName();
2656 notePreviousDefinition(Old, New->getLocation());
2657 return New->setInvalidDecl();
2658 }
2659
2660 // Modules always permit redefinition of typedefs, as does C11.
2661 if (getLangOpts().Modules || getLangOpts().C11)
2662 return;
2663
2664 // If we have a redefinition of a typedef in C, emit a warning. This warning
2665 // is normally mapped to an error, but can be controlled with
2666 // -Wtypedef-redefinition. If either the original or the redefinition is
2667 // in a system header, don't emit this for compatibility with GCC.
2668 if (getDiagnostics().getSuppressSystemWarnings() &&
2669 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2670 (Old->isImplicit() ||
2671 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2672 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2673 return;
2674
2675 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2676 << New->getDeclName();
2677 notePreviousDefinition(Old, New->getLocation());
2678}
2679
2680/// DeclhasAttr - returns true if decl Declaration already has the target
2681/// attribute.
2682static bool DeclHasAttr(const Decl *D, const Attr *A) {
2683 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2684 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2685 for (const auto *i : D->attrs())
2686 if (i->getKind() == A->getKind()) {
2687 if (Ann) {
2688 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2689 return true;
2690 continue;
2691 }
2692 // FIXME: Don't hardcode this check
2693 if (OA && isa<OwnershipAttr>(i))
2694 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2695 return true;
2696 }
2697
2698 return false;
2699}
2700
2701static bool isAttributeTargetADefinition(Decl *D) {
2702 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2703 return VD->isThisDeclarationADefinition();
2704 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2705 return TD->isCompleteDefinition() || TD->isBeingDefined();
2706 return true;
2707}
2708
2709/// Merge alignment attributes from \p Old to \p New, taking into account the
2710/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2711///
2712/// \return \c true if any attributes were added to \p New.
2713static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2714 // Look for alignas attributes on Old, and pick out whichever attribute
2715 // specifies the strictest alignment requirement.
2716 AlignedAttr *OldAlignasAttr = nullptr;
2717 AlignedAttr *OldStrictestAlignAttr = nullptr;
2718 unsigned OldAlign = 0;
2719 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2720 // FIXME: We have no way of representing inherited dependent alignments
2721 // in a case like:
2722 // template<int A, int B> struct alignas(A) X;
2723 // template<int A, int B> struct alignas(B) X {};
2724 // For now, we just ignore any alignas attributes which are not on the
2725 // definition in such a case.
2726 if (I->isAlignmentDependent())
2727 return false;
2728
2729 if (I->isAlignas())
2730 OldAlignasAttr = I;
2731
2732 unsigned Align = I->getAlignment(S.Context);
2733 if (Align > OldAlign) {
2734 OldAlign = Align;
2735 OldStrictestAlignAttr = I;
2736 }
2737 }
2738
2739 // Look for alignas attributes on New.
2740 AlignedAttr *NewAlignasAttr = nullptr;
2741 unsigned NewAlign = 0;
2742 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2743 if (I->isAlignmentDependent())
2744 return false;
2745
2746 if (I->isAlignas())
2747 NewAlignasAttr = I;
2748
2749 unsigned Align = I->getAlignment(S.Context);
2750 if (Align > NewAlign)
2751 NewAlign = Align;
2752 }
2753
2754 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2755 // Both declarations have 'alignas' attributes. We require them to match.
2756 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2757 // fall short. (If two declarations both have alignas, they must both match
2758 // every definition, and so must match each other if there is a definition.)
2759
2760 // If either declaration only contains 'alignas(0)' specifiers, then it
2761 // specifies the natural alignment for the type.
2762 if (OldAlign == 0 || NewAlign == 0) {
2763 QualType Ty;
2764 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2765 Ty = VD->getType();
2766 else
2767 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2768
2769 if (OldAlign == 0)
2770 OldAlign = S.Context.getTypeAlign(Ty);
2771 if (NewAlign == 0)
2772 NewAlign = S.Context.getTypeAlign(Ty);
2773 }
2774
2775 if (OldAlign != NewAlign) {
2776 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2777 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2778 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2779 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2780 }
2781 }
2782
2783 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2784 // C++11 [dcl.align]p6:
2785 // if any declaration of an entity has an alignment-specifier,
2786 // every defining declaration of that entity shall specify an
2787 // equivalent alignment.
2788 // C11 6.7.5/7:
2789 // If the definition of an object does not have an alignment
2790 // specifier, any other declaration of that object shall also
2791 // have no alignment specifier.
2792 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2793 << OldAlignasAttr;
2794 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2795 << OldAlignasAttr;
2796 }
2797
2798 bool AnyAdded = false;
2799
2800 // Ensure we have an attribute representing the strictest alignment.
2801 if (OldAlign > NewAlign) {
2802 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2803 Clone->setInherited(true);
2804 New->addAttr(Clone);
2805 AnyAdded = true;
2806 }
2807
2808 // Ensure we have an alignas attribute if the old declaration had one.
2809 if (OldAlignasAttr && !NewAlignasAttr &&
2810 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2811 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2812 Clone->setInherited(true);
2813 New->addAttr(Clone);
2814 AnyAdded = true;
2815 }
2816
2817 return AnyAdded;
2818}
2819
2820#define WANT_DECL_MERGE_LOGIC
2821#include "clang/Sema/AttrParsedAttrImpl.inc"
2822#undef WANT_DECL_MERGE_LOGIC
2823
2824static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2825 const InheritableAttr *Attr,
2826 Sema::AvailabilityMergeKind AMK) {
2827 // Diagnose any mutual exclusions between the attribute that we want to add
2828 // and attributes that already exist on the declaration.
2829 if (!DiagnoseMutualExclusions(S, D, Attr))
2830 return false;
2831
2832 // This function copies an attribute Attr from a previous declaration to the
2833 // new declaration D if the new declaration doesn't itself have that attribute
2834 // yet or if that attribute allows duplicates.
2835 // If you're adding a new attribute that requires logic different from
2836 // "use explicit attribute on decl if present, else use attribute from
2837 // previous decl", for example if the attribute needs to be consistent
2838 // between redeclarations, you need to call a custom merge function here.
2839 InheritableAttr *NewAttr = nullptr;
2840 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2841 NewAttr = S.mergeAvailabilityAttr(
2842 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2843 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2844 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2845 AA->getPriority());
2846 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2847 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2848 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2849 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2850 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2851 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2852 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2853 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2854 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2855 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2856 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2857 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2858 FA->getFirstArg());
2859 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2860 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2861 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2862 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2863 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2864 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2865 IA->getInheritanceModel());
2866 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2867 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2868 &S.Context.Idents.get(AA->getSpelling()));
2869 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2870 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2871 isa<CUDAGlobalAttr>(Attr))) {
2872 // CUDA target attributes are part of function signature for
2873 // overloading purposes and must not be merged.
2874 return false;
2875 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2876 NewAttr = S.mergeMinSizeAttr(D, *MA);
2877 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2878 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2879 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2880 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2881 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2882 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2883 else if (isa<AlignedAttr>(Attr))
2884 // AlignedAttrs are handled separately, because we need to handle all
2885 // such attributes on a declaration at the same time.
2886 NewAttr = nullptr;
2887 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2888 (AMK == Sema::AMK_Override ||
2889 AMK == Sema::AMK_ProtocolImplementation ||
2890 AMK == Sema::AMK_OptionalProtocolImplementation))
2891 NewAttr = nullptr;
2892 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2893 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2894 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2895 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2896 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2897 NewAttr = S.mergeImportNameAttr(D, *INA);
2898 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2899 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2900 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2901 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2902 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2903 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2904 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2905 NewAttr =
2906 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2907 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2908 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2909 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2910 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2911
2912 if (NewAttr) {
2913 NewAttr->setInherited(true);
2914 D->addAttr(NewAttr);
2915 if (isa<MSInheritanceAttr>(NewAttr))
2916 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2917 return true;
2918 }
2919
2920 return false;
2921}
2922
2923static const NamedDecl *getDefinition(const Decl *D) {
2924 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2925 return TD->getDefinition();
2926 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2927 const VarDecl *Def = VD->getDefinition();
2928 if (Def)
2929 return Def;
2930 return VD->getActingDefinition();
2931 }
2932 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2933 const FunctionDecl *Def = nullptr;
2934 if (FD->isDefined(Def, true))
2935 return Def;
2936 }
2937 return nullptr;
2938}
2939
2940static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2941 for (const auto *Attribute : D->attrs())
2942 if (Attribute->getKind() == Kind)
2943 return true;
2944 return false;
2945}
2946
2947/// checkNewAttributesAfterDef - If we already have a definition, check that
2948/// there are no new attributes in this declaration.
2949static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2950 if (!New->hasAttrs())
2951 return;
2952
2953 const NamedDecl *Def = getDefinition(Old);
2954 if (!Def || Def == New)
2955 return;
2956
2957 AttrVec &NewAttributes = New->getAttrs();
2958 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2959 const Attr *NewAttribute = NewAttributes[I];
2960
2961 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2962 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2963 Sema::SkipBodyInfo SkipBody;
2964 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2965
2966 // If we're skipping this definition, drop the "alias" attribute.
2967 if (SkipBody.ShouldSkip) {
2968 NewAttributes.erase(NewAttributes.begin() + I);
2969 --E;
2970 continue;
2971 }
2972 } else {
2973 VarDecl *VD = cast<VarDecl>(New);
2974 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2975 VarDecl::TentativeDefinition
2976 ? diag::err_alias_after_tentative
2977 : diag::err_redefinition;
2978 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2979 if (Diag == diag::err_redefinition)
2980 S.notePreviousDefinition(Def, VD->getLocation());
2981 else
2982 S.Diag(Def->getLocation(), diag::note_previous_definition);
2983 VD->setInvalidDecl();
2984 }
2985 ++I;
2986 continue;
2987 }
2988
2989 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2990 // Tentative definitions are only interesting for the alias check above.
2991 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2992 ++I;
2993 continue;
2994 }
2995 }
2996
2997 if (hasAttribute(Def, NewAttribute->getKind())) {
2998 ++I;
2999 continue; // regular attr merging will take care of validating this.
3000 }
3001
3002 if (isa<C11NoReturnAttr>(NewAttribute)) {
3003 // C's _Noreturn is allowed to be added to a function after it is defined.
3004 ++I;
3005 continue;
3006 } else if (isa<UuidAttr>(NewAttribute)) {
3007 // msvc will allow a subsequent definition to add an uuid to a class
3008 ++I;
3009 continue;
3010 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3011 if (AA->isAlignas()) {
3012 // C++11 [dcl.align]p6:
3013 // if any declaration of an entity has an alignment-specifier,
3014 // every defining declaration of that entity shall specify an
3015 // equivalent alignment.
3016 // C11 6.7.5/7:
3017 // If the definition of an object does not have an alignment
3018 // specifier, any other declaration of that object shall also
3019 // have no alignment specifier.
3020 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3021 << AA;
3022 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3023 << AA;
3024 NewAttributes.erase(NewAttributes.begin() + I);
3025 --E;
3026 continue;
3027 }
3028 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3029 // If there is a C definition followed by a redeclaration with this
3030 // attribute then there are two different definitions. In C++, prefer the
3031 // standard diagnostics.
3032 if (!S.getLangOpts().CPlusPlus) {
3033 S.Diag(NewAttribute->getLocation(),
3034 diag::err_loader_uninitialized_redeclaration);
3035 S.Diag(Def->getLocation(), diag::note_previous_definition);
3036 NewAttributes.erase(NewAttributes.begin() + I);
3037 --E;
3038 continue;
3039 }
3040 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3041 cast<VarDecl>(New)->isInline() &&
3042 !cast<VarDecl>(New)->isInlineSpecified()) {
3043 // Don't warn about applying selectany to implicitly inline variables.
3044 // Older compilers and language modes would require the use of selectany
3045 // to make such variables inline, and it would have no effect if we
3046 // honored it.
3047 ++I;
3048 continue;
3049 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3050 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3051 // declarations after definitions.
3052 ++I;
3053 continue;
3054 }
3055
3056 S.Diag(NewAttribute->getLocation(),
3057 diag::warn_attribute_precede_definition);
3058 S.Diag(Def->getLocation(), diag::note_previous_definition);
3059 NewAttributes.erase(NewAttributes.begin() + I);
3060 --E;
3061 }
3062}
3063
3064static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3065 const ConstInitAttr *CIAttr,
3066 bool AttrBeforeInit) {
3067 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3068
3069 // Figure out a good way to write this specifier on the old declaration.
3070 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3071 // enough of the attribute list spelling information to extract that without
3072 // heroics.
3073 std::string SuitableSpelling;
3074 if (S.getLangOpts().CPlusPlus20)
3075 SuitableSpelling = std::string(
3076 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3077 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3078 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3079 InsertLoc, {tok::l_square, tok::l_square,
3080 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3081 S.PP.getIdentifierInfo("require_constant_initialization"),
3082 tok::r_square, tok::r_square}));
3083 if (SuitableSpelling.empty())
3084 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3085 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3086 S.PP.getIdentifierInfo("require_constant_initialization"),
3087 tok::r_paren, tok::r_paren}));
3088 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3089 SuitableSpelling = "constinit";
3090 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3091 SuitableSpelling = "[[clang::require_constant_initialization]]";
3092 if (SuitableSpelling.empty())
3093 SuitableSpelling = "__attribute__((require_constant_initialization))";
3094 SuitableSpelling += " ";
3095
3096 if (AttrBeforeInit) {
3097 // extern constinit int a;
3098 // int a = 0; // error (missing 'constinit'), accepted as extension
3099 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")(static_cast <bool> (CIAttr->isConstinit() &&
"should not diagnose this for attribute") ? void (0) : __assert_fail
("CIAttr->isConstinit() && \"should not diagnose this for attribute\""
, "clang/lib/Sema/SemaDecl.cpp", 3099, __extension__ __PRETTY_FUNCTION__
))
;
3100 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3101 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3102 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3103 } else {
3104 // int a = 0;
3105 // constinit extern int a; // error (missing 'constinit')
3106 S.Diag(CIAttr->getLocation(),
3107 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3108 : diag::warn_require_const_init_added_too_late)
3109 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3110 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3111 << CIAttr->isConstinit()
3112 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3113 }
3114}
3115
3116/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3117void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3118 AvailabilityMergeKind AMK) {
3119 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3120 UsedAttr *NewAttr = OldAttr->clone(Context);
3121 NewAttr->setInherited(true);
3122 New->addAttr(NewAttr);
3123 }
3124 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3125 RetainAttr *NewAttr = OldAttr->clone(Context);
3126 NewAttr->setInherited(true);
3127 New->addAttr(NewAttr);
3128 }
3129
3130 if (!Old->hasAttrs() && !New->hasAttrs())
3131 return;
3132
3133 // [dcl.constinit]p1:
3134 // If the [constinit] specifier is applied to any declaration of a
3135 // variable, it shall be applied to the initializing declaration.
3136 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3137 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3138 if (bool(OldConstInit) != bool(NewConstInit)) {
3139 const auto *OldVD = cast<VarDecl>(Old);
3140 auto *NewVD = cast<VarDecl>(New);
3141
3142 // Find the initializing declaration. Note that we might not have linked
3143 // the new declaration into the redeclaration chain yet.
3144 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3145 if (!InitDecl &&
3146 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3147 InitDecl = NewVD;
3148
3149 if (InitDecl == NewVD) {
3150 // This is the initializing declaration. If it would inherit 'constinit',
3151 // that's ill-formed. (Note that we do not apply this to the attribute
3152 // form).
3153 if (OldConstInit && OldConstInit->isConstinit())
3154 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3155 /*AttrBeforeInit=*/true);
3156 } else if (NewConstInit) {
3157 // This is the first time we've been told that this declaration should
3158 // have a constant initializer. If we already saw the initializing
3159 // declaration, this is too late.
3160 if (InitDecl && InitDecl != NewVD) {
3161 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3162 /*AttrBeforeInit=*/false);
3163 NewVD->dropAttr<ConstInitAttr>();
3164 }
3165 }
3166 }
3167
3168 // Attributes declared post-definition are currently ignored.
3169 checkNewAttributesAfterDef(*this, New, Old);
3170
3171 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3172 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3173 if (!OldA->isEquivalent(NewA)) {
3174 // This redeclaration changes __asm__ label.
3175 Diag(New->getLocation(), diag::err_different_asm_label);
3176 Diag(OldA->getLocation(), diag::note_previous_declaration);
3177 }
3178 } else if (Old->isUsed()) {
3179 // This redeclaration adds an __asm__ label to a declaration that has
3180 // already been ODR-used.
3181 Diag(New->getLocation(), diag::err_late_asm_label_name)
3182 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3183 }
3184 }
3185
3186 // Re-declaration cannot add abi_tag's.
3187 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3188 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3189 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3190 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3191 Diag(NewAbiTagAttr->getLocation(),
3192 diag::err_new_abi_tag_on_redeclaration)
3193 << NewTag;
3194 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3195 }
3196 }
3197 } else {
3198 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3199 Diag(Old->getLocation(), diag::note_previous_declaration);
3200 }
3201 }
3202
3203 // This redeclaration adds a section attribute.
3204 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3205 if (auto *VD = dyn_cast<VarDecl>(New)) {
3206 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3207 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3208 Diag(Old->getLocation(), diag::note_previous_declaration);
3209 }
3210 }
3211 }
3212
3213 // Redeclaration adds code-seg attribute.
3214 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3215 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3216 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3217 Diag(New->getLocation(), diag::warn_mismatched_section)
3218 << 0 /*codeseg*/;
3219 Diag(Old->getLocation(), diag::note_previous_declaration);
3220 }
3221
3222 if (!Old->hasAttrs())
3223 return;
3224
3225 bool foundAny = New->hasAttrs();
3226
3227 // Ensure that any moving of objects within the allocated map is done before
3228 // we process them.
3229 if (!foundAny) New->setAttrs(AttrVec());
3230
3231 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3232 // Ignore deprecated/unavailable/availability attributes if requested.
3233 AvailabilityMergeKind LocalAMK = AMK_None;
3234 if (isa<DeprecatedAttr>(I) ||
3235 isa<UnavailableAttr>(I) ||
3236 isa<AvailabilityAttr>(I)) {
3237 switch (AMK) {
3238 case AMK_None:
3239 continue;
3240
3241 case AMK_Redeclaration:
3242 case AMK_Override:
3243 case AMK_ProtocolImplementation:
3244 case AMK_OptionalProtocolImplementation:
3245 LocalAMK = AMK;
3246 break;
3247 }
3248 }
3249
3250 // Already handled.
3251 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3252 continue;
3253
3254 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3255 foundAny = true;
3256 }
3257
3258 if (mergeAlignedAttrs(*this, New, Old))
3259 foundAny = true;
3260
3261 if (!foundAny) New->dropAttrs();
3262}
3263
3264/// mergeParamDeclAttributes - Copy attributes from the old parameter
3265/// to the new one.
3266static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3267 const ParmVarDecl *oldDecl,
3268 Sema &S) {
3269 // C++11 [dcl.attr.depend]p2:
3270 // The first declaration of a function shall specify the
3271 // carries_dependency attribute for its declarator-id if any declaration
3272 // of the function specifies the carries_dependency attribute.
3273 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3274 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3275 S.Diag(CDA->getLocation(),
3276 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3277 // Find the first declaration of the parameter.
3278 // FIXME: Should we build redeclaration chains for function parameters?
3279 const FunctionDecl *FirstFD =
3280 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3281 const ParmVarDecl *FirstVD =
3282 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3283 S.Diag(FirstVD->getLocation(),
3284 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3285 }
3286
3287 if (!oldDecl->hasAttrs())
3288 return;
3289
3290 bool foundAny = newDecl->hasAttrs();
3291
3292 // Ensure that any moving of objects within the allocated map is
3293 // done before we process them.
3294 if (!foundAny) newDecl->setAttrs(AttrVec());
3295
3296 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3297 if (!DeclHasAttr(newDecl, I)) {
3298 InheritableAttr *newAttr =
3299 cast<InheritableParamAttr>(I->clone(S.Context));
3300 newAttr->setInherited(true);
3301 newDecl->addAttr(newAttr);
3302 foundAny = true;
3303 }
3304 }
3305
3306 if (!foundAny) newDecl->dropAttrs();
3307}
3308
3309static bool EquivalentArrayTypes(QualType Old, QualType New,
3310 const ASTContext &Ctx) {
3311
3312 auto NoSizeInfo = [&Ctx](QualType Ty) {
3313 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3314 return true;
3315 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3316 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3317 return false;
3318 };
3319
3320 // `type[]` is equivalent to `type *` and `type[*]`.
3321 if (NoSizeInfo(Old) && NoSizeInfo(New))
3322 return true;
3323
3324 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3325 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3326 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3327 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3328 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3329 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3330 return false;
3331 return true;
3332 }
3333
3334 // Only compare size, ignore Size modifiers and CVR.
3335 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3336 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3337 Ctx.getAsConstantArrayType(New)->getSize();
3338 }
3339
3340 // Don't try to compare dependent sized array
3341 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3342 return true;
3343 }
3344
3345 return Old == New;
3346}
3347
3348static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3349 const ParmVarDecl *OldParam,
3350 Sema &S) {
3351 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3352 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3353 if (*Oldnullability != *Newnullability) {
3354 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3355 << DiagNullabilityKind(
3356 *Newnullability,
3357 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3358 != 0))
3359 << DiagNullabilityKind(
3360 *Oldnullability,
3361 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3362 != 0));
3363 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3364 }
3365 } else {
3366 QualType NewT = NewParam->getType();
3367 NewT = S.Context.getAttributedType(
3368 AttributedType::getNullabilityAttrKind(*Oldnullability),
3369 NewT, NewT);
3370 NewParam->setType(NewT);
3371 }
3372 }
3373 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3374 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3375 if (OldParamDT && NewParamDT &&
3376 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3377 QualType OldParamOT = OldParamDT->getOriginalType();
3378 QualType NewParamOT = NewParamDT->getOriginalType();
3379 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3380 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3381 << NewParam << NewParamOT;
3382 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3383 << OldParamOT;
3384 }
3385 }
3386}
3387
3388namespace {
3389
3390/// Used in MergeFunctionDecl to keep track of function parameters in
3391/// C.
3392struct GNUCompatibleParamWarning {
3393 ParmVarDecl *OldParm;
3394 ParmVarDecl *NewParm;
3395 QualType PromotedType;
3396};
3397
3398} // end anonymous namespace
3399
3400// Determine whether the previous declaration was a definition, implicit
3401// declaration, or a declaration.
3402template <typename T>
3403static std::pair<diag::kind, SourceLocation>
3404getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3405 diag::kind PrevDiag;
3406 SourceLocation OldLocation = Old->getLocation();
3407 if (Old->isThisDeclarationADefinition())
3408 PrevDiag = diag::note_previous_definition;
3409 else if (Old->isImplicit()) {
3410 PrevDiag = diag::note_previous_implicit_declaration;
3411 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3412 if (FD->getBuiltinID())
3413 PrevDiag = diag::note_previous_builtin_declaration;
3414 }
3415 if (OldLocation.isInvalid())
3416 OldLocation = New->getLocation();
3417 } else
3418 PrevDiag = diag::note_previous_declaration;
3419 return std::make_pair(PrevDiag, OldLocation);
3420}
3421
3422/// canRedefineFunction - checks if a function can be redefined. Currently,
3423/// only extern inline functions can be redefined, and even then only in
3424/// GNU89 mode.
3425static bool canRedefineFunction(const FunctionDecl *FD,
3426 const LangOptions& LangOpts) {
3427 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3428 !LangOpts.CPlusPlus &&
3429 FD->isInlineSpecified() &&
3430 FD->getStorageClass() == SC_Extern);
3431}
3432
3433const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3434 const AttributedType *AT = T->getAs<AttributedType>();
3435 while (AT && !AT->isCallingConv())
3436 AT = AT->getModifiedType()->getAs<AttributedType>();
3437 return AT;
3438}
3439
3440template <typename T>
3441static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3442 const DeclContext *DC = Old->getDeclContext();
3443 if (DC->isRecord())
3444 return false;
3445
3446 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3447 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3448 return true;
3449 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3450 return true;
3451 return false;
3452}
3453
3454template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3455static bool isExternC(VarTemplateDecl *) { return false; }
3456static bool isExternC(FunctionTemplateDecl *) { return false; }
3457
3458/// Check whether a redeclaration of an entity introduced by a
3459/// using-declaration is valid, given that we know it's not an overload
3460/// (nor a hidden tag declaration).
3461template<typename ExpectedDecl>
3462static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3463 ExpectedDecl *New) {
3464 // C++11 [basic.scope.declarative]p4:
3465 // Given a set of declarations in a single declarative region, each of
3466 // which specifies the same unqualified name,
3467 // -- they shall all refer to the same entity, or all refer to functions
3468 // and function templates; or
3469 // -- exactly one declaration shall declare a class name or enumeration
3470 // name that is not a typedef name and the other declarations shall all
3471 // refer to the same variable or enumerator, or all refer to functions
3472 // and function templates; in this case the class name or enumeration
3473 // name is hidden (3.3.10).
3474
3475 // C++11 [namespace.udecl]p14:
3476 // If a function declaration in namespace scope or block scope has the
3477 // same name and the same parameter-type-list as a function introduced
3478 // by a using-declaration, and the declarations do not declare the same
3479 // function, the program is ill-formed.
3480
3481 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3482 if (Old &&
3483 !Old->getDeclContext()->getRedeclContext()->Equals(
3484 New->getDeclContext()->getRedeclContext()) &&
3485 !(isExternC(Old) && isExternC(New)))
3486 Old = nullptr;
3487
3488 if (!Old) {
3489 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3490 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3491 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3492 return true;
3493 }
3494 return false;
3495}
3496
3497static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3498 const FunctionDecl *B) {
3499 assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams
()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "clang/lib/Sema/SemaDecl.cpp", 3499, __extension__ __PRETTY_FUNCTION__
))
;
3500
3501 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3502 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3503 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3504 if (AttrA == AttrB)
3505 return true;
3506 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3507 AttrA->isDynamic() == AttrB->isDynamic();
3508 };
3509
3510 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3511}
3512
3513/// If necessary, adjust the semantic declaration context for a qualified
3514/// declaration to name the correct inline namespace within the qualifier.
3515static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3516 DeclaratorDecl *OldD) {
3517 // The only case where we need to update the DeclContext is when
3518 // redeclaration lookup for a qualified name finds a declaration
3519 // in an inline namespace within the context named by the qualifier:
3520 //
3521 // inline namespace N { int f(); }
3522 // int ::f(); // Sema DC needs adjusting from :: to N::.
3523 //
3524 // For unqualified declarations, the semantic context *can* change
3525 // along the redeclaration chain (for local extern declarations,
3526 // extern "C" declarations, and friend declarations in particular).
3527 if (!NewD->getQualifier())
3528 return;
3529
3530 // NewD is probably already in the right context.
3531 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3532 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3533 if (NamedDC->Equals(SemaDC))
3534 return;
3535
3536 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "clang/lib/Sema/SemaDecl.cpp", 3538, __extension__ __PRETTY_FUNCTION__
))
3537 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "clang/lib/Sema/SemaDecl.cpp", 3538, __extension__ __PRETTY_FUNCTION__
))
3538 "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "clang/lib/Sema/SemaDecl.cpp", 3538, __extension__ __PRETTY_FUNCTION__
))
;
3539
3540 auto *LexDC = NewD->getLexicalDeclContext();
3541 auto FixSemaDC = [=](NamedDecl *D) {
3542 if (!D)
3543 return;
3544 D->setDeclContext(SemaDC);
3545 D->setLexicalDeclContext(LexDC);
3546 };
3547
3548 FixSemaDC(NewD);
3549 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3550 FixSemaDC(FD->getDescribedFunctionTemplate());
3551 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3552 FixSemaDC(VD->getDescribedVarTemplate());
3553}
3554
3555/// MergeFunctionDecl - We just parsed a function 'New' from
3556/// declarator D which has the same name and scope as a previous
3557/// declaration 'Old'. Figure out how to resolve this situation,
3558/// merging decls or emitting diagnostics as appropriate.
3559///
3560/// In C++, New and Old must be declarations that are not
3561/// overloaded. Use IsOverload to determine whether New and Old are
3562/// overloaded, and to select the Old declaration that New should be
3563/// merged with.
3564///
3565/// Returns true if there was an error, false otherwise.
3566bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3567 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3568 // Verify the old decl was also a function.
3569 FunctionDecl *Old = OldD->getAsFunction();
3570 if (!Old) {
3571 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3572 if (New->getFriendObjectKind()) {
3573 Diag(New->getLocation(), diag::err_using_decl_friend);
3574 Diag(Shadow->getTargetDecl()->getLocation(),
3575 diag::note_using_decl_target);
3576 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3577 << 0;
3578 return true;
3579 }
3580
3581 // Check whether the two declarations might declare the same function or
3582 // function template.
3583 if (FunctionTemplateDecl *NewTemplate =
3584 New->getDescribedFunctionTemplate()) {
3585 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3586 NewTemplate))
3587 return true;
3588 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3589 ->getAsFunction();
3590 } else {
3591 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3592 return true;
3593 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3594 }
3595 } else {
3596 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3597 << New->getDeclName();
3598 notePreviousDefinition(OldD, New->getLocation());
3599 return true;
3600 }
3601 }
3602
3603 // If the old declaration was found in an inline namespace and the new
3604 // declaration was qualified, update the DeclContext to match.
3605 adjustDeclContextForDeclaratorDecl(New, Old);
3606
3607 // If the old declaration is invalid, just give up here.
3608 if (Old->isInvalidDecl())
3609 return true;
3610
3611 // Disallow redeclaration of some builtins.
3612 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3613 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3614 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3615 << Old << Old->getType();
3616 return true;
3617 }
3618
3619 diag::kind PrevDiag;
3620 SourceLocation OldLocation;
3621 std::tie(PrevDiag, OldLocation) =
3622 getNoteDiagForInvalidRedeclaration(Old, New);
3623
3624 // Don't complain about this if we're in GNU89 mode and the old function
3625 // is an extern inline function.
3626 // Don't complain about specializations. They are not supposed to have
3627 // storage classes.
3628 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3629 New->getStorageClass() == SC_Static &&
3630 Old->hasExternalFormalLinkage() &&
3631 !New->getTemplateSpecializationInfo() &&
3632 !canRedefineFunction(Old, getLangOpts())) {
3633 if (getLangOpts().MicrosoftExt) {
3634 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3635 Diag(OldLocation, PrevDiag);
3636 } else {
3637 Diag(New->getLocation(), diag::err_static_non_static) << New;
3638 Diag(OldLocation, PrevDiag);
3639 return true;
3640 }
3641 }
3642
3643 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3644 if (!Old->hasAttr<InternalLinkageAttr>()) {
3645 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3646 << ILA;
3647 Diag(Old->getLocation(), diag::note_previous_declaration);
3648 New->dropAttr<InternalLinkageAttr>();
3649 }
3650
3651 if (auto *EA = New->getAttr<ErrorAttr>()) {
3652 if (!Old->hasAttr<ErrorAttr>()) {
3653 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3654 Diag(Old->getLocation(), diag::note_previous_declaration);
3655 New->dropAttr<ErrorAttr>();
3656 }
3657 }
3658
3659 if (CheckRedeclarationInModule(New, Old))
3660 return true;
3661
3662 if (!getLangOpts().CPlusPlus) {
3663 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3664 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3665 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3666 << New << OldOvl;
3667
3668 // Try our best to find a decl that actually has the overloadable
3669 // attribute for the note. In most cases (e.g. programs with only one
3670 // broken declaration/definition), this won't matter.
3671 //
3672 // FIXME: We could do this if we juggled some extra state in
3673 // OverloadableAttr, rather than just removing it.
3674 const Decl *DiagOld = Old;
3675 if (OldOvl) {
3676 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3677 const auto *A = D->getAttr<OverloadableAttr>();
3678 return A && !A->isImplicit();
3679 });
3680 // If we've implicitly added *all* of the overloadable attrs to this
3681 // chain, emitting a "previous redecl" note is pointless.
3682 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3683 }
3684
3685 if (DiagOld)
3686 Diag(DiagOld->getLocation(),
3687 diag::note_attribute_overloadable_prev_overload)
3688 << OldOvl;
3689
3690 if (OldOvl)
3691 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3692 else
3693 New->dropAttr<OverloadableAttr>();
3694 }
3695 }
3696
3697 // If a function is first declared with a calling convention, but is later
3698 // declared or defined without one, all following decls assume the calling
3699 // convention of the first.
3700 //
3701 // It's OK if a function is first declared without a calling convention,
3702 // but is later declared or defined with the default calling convention.
3703 //
3704 // To test if either decl has an explicit calling convention, we look for
3705 // AttributedType sugar nodes on the type as written. If they are missing or
3706 // were canonicalized away, we assume the calling convention was implicit.
3707 //
3708 // Note also that we DO NOT return at this point, because we still have
3709 // other tests to run.
3710 QualType OldQType = Context.getCanonicalType(Old->getType());
3711 QualType NewQType = Context.getCanonicalType(New->getType());
3712 const FunctionType *OldType = cast<FunctionType>(OldQType);
3713 const FunctionType *NewType = cast<FunctionType>(NewQType);
3714 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3715 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3716 bool RequiresAdjustment = false;
3717
3718 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3719 FunctionDecl *First = Old->getFirstDecl();
3720 const FunctionType *FT =
3721 First->getType().getCanonicalType()->castAs<FunctionType>();
3722 FunctionType::ExtInfo FI = FT->getExtInfo();
3723 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3724 if (!NewCCExplicit) {
3725 // Inherit the CC from the previous declaration if it was specified
3726 // there but not here.
3727 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3728 RequiresAdjustment = true;
3729 } else if (Old->getBuiltinID()) {
3730 // Builtin attribute isn't propagated to the new one yet at this point,
3731 // so we check if the old one is a builtin.
3732
3733 // Calling Conventions on a Builtin aren't really useful and setting a
3734 // default calling convention and cdecl'ing some builtin redeclarations is
3735 // common, so warn and ignore the calling convention on the redeclaration.
3736 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3737 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3738 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3739 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3740 RequiresAdjustment = true;
3741 } else {
3742 // Calling conventions aren't compatible, so complain.
3743 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3744 Diag(New->getLocation(), diag::err_cconv_change)
3745 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3746 << !FirstCCExplicit
3747 << (!FirstCCExplicit ? "" :
3748 FunctionType::getNameForCallConv(FI.getCC()));
3749
3750 // Put the note on the first decl, since it is the one that matters.
3751 Diag(First->getLocation(), diag::note_previous_declaration);
3752 return true;
3753 }
3754 }
3755
3756 // FIXME: diagnose the other way around?
3757 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3758 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3759 RequiresAdjustment = true;
3760 }
3761
3762 // Merge regparm attribute.
3763 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3764 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3765 if (NewTypeInfo.getHasRegParm()) {
3766 Diag(New->getLocation(), diag::err_regparm_mismatch)
3767 << NewType->getRegParmType()
3768 << OldType->getRegParmType();
3769 Diag(OldLocation, diag::note_previous_declaration);
3770 return true;
3771 }
3772
3773 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3774 RequiresAdjustment = true;
3775 }
3776
3777 // Merge ns_returns_retained attribute.
3778 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3779 if (NewTypeInfo.getProducesResult()) {
3780 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3781 << "'ns_returns_retained'";
3782 Diag(OldLocation, diag::note_previous_declaration);
3783 return true;
3784 }
3785
3786 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3787 RequiresAdjustment = true;
3788 }
3789
3790 if (OldTypeInfo.getNoCallerSavedRegs() !=
3791 NewTypeInfo.getNoCallerSavedRegs()) {
3792 if (NewTypeInfo.getNoCallerSavedRegs()) {
3793 AnyX86NoCallerSavedRegistersAttr *Attr =
3794 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3795 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3796 Diag(OldLocation, diag::note_previous_declaration);
3797 return true;
3798 }
3799
3800 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3801 RequiresAdjustment = true;
3802 }
3803
3804 if (RequiresAdjustment) {
3805 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3806 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3807 New->setType(QualType(AdjustedType, 0));
3808 NewQType = Context.getCanonicalType(New->getType());
3809 }
3810
3811 // If this redeclaration makes the function inline, we may need to add it to
3812 // UndefinedButUsed.
3813 if (!Old->isInlined() && New->isInlined() &&
3814 !New->hasAttr<GNUInlineAttr>() &&
3815 !getLangOpts().GNUInline &&
3816 Old->isUsed(false) &&
3817 !Old->isDefined() && !New->isThisDeclarationADefinition())
3818 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3819 SourceLocation()));
3820
3821 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3822 // about it.
3823 if (New->hasAttr<GNUInlineAttr>() &&
3824 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3825 UndefinedButUsed.erase(Old->getCanonicalDecl());
3826 }
3827
3828 // If pass_object_size params don't match up perfectly, this isn't a valid
3829 // redeclaration.
3830 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3831 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3832 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3833 << New->getDeclName();
3834 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3835 return true;
3836 }
3837
3838 if (getLangOpts().CPlusPlus) {
3839 // C++1z [over.load]p2
3840 // Certain function declarations cannot be overloaded:
3841 // -- Function declarations that differ only in the return type,
3842 // the exception specification, or both cannot be overloaded.
3843
3844 // Check the exception specifications match. This may recompute the type of
3845 // both Old and New if it resolved exception specifications, so grab the
3846 // types again after this. Because this updates the type, we do this before
3847 // any of the other checks below, which may update the "de facto" NewQType
3848 // but do not necessarily update the type of New.
3849 if (CheckEquivalentExceptionSpec(Old, New))
3850 return true;
3851 OldQType = Context.getCanonicalType(Old->getType());
3852 NewQType = Context.getCanonicalType(New->getType());
3853
3854 // Go back to the type source info to compare the declared return types,
3855 // per C++1y [dcl.type.auto]p13:
3856 // Redeclarations or specializations of a function or function template
3857 // with a declared return type that uses a placeholder type shall also
3858 // use that placeholder, not a deduced type.
3859 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3860 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3861 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3862 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3863 OldDeclaredReturnType)) {
3864 QualType ResQT;
3865 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3866 OldDeclaredReturnType->isObjCObjectPointerType())
3867 // FIXME: This does the wrong thing for a deduced return type.
3868 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3869 if (ResQT.isNull()) {
3870 if (New->isCXXClassMember() && New->isOutOfLine())
3871 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3872 << New << New->getReturnTypeSourceRange();
3873 else
3874 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3875 << New->getReturnTypeSourceRange();
3876 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3877 << Old->getReturnTypeSourceRange();
3878 return true;
3879 }
3880 else
3881 NewQType = ResQT;
3882 }
3883
3884 QualType OldReturnType = OldType->getReturnType();
3885 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3886 if (OldReturnType != NewReturnType) {
3887 // If this function has a deduced return type and has already been
3888 // defined, copy the deduced value from the old declaration.
3889 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3890 if (OldAT && OldAT->isDeduced()) {
3891 QualType DT = OldAT->getDeducedType();
3892 if (DT.isNull()) {
3893 New->setType(SubstAutoTypeDependent(New->getType()));
3894 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3895 } else {
3896 New->setType(SubstAutoType(New->getType(), DT));
3897 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3898 }
3899 }
3900 }
3901
3902 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3903 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3904 if (OldMethod && NewMethod) {
3905 // Preserve triviality.
3906 NewMethod->setTrivial(OldMethod->isTrivial());
3907
3908 // MSVC allows explicit template specialization at class scope:
3909 // 2 CXXMethodDecls referring to the same function will be injected.
3910 // We don't want a redeclaration error.
3911 bool IsClassScopeExplicitSpecialization =
3912 OldMethod->isFunctionTemplateSpecialization() &&
3913 NewMethod->isFunctionTemplateSpecialization();
3914 bool isFriend = NewMethod->getFriendObjectKind();
3915
3916 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3917 !IsClassScopeExplicitSpecialization) {
3918 // -- Member function declarations with the same name and the
3919 // same parameter types cannot be overloaded if any of them
3920 // is a static member function declaration.
3921 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3922 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3923 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3924 return true;
3925 }
3926
3927 // C++ [class.mem]p1:
3928 // [...] A member shall not be declared twice in the
3929 // member-specification, except that a nested class or member
3930 // class template can be declared and then later defined.
3931 if (!inTemplateInstantiation()) {
3932 unsigned NewDiag;
3933 if (isa<CXXConstructorDecl>(OldMethod))
3934 NewDiag = diag::err_constructor_redeclared;
3935 else if (isa<CXXDestructorDecl>(NewMethod))
3936 NewDiag = diag::err_destructor_redeclared;
3937 else if (isa<CXXConversionDecl>(NewMethod))
3938 NewDiag = diag::err_conv_function_redeclared;
3939 else
3940 NewDiag = diag::err_member_redeclared;
3941
3942 Diag(New->getLocation(), NewDiag);
3943 } else {
3944 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3945 << New << New->getType();
3946 }
3947 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3948 return true;
3949
3950 // Complain if this is an explicit declaration of a special
3951 // member that was initially declared implicitly.
3952 //
3953 // As an exception, it's okay to befriend such methods in order
3954 // to permit the implicit constructor/destructor/operator calls.
3955 } else if (OldMethod->isImplicit()) {
3956 if (isFriend) {
3957 NewMethod->setImplicit();
3958 } else {
3959 Diag(NewMethod->getLocation(),
3960 diag::err_definition_of_implicitly_declared_member)
3961 << New << getSpecialMember(OldMethod);
3962 return true;
3963 }
3964 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3965 Diag(NewMethod->getLocation(),
3966 diag::err_definition_of_explicitly_defaulted_member)
3967 << getSpecialMember(OldMethod);
3968 return true;
3969 }
3970 }
3971
3972 // C++11 [dcl.attr.noreturn]p1:
3973 // The first declaration of a function shall specify the noreturn
3974 // attribute if any declaration of that function specifies the noreturn
3975 // attribute.
3976 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3977 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3978 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3979 << NRA;
3980 Diag(Old->getLocation(), diag::note_previous_declaration);
3981 }
3982
3983 // C++11 [dcl.attr.depend]p2:
3984 // The first declaration of a function shall specify the
3985 // carries_dependency attribute for its declarator-id if any declaration
3986 // of the function specifies the carries_dependency attribute.
3987 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3988 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3989 Diag(CDA->getLocation(),
3990 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3991 Diag(Old->getFirstDecl()->getLocation(),
3992 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3993 }
3994
3995 // (C++98 8.3.5p3):
3996 // All declarations for a function shall agree exactly in both the
3997 // return type and the parameter-type-list.
3998 // We also want to respect all the extended bits except noreturn.
3999
4000 // noreturn should now match unless the old type info didn't have it.
4001 QualType OldQTypeForComparison = OldQType;
4002 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4003 auto *OldType = OldQType->castAs<FunctionProtoType>();
4004 const FunctionType *OldTypeForComparison
4005 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4006 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4007 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "clang/lib/Sema/SemaDecl.cpp", 4007, __extension__ __PRETTY_FUNCTION__
))
;
4008 }
4009
4010 if (haveIncompatibleLanguageLinkages(Old, New)) {
4011 // As a special case, retain the language linkage from previous
4012 // declarations of a friend function as an extension.
4013 //
4014 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4015 // and is useful because there's otherwise no way to specify language
4016 // linkage within class scope.
4017 //
4018 // Check cautiously as the friend object kind isn't yet complete.
4019 if (New->getFriendObjectKind() != Decl::FOK_None) {
4020 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4021 Diag(OldLocation, PrevDiag);
4022 } else {
4023 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4024 Diag(OldLocation, PrevDiag);
4025 return true;
4026 }
4027 }
4028
4029 // If the function types are compatible, merge the declarations. Ignore the
4030 // exception specifier because it was already checked above in
4031 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4032 // about incompatible types under -fms-compatibility.
4033 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4034 NewQType))
4035 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4036
4037 // If the types are imprecise (due to dependent constructs in friends or
4038 // local extern declarations), it's OK if they differ. We'll check again
4039 // during instantiation.
4040 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4041 return false;
4042
4043 // Fall through for conflicting redeclarations and redefinitions.
4044 }
4045
4046 // C: Function types need to be compatible, not identical. This handles
4047 // duplicate function decls like "void f(int); void f(enum X);" properly.
4048 if (!getLangOpts().CPlusPlus) {
4049 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4050 // type is specified by a function definition that contains a (possibly
4051 // empty) identifier list, both shall agree in the number of parameters
4052 // and the type of each parameter shall be compatible with the type that
4053 // results from the application of default argument promotions to the
4054 // type of the corresponding identifier. ...
4055 // This cannot be handled by ASTContext::typesAreCompatible() because that
4056 // doesn't know whether the function type is for a definition or not when
4057 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4058 // we need to cover here is that the number of arguments agree as the
4059 // default argument promotion rules were already checked by
4060 // ASTContext::typesAreCompatible().
4061 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4062 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4063 if (Old->hasInheritedPrototype())
4064 Old = Old->getCanonicalDecl();
4065 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4066 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4067 return true;
4068 }
4069
4070 // If we are merging two functions where only one of them has a prototype,
4071 // we may have enough information to decide to issue a diagnostic that the
4072 // function without a protoype will change behavior in C2x. This handles
4073 // cases like:
4074 // void i(); void i(int j);
4075 // void i(int j); void i();
4076 // void i(); void i(int j) {}
4077 // See ActOnFinishFunctionBody() for other cases of the behavior change
4078 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4079 // type without a prototype.
4080 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4081 !New->isImplicit() && !Old->isImplicit()) {
4082 const FunctionDecl *WithProto, *WithoutProto;
4083 if (New->hasWrittenPrototype()) {
4084 WithProto = New;
4085 WithoutProto = Old;
4086 } else {
4087 WithProto = Old;
4088 WithoutProto = New;
4089 }
4090
4091 if (WithProto->getNumParams() != 0) {
4092 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4093 // The one without the prototype will be changing behavior in C2x, so
4094 // warn about that one so long as it's a user-visible declaration.
4095 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4096 if (WithoutProto == New)
4097 IsWithoutProtoADef = NewDeclIsDefn;
4098 else
4099 IsWithProtoADef = NewDeclIsDefn;
4100 Diag(WithoutProto->getLocation(),
4101 diag::warn_non_prototype_changes_behavior)
4102 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4103 << (WithoutProto == Old) << IsWithProtoADef;
4104
4105 // The reason the one without the prototype will be changing behavior
4106 // is because of the one with the prototype, so note that so long as
4107 // it's a user-visible declaration. There is one exception to this:
4108 // when the new declaration is a definition without a prototype, the
4109 // old declaration with a prototype is not the cause of the issue,
4110 // and that does not need to be noted because the one with a
4111 // prototype will not change behavior in C2x.
4112 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4113 !IsWithoutProtoADef)
4114 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4115 }
4116 }
4117 }
4118
4119 if (Context.typesAreCompatible(OldQType, NewQType)) {
4120 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4121 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4122 const FunctionProtoType *OldProto = nullptr;
4123 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4124 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4125 // The old declaration provided a function prototype, but the
4126 // new declaration does not. Merge in the prototype.
4127 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() &&
"Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "clang/lib/Sema/SemaDecl.cpp", 4127, __extension__ __PRETTY_FUNCTION__
))
;
4128 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4129 OldProto->getParamTypes(),
4130 OldProto->getExtProtoInfo());
4131 New->setType(NewQType);
4132 New->setHasInheritedPrototype();
4133
4134 // Synthesize parameters with the same types.
4135 SmallVector<ParmVarDecl *, 16> Params;
4136 for (const auto &ParamType : OldProto->param_types()) {
4137 ParmVarDecl *Param = ParmVarDecl::Create(
4138 Context, New, SourceLocation(), SourceLocation(), nullptr,
4139 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4140 Param->setScopeInfo(0, Params.size());
4141 Param->setImplicit();
4142 Params.push_back(Param);
4143 }
4144
4145 New->setParams(Params);
4146 }
4147
4148 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4149 }
4150 }
4151
4152 // Check if the function types are compatible when pointer size address
4153 // spaces are ignored.
4154 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4155 return false;
4156
4157 // GNU C permits a K&R definition to follow a prototype declaration
4158 // if the declared types of the parameters in the K&R definition
4159 // match the types in the prototype declaration, even when the
4160 // promoted types of the parameters from the K&R definition differ
4161 // from the types in the prototype. GCC then keeps the types from
4162 // the prototype.
4163 //
4164 // If a variadic prototype is followed by a non-variadic K&R definition,
4165 // the K&R definition becomes variadic. This is sort of an edge case, but
4166 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4167 // C99 6.9.1p8.
4168 if (!getLangOpts().CPlusPlus &&
4169 Old->hasPrototype() && !New->hasPrototype() &&
4170 New->getType()->getAs<FunctionProtoType>() &&
4171 Old->getNumParams() == New->getNumParams()) {
4172 SmallVector<QualType, 16> ArgTypes;
4173 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4174 const FunctionProtoType *OldProto
4175 = Old->getType()->getAs<FunctionProtoType>();
4176 const FunctionProtoType *NewProto
4177 = New->getType()->getAs<FunctionProtoType>();
4178
4179 // Determine whether this is the GNU C extension.
4180 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4181 NewProto->getReturnType());
4182 bool LooseCompatible = !MergedReturn.isNull();
4183 for (unsigned Idx = 0, End = Old->getNumParams();
4184 LooseCompatible && Idx != End; ++Idx) {
4185 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4186 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4187 if (Context.typesAreCompatible(OldParm->getType(),
4188 NewProto->getParamType(Idx))) {
4189 ArgTypes.push_back(NewParm->getType());
4190 } else if (Context.typesAreCompatible(OldParm->getType(),
4191 NewParm->getType(),
4192 /*CompareUnqualified=*/true)) {
4193 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4194 NewProto->getParamType(Idx) };
4195 Warnings.push_back(Warn);
4196 ArgTypes.push_back(NewParm->getType());
4197 } else
4198 LooseCompatible = false;
4199 }
4200
4201 if (LooseCompatible) {
4202 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4203 Diag(Warnings[Warn].NewParm->getLocation(),
4204 diag::ext_param_promoted_not_compatible_with_prototype)
4205 << Warnings[Warn].PromotedType
4206 << Warnings[Warn].OldParm->getType();
4207 if (Warnings[Warn].OldParm->getLocation().isValid())
4208 Diag(Warnings[Warn].OldParm->getLocation(),
4209 diag::note_previous_declaration);
4210 }
4211
4212 if (MergeTypeWithOld)
4213 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4214 OldProto->getExtProtoInfo()));
4215 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4216 }
4217
4218 // Fall through to diagnose conflicting types.
4219 }
4220
4221 // A function that has already been declared has been redeclared or
4222 // defined with a different type; show an appropriate diagnostic.
4223
4224 // If the previous declaration was an implicitly-generated builtin
4225 // declaration, then at the very least we should use a specialized note.
4226 unsigned BuiltinID;
4227 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4228 // If it's actually a library-defined builtin function like 'malloc'
4229 // or 'printf', just warn about the incompatible redeclaration.
4230 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4231 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4232 Diag(OldLocation, diag::note_previous_builtin_declaration)
4233 << Old << Old->getType();
4234 return false;
4235 }
4236
4237 PrevDiag = diag::note_previous_builtin_declaration;
4238 }
4239
4240 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4241 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4242 return true;
4243}
4244
4245/// Completes the merge of two function declarations that are
4246/// known to be compatible.
4247///
4248/// This routine handles the merging of attributes and other
4249/// properties of function declarations from the old declaration to
4250/// the new declaration, once we know that New is in fact a
4251/// redeclaration of Old.
4252///
4253/// \returns false
4254bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4255 Scope *S, bool MergeTypeWithOld) {
4256 // Merge the attributes
4257 mergeDeclAttributes(New, Old);
4258
4259 // Merge "pure" flag.
4260 if (Old->isPure())
4261 New->setPure();
4262
4263 // Merge "used" flag.
4264 if (Old->getMostRecentDecl()->isUsed(false))
4265 New->setIsUsed();
4266
4267 // Merge attributes from the parameters. These can mismatch with K&R
4268 // declarations.
4269 if (New->getNumParams() == Old->getNumParams())
4270 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4271 ParmVarDecl *NewParam = New->getParamDecl(i);
4272 ParmVarDecl *OldParam = Old->getParamDecl(i);
4273 mergeParamDeclAttributes(NewParam, OldParam, *this);
4274 mergeParamDeclTypes(NewParam, OldParam, *this);
4275 }
4276
4277 if (getLangOpts().CPlusPlus)
4278 return MergeCXXFunctionDecl(New, Old, S);
4279
4280 // Merge the function types so the we get the composite types for the return
4281 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4282 // was visible.
4283 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4284 if (!Merged.isNull() && MergeTypeWithOld)
4285 New->setType(Merged);
4286
4287 return false;
4288}
4289
4290void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4291 ObjCMethodDecl *oldMethod) {
4292 // Merge the attributes, including deprecated/unavailable
4293 AvailabilityMergeKind MergeKind =
4294 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4295 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4296 : AMK_ProtocolImplementation)
4297 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4298 : AMK_Override;
4299
4300 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4301
4302 // Merge attributes from the parameters.
4303 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4304 oe = oldMethod->param_end();
4305 for (ObjCMethodDecl::param_iterator
4306 ni = newMethod->param_begin(), ne = newMethod->param_end();
4307 ni != ne && oi != oe; ++ni, ++oi)
4308 mergeParamDeclAttributes(*ni, *oi, *this);
4309
4310 CheckObjCMethodOverride(newMethod, oldMethod);
4311}
4312
4313static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4314 assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType
(), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "clang/lib/Sema/SemaDecl.cpp", 4314, __extension__ __PRETTY_FUNCTION__
))
;
4315
4316 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4317 ? diag::err_redefinition_different_type
4318 : diag::err_redeclaration_different_type)
4319 << New->getDeclName() << New->getType() << Old->getType();
4320
4321 diag::kind PrevDiag;
4322 SourceLocation OldLocation;
4323 std::tie(PrevDiag, OldLocation)
4324 = getNoteDiagForInvalidRedeclaration(Old, New);
4325 S.Diag(OldLocation, PrevDiag);
4326 New->setInvalidDecl();
4327}
4328
4329/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4330/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4331/// emitting diagnostics as appropriate.
4332///
4333/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4334/// to here in AddInitializerToDecl. We can't check them before the initializer
4335/// is attached.
4336void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4337 bool MergeTypeWithOld) {
4338 if (New->isInvalidDecl() || Old->isInvalidDecl())
4339 return;
4340
4341 QualType MergedT;
4342 if (getLangOpts().CPlusPlus) {
4343 if (New->getType()->isUndeducedType()) {
4344 // We don't know what the new type is until the initializer is attached.
4345 return;
4346 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4347 // These could still be something that needs exception specs checked.
4348 return MergeVarDeclExceptionSpecs(New, Old);
4349 }
4350 // C++ [basic.link]p10:
4351 // [...] the types specified by all declarations referring to a given
4352 // object or function shall be identical, except that declarations for an
4353 // array object can specify array types that differ by the presence or
4354 // absence of a major array bound (8.3.4).
4355 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4356 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4357 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4358
4359 // We are merging a variable declaration New into Old. If it has an array
4360 // bound, and that bound differs from Old's bound, we should diagnose the
4361 // mismatch.
4362 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4363 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4364 PrevVD = PrevVD->getPreviousDecl()) {
4365 QualType PrevVDTy = PrevVD->getType();
4366 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4367 continue;
4368
4369 if (!Context.hasSameType(New->getType(), PrevVDTy))
4370 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4371 }
4372 }
4373
4374 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4375 if (Context.hasSameType(OldArray->getElementType(),
4376 NewArray->getElementType()))
4377 MergedT = New->getType();
4378 }
4379 // FIXME: Check visibility. New is hidden but has a complete type. If New
4380 // has no array bound, it should not inherit one from Old, if Old is not
4381 // visible.
4382 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4383 if (Context.hasSameType(OldArray->getElementType(),
4384 NewArray->getElementType()))
4385 MergedT = Old->getType();
4386 }
4387 }
4388 else if (New->getType()->isObjCObjectPointerType() &&
4389 Old->getType()->isObjCObjectPointerType()) {
4390 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4391 Old->getType());
4392 }
4393 } else {
4394 // C 6.2.7p2:
4395 // All declarations that refer to the same object or function shall have
4396 // compatible type.
4397 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4398 }
4399 if (MergedT.isNull()) {
4400 // It's OK if we couldn't merge types if either type is dependent, for a
4401 // block-scope variable. In other cases (static data members of class
4402 // templates, variable templates, ...), we require the types to be
4403 // equivalent.
4404 // FIXME: The C++ standard doesn't say anything about this.
4405 if ((New->getType()->isDependentType() ||
4406 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4407 // If the old type was dependent, we can't merge with it, so the new type
4408 // becomes dependent for now. We'll reproduce the original type when we
4409 // instantiate the TypeSourceInfo for the variable.
4410 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4411 New->setType(Context.DependentTy);
4412 return;
4413 }
4414 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4415 }
4416
4417 // Don't actually update the type on the new declaration if the old
4418 // declaration was an extern declaration in a different scope.
4419 if (MergeTypeWithOld)
4420 New->setType(MergedT);
4421}
4422
4423static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4424 LookupResult &Previous) {
4425 // C11 6.2.7p4:
4426 // For an identifier with internal or external linkage declared
4427 // in a scope in which a prior declaration of that identifier is
4428 // visible, if the prior declaration specifies internal or
4429 // external linkage, the type of the identifier at the later
4430 // declaration becomes the composite type.
4431 //
4432 // If the variable isn't visible, we do not merge with its type.
4433 if (Previous.isShadowed())
4434 return false;
4435
4436 if (S.getLangOpts().CPlusPlus) {
4437 // C++11 [dcl.array]p3:
4438 // If there is a preceding declaration of the entity in the same
4439 // scope in which the bound was specified, an omitted array bound
4440 // is taken to be the same as in that earlier declaration.
4441 return NewVD->isPreviousDeclInSameBlockScope() ||
4442 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4443 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4444 } else {
4445 // If the old declaration was function-local, don't merge with its
4446 // type unless we're in the same function.
4447 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4448 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4449 }
4450}
4451
4452/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4453/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4454/// situation, merging decls or emitting diagnostics as appropriate.
4455///
4456/// Tentative definition rules (C99 6.9.2p2) are checked by
4457/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4458/// definitions here, since the initializer hasn't been attached.
4459///
4460void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4461 // If the new decl is already invalid, don't do any other checking.
4462 if (New->isInvalidDecl())
4463 return;
4464
4465 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4466 return;
4467
4468 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4469
4470 // Verify the old decl was also a variable or variable template.
4471 VarDecl *Old = nullptr;
4472 VarTemplateDecl *OldTemplate = nullptr;
4473 if (Previous.isSingleResult()) {
4474 if (NewTemplate) {
4475 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4476 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4477
4478 if (auto *Shadow =
4479 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4480 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4481 return New->setInvalidDecl();
4482 } else {
4483 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4484
4485 if (auto *Shadow =
4486 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4487 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4488 return New->setInvalidDecl();
4489 }
4490 }
4491 if (!Old) {
4492 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4493 << New->getDeclName();
4494 notePreviousDefinition(Previous.getRepresentativeDecl(),
4495 New->getLocation());
4496 return New->setInvalidDecl();
4497 }
4498
4499 // If the old declaration was found in an inline namespace and the new
4500 // declaration was qualified, update the DeclContext to match.
4501 adjustDeclContextForDeclaratorDecl(New, Old);
4502
4503 // Ensure the template parameters are compatible.
4504 if (NewTemplate &&
4505 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4506 OldTemplate->getTemplateParameters(),
4507 /*Complain=*/true, TPL_TemplateMatch))
4508 return New->setInvalidDecl();
4509
4510 // C++ [class.mem]p1:
4511 // A member shall not be declared twice in the member-specification [...]
4512 //
4513 // Here, we need only consider static data members.
4514 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4515 Diag(New->getLocation(), diag::err_duplicate_member)
4516 << New->getIdentifier();
4517 Diag(Old->getLocation(), diag::note_previous_declaration);
4518 New->setInvalidDecl();
4519 }
4520
4521 mergeDeclAttributes(New, Old);
4522 // Warn if an already-declared variable is made a weak_import in a subsequent
4523 // declaration
4524 if (New->hasAttr<WeakImportAttr>() &&
4525 Old->getStorageClass() == SC_None &&
4526 !Old->hasAttr<WeakImportAttr>()) {
4527 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4528 Diag(Old->getLocation(), diag::note_previous_declaration);
4529 // Remove weak_import attribute on new declaration.
4530 New->dropAttr<WeakImportAttr>();
4531 }
4532
4533 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4534 if (!Old->hasAttr<InternalLinkageAttr>()) {
4535 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4536 << ILA;
4537 Diag(Old->getLocation(), diag::note_previous_declaration);
4538 New->dropAttr<InternalLinkageAttr>();
4539 }
4540
4541 // Merge the types.
4542 VarDecl *MostRecent = Old->getMostRecentDecl();
4543 if (MostRecent != Old) {
4544 MergeVarDeclTypes(New, MostRecent,
4545 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4546 if (New->isInvalidDecl())
4547 return;
4548 }
4549
4550 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4551 if (New->isInvalidDecl())
4552 return;
4553
4554 diag::kind PrevDiag;
4555 SourceLocation OldLocation;
4556 std::tie(PrevDiag, OldLocation) =
4557 getNoteDiagForInvalidRedeclaration(Old, New);
4558
4559 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4560 if (New->getStorageClass() == SC_Static &&
4561 !New->isStaticDataMember() &&
4562 Old->hasExternalFormalLinkage()) {
4563 if (getLangOpts().MicrosoftExt) {
4564 Diag(New->getLocation(), diag::ext_static_non_static)
4565 << New->getDeclName();
4566 Diag(OldLocation, PrevDiag);
4567 } else {
4568 Diag(New->getLocation(), diag::err_static_non_static)
4569 << New->getDeclName();
4570 Diag(OldLocation, PrevDiag);
4571 return New->setInvalidDecl();
4572 }
4573 }
4574 // C99 6.2.2p4:
4575 // For an identifier declared with the storage-class specifier
4576 // extern in a scope in which a prior declaration of that
4577 // identifier is visible,23) if the prior declaration specifies
4578 // internal or external linkage, the linkage of the identifier at
4579 // the later declaration is the same as the linkage specified at
4580 // the prior declaration. If no prior declaration is visible, or
4581 // if the prior declaration specifies no linkage, then the
4582 // identifier has external linkage.
4583 if (New->hasExternalStorage() && Old->hasLinkage())
4584 /* Okay */;
4585 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4586 !New->isStaticDataMember() &&
4587 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4588 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4589 Diag(OldLocation, PrevDiag);
4590 return New->setInvalidDecl();
4591 }
4592
4593 // Check if extern is followed by non-extern and vice-versa.
4594 if (New->hasExternalStorage() &&
4595 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4596 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4597 Diag(OldLocation, PrevDiag);
4598 return New->setInvalidDecl();
4599 }
4600 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4601 !New->hasExternalStorage()) {
4602 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4603 Diag(OldLocation, PrevDiag);
4604 return New->setInvalidDecl();
4605 }
4606
4607 if (CheckRedeclarationInModule(New, Old))
4608 return;
4609
4610 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4611
4612 // FIXME: The test for external storage here seems wrong? We still
4613 // need to check for mismatches.
4614 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4615 // Don't complain about out-of-line definitions of static members.
4616 !(Old->getLexicalDeclContext()->isRecord() &&
4617 !New->getLexicalDeclContext()->isRecord())) {
4618 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4619 Diag(OldLocation, PrevDiag);
4620 return New->setInvalidDecl();
4621 }
4622
4623 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4624 if (VarDecl *Def = Old->getDefinition()) {
4625 // C++1z [dcl.fcn.spec]p4:
4626 // If the definition of a variable appears in a translation unit before
4627 // its first declaration as inline, the program is ill-formed.
4628 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4629 Diag(Def->getLocation(), diag::note_previous_definition);
4630 }
4631 }
4632
4633 // If this redeclaration makes the variable inline, we may need to add it to
4634 // UndefinedButUsed.
4635 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4636 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4637 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4638 SourceLocation()));
4639
4640 if (New->getTLSKind() != Old->getTLSKind()) {
4641 if (!Old->getTLSKind()) {
4642 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4643 Diag(OldLocation, PrevDiag);
4644 } else if (!New->getTLSKind()) {
4645 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4646 Diag(OldLocation, PrevDiag);
4647 } else {
4648 // Do not allow redeclaration to change the variable between requiring
4649 // static and dynamic initialization.
4650 // FIXME: GCC allows this, but uses the TLS keyword on the first
4651 // declaration to determine the kind. Do we need to be compatible here?
4652 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4653 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4654 Diag(OldLocation, PrevDiag);
4655 }
4656 }
4657
4658 // C++ doesn't have tentative definitions, so go right ahead and check here.
4659 if (getLangOpts().CPlusPlus) {
4660 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4661 Old->getCanonicalDecl()->isConstexpr()) {
4662 // This definition won't be a definition any more once it's been merged.
4663 Diag(New->getLocation(),
4664 diag::warn_deprecated_redundant_constexpr_static_def);
4665 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4666 VarDecl *Def = Old->getDefinition();
4667 if (Def && checkVarDeclRedefinition(Def, New))
4668 return;
4669 }
4670 }
4671
4672 if (haveIncompatibleLanguageLinkages(Old, New)) {
4673 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4674 Diag(OldLocation, PrevDiag);
4675 New->setInvalidDecl();
4676 return;
4677 }
4678
4679 // Merge "used" flag.
4680 if (Old->getMostRecentDecl()->isUsed(false))
4681 New->setIsUsed();
4682
4683 // Keep a chain of previous declarations.
4684 New->setPreviousDecl(Old);
4685 if (NewTemplate)
4686 NewTemplate->setPreviousDecl(OldTemplate);
4687
4688 // Inherit access appropriately.
4689 New->setAccess(Old->getAccess());
4690 if (NewTemplate)
4691 NewTemplate->setAccess(New->getAccess());
4692
4693 if (Old->isInline())
4694 New->setImplicitlyInline();
4695}
4696
4697void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4698 SourceManager &SrcMgr = getSourceManager();
4699 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4700 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4701 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4702 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4703 auto &HSI = PP.getHeaderSearchInfo();
4704 StringRef HdrFilename =
4705 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4706
4707 auto noteFromModuleOrInclude = [&](Module *Mod,
4708 SourceLocation IncLoc) -> bool {
4709 // Redefinition errors with modules are common with non modular mapped
4710 // headers, example: a non-modular header H in module A that also gets
4711 // included directly in a TU. Pointing twice to the same header/definition
4712 // is confusing, try to get better diagnostics when modules is on.
4713 if (IncLoc.isValid()) {
4714 if (Mod) {
4715 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4716 << HdrFilename.str() << Mod->getFullModuleName();
4717 if (!Mod->DefinitionLoc.isInvalid())
4718 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4719 << Mod->getFullModuleName();
4720 } else {
4721 Diag(IncLoc, diag::note_redefinition_include_same_file)
4722 << HdrFilename.str();
4723 }
4724 return true;
4725 }
4726
4727 return false;
4728 };
4729
4730 // Is it the same file and same offset? Provide more information on why
4731 // this leads to a redefinition error.
4732 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4733 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4734 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4735 bool EmittedDiag =
4736 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4737 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4738
4739 // If the header has no guards, emit a note suggesting one.
4740 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4741 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4742
4743 if (EmittedDiag)
4744 return;
4745 }
4746
4747 // Redefinition coming from different files or couldn't do better above.
4748 if (Old->getLocation().isValid())
4749 Diag(Old->getLocation(), diag::note_previous_definition);
4750}
4751
4752/// We've just determined that \p Old and \p New both appear to be definitions
4753/// of the same variable. Either diagnose or fix the problem.
4754bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4755 if (!hasVisibleDefinition(Old) &&
4756 (New->getFormalLinkage() == InternalLinkage ||
4757 New->isInline() ||
4758 isa<VarTemplateSpecializationDecl>(New) ||
4759 New->getDescribedVarTemplate() ||
4760 New->getNumTemplateParameterLists() ||
4761 New->getDeclContext()->isDependentContext())) {
4762 // The previous definition is hidden, and multiple definitions are
4763 // permitted (in separate TUs). Demote this to a declaration.
4764 New->demoteThisDefinitionToDeclaration();
4765
4766 // Make the canonical definition visible.
4767 if (auto *OldTD = Old->getDescribedVarTemplate())
4768 makeMergedDefinitionVisible(OldTD);
4769 makeMergedDefinitionVisible(Old);
4770 return false;
4771 } else {
4772 Diag(New->getLocation(), diag::err_redefinition) << New;
4773 notePreviousDefinition(Old, New->getLocation());
4774 New->setInvalidDecl();
4775 return true;
4776 }
4777}
4778
4779/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4780/// no declarator (e.g. "struct foo;") is parsed.
4781Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4782 DeclSpec &DS,
4783 const ParsedAttributesView &DeclAttrs,
4784 RecordDecl *&AnonRecord) {
4785 return ParsedFreeStandingDeclSpec(
4786 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4787}
4788
4789// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4790// disambiguate entities defined in different scopes.
4791// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4792// compatibility.
4793// We will pick our mangling number depending on which version of MSVC is being
4794// targeted.
4795static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4796 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4797 ? S->getMSCurManglingNumber()
4798 : S->getMSLastManglingNumber();
4799}
4800
4801void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4802 if (!Context.getLangOpts().CPlusPlus)
4803 return;
4804
4805 if (isa<CXXRecordDecl>(Tag->getParent())) {
4806 // If this tag is the direct child of a class, number it if
4807 // it is anonymous.
4808 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4809 return;
4810 MangleNumberingContext &MCtx =
4811 Context.getManglingNumberContext(Tag->getParent());
4812 Context.setManglingNumber(
4813 Tag, MCtx.getManglingNumber(
4814 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4815 return;
4816 }
4817
4818 // If this tag isn't a direct child of a class, number it if it is local.
4819 MangleNumberingContext *MCtx;
4820 Decl *ManglingContextDecl;
4821 std::tie(MCtx, ManglingContextDecl) =
4822 getCurrentMangleNumberContext(Tag->getDeclContext());
4823 if (MCtx) {
4824 Context.setManglingNumber(
4825 Tag, MCtx->getManglingNumber(
4826 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4827 }
4828}
4829
4830namespace {
4831struct NonCLikeKind {
4832 enum {
4833 None,
4834 BaseClass,
4835 DefaultMemberInit,
4836 Lambda,
4837 Friend,
4838 OtherMember,
4839 Invalid,
4840 } Kind = None;
4841 SourceRange Range;
4842
4843 explicit operator bool() { return Kind != None; }
4844};
4845}
4846
4847/// Determine whether a class is C-like, according to the rules of C++
4848/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4849static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4850 if (RD->isInvalidDecl())
4851 return {NonCLikeKind::Invalid, {}};
4852
4853 // C++ [dcl.typedef]p9: [P1766R1]
4854 // An unnamed class with a typedef name for linkage purposes shall not
4855 //
4856 // -- have any base classes
4857 if (RD->getNumBases())
4858 return {NonCLikeKind::BaseClass,
4859 SourceRange(RD->bases_begin()->getBeginLoc(),
4860 RD->bases_end()[-1].getEndLoc())};
4861 bool Invalid = false;
4862 for (Decl *D : RD->decls()) {
4863 // Don't complain about things we already diagnosed.
4864 if (D->isInvalidDecl()) {
4865 Invalid = true;
4866 continue;
4867 }
4868
4869 // -- have any [...] default member initializers
4870 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4871 if (FD->hasInClassInitializer()) {
4872 auto *Init = FD->getInClassInitializer();
4873 return {NonCLikeKind::DefaultMemberInit,
4874 Init ? Init->getSourceRange() : D->getSourceRange()};
4875 }
4876 continue;
4877 }
4878
4879 // FIXME: We don't allow friend declarations. This violates the wording of
4880 // P1766, but not the intent.
4881 if (isa<FriendDecl>(D))
4882 return {NonCLikeKind::Friend, D->getSourceRange()};
4883
4884 // -- declare any members other than non-static data members, member
4885 // enumerations, or member classes,
4886 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4887 isa<EnumDecl>(D))
4888 continue;
4889 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4890 if (!MemberRD) {
4891 if (D->isImplicit())
4892 continue;
4893 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4894 }
4895
4896 // -- contain a lambda-expression,
4897 if (MemberRD->isLambda())
4898 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4899
4900 // and all member classes shall also satisfy these requirements
4901 // (recursively).
4902 if (MemberRD->isThisDeclarationADefinition()) {
4903 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4904 return Kind;
4905 }
4906 }
4907
4908 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4909}
4910
4911void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4912 TypedefNameDecl *NewTD) {
4913 if (TagFromDeclSpec->isInvalidDecl())
4914 return;
4915
4916 // Do nothing if the tag already has a name for linkage purposes.
4917 if (TagFromDeclSpec->hasNameForLinkage())
4918 return;
4919
4920 // A well-formed anonymous tag must always be a TUK_Definition.
4921 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "clang/lib/Sema/SemaDecl.cpp", 4921, __extension__ __PRETTY_FUNCTION__
))
;
4922
4923 // The type must match the tag exactly; no qualifiers allowed.
4924 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4925 Context.getTagDeclType(TagFromDeclSpec))) {
4926 if (getLangOpts().CPlusPlus)
4927 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4928 return;
4929 }
4930
4931 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4932 // An unnamed class with a typedef name for linkage purposes shall [be
4933 // C-like].
4934 //
4935 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4936 // shouldn't happen, but there are constructs that the language rule doesn't
4937 // disallow for which we can't reasonably avoid computing linkage early.
4938 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4939 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4940 : NonCLikeKind();
4941 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4942 if (NonCLike || ChangesLinkage) {
4943 if (NonCLike.Kind == NonCLikeKind::Invalid)
4944 return;
4945
4946 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4947 if (ChangesLinkage) {
4948 // If the linkage changes, we can't accept this as an extension.
4949 if (NonCLike.Kind == NonCLikeKind::None)
4950 DiagID = diag::err_typedef_changes_linkage;
4951 else
4952 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4953 }
4954
4955 SourceLocation FixitLoc =
4956 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4957 llvm::SmallString<40> TextToInsert;
4958 TextToInsert += ' ';
4959 TextToInsert += NewTD->getIdentifier()->getName();
4960
4961 Diag(FixitLoc, DiagID)
4962 << isa<TypeAliasDecl>(NewTD)
4963 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4964 if (NonCLike.Kind != NonCLikeKind::None) {
4965 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4966 << NonCLike.Kind - 1 << NonCLike.Range;
4967 }
4968 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4969 << NewTD << isa<TypeAliasDecl>(NewTD);
4970
4971 if (ChangesLinkage)
4972 return;
4973 }
4974
4975 // Otherwise, set this as the anon-decl typedef for the tag.
4976 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4977}
4978
4979static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4980 switch (T) {
4981 case DeclSpec::TST_class:
4982 return 0;
4983 case DeclSpec::TST_struct:
4984 return 1;
4985 case DeclSpec::TST_interface:
4986 return 2;
4987 case DeclSpec::TST_union:
4988 return 3;
4989 case DeclSpec::TST_enum:
4990 return 4;
4991 default:
4992 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "clang/lib/Sema/SemaDecl.cpp", 4992)
;
4993 }
4994}
4995
4996/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4997/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4998/// parameters to cope with template friend declarations.
4999Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5000 DeclSpec &DS,
5001 const ParsedAttributesView &DeclAttrs,
5002 MultiTemplateParamsArg TemplateParams,
5003 bool IsExplicitInstantiation,
5004 RecordDecl *&AnonRecord) {
5005 Decl *TagD = nullptr;
5006 TagDecl *Tag = nullptr;
5007 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5008 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5009 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5010 DS.getTypeSpecType() == DeclSpec::TST_union ||
5011 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5012 TagD = DS.getRepAsDecl();
5013
5014 if (!TagD) // We probably had an error
5015 return nullptr;
5016
5017 // Note that the above type specs guarantee that the
5018 // type rep is a Decl, whereas in many of the others
5019 // it's a Type.
5020 if (isa<TagDecl>(TagD))
5021 Tag = cast<TagDecl>(TagD);
5022 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5023 Tag = CTD->getTemplatedDecl();
5024 }
5025
5026 if (Tag) {
5027 handleTagNumbering(Tag, S);
5028 Tag->setFreeStanding();
5029 if (Tag->isInvalidDecl())
5030 return Tag;
5031 }
5032
5033 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5034 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5035 // or incomplete types shall not be restrict-qualified."
5036 if (TypeQuals & DeclSpec::TQ_restrict)
5037 Diag(DS.getRestrictSpecLoc(),
5038 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5039 << DS.getSourceRange();
5040 }
5041
5042 if (DS.isInlineSpecified())
5043 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5044 << getLangOpts().CPlusPlus17;
5045
5046 if (DS.hasConstexprSpecifier()) {
5047 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5048 // and definitions of functions and variables.
5049 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5050 // the declaration of a function or function template
5051 if (Tag)
5052 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5053 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
5054 << static_cast<int>(DS.getConstexprSpecifier());
5055 else
5056 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5057 << static_cast<int>(DS.getConstexprSpecifier());
5058 // Don't emit warnings after this error.
5059 return TagD;
5060 }
5061
5062 DiagnoseFunctionSpecifiers(DS);
5063
5064 if (DS.isFriendSpecified()) {
5065 // If we're dealing with a decl but not a TagDecl, assume that
5066 // whatever routines created it handled the friendship aspect.
5067 if (TagD && !Tag)
5068 return nullptr;
5069 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5070 }
5071
5072 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5073 bool IsExplicitSpecialization =
5074 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5075 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5076 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5077 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5078 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5079 // nested-name-specifier unless it is an explicit instantiation
5080 // or an explicit specialization.
5081 //
5082 // FIXME: We allow class template partial specializations here too, per the
5083 // obvious intent of DR1819.
5084 //
5085 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5086 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5087 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
5088 return nullptr;
5089 }
5090
5091 // Track whether this decl-specifier declares anything.
5092 bool DeclaresAnything = true;
5093
5094 // Handle anonymous struct definitions.
5095 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5096 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5097 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5098 if (getLangOpts().CPlusPlus ||
5099 Record->getDeclContext()->isRecord()) {
5100 // If CurContext is a DeclContext that can contain statements,
5101 // RecursiveASTVisitor won't visit the decls that
5102 // BuildAnonymousStructOrUnion() will put into CurContext.
5103 // Also store them here so that they can be part of the
5104 // DeclStmt that gets created in this case.
5105 // FIXME: Also return the IndirectFieldDecls created by
5106 // BuildAnonymousStructOr union, for the same reason?
5107 if (CurContext->isFunctionOrMethod())
5108 AnonRecord = Record;
5109 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5110 Context.getPrintingPolicy());
5111 }
5112
5113 DeclaresAnything = false;
5114 }
5115 }
5116
5117 // C11 6.7.2.1p2:
5118 // A struct-declaration that does not declare an anonymous structure or
5119 // anonymous union shall contain a struct-declarator-list.
5120 //
5121 // This rule also existed in C89 and C99; the grammar for struct-declaration
5122 // did not permit a struct-declaration without a struct-declarator-list.
5123 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5124 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5125 // Check for Microsoft C extension: anonymous struct/union member.
5126 // Handle 2 kinds of anonymous struct/union:
5127 // struct STRUCT;
5128 // union UNION;
5129 // and
5130 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5131 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5132 if ((Tag && Tag->getDeclName()) ||
5133 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5134 RecordDecl *Record = nullptr;
5135 if (Tag)
5136 Record = dyn_cast<RecordDecl>(Tag);
5137 else if (const RecordType *RT =
5138 DS.getRepAsType().get()->getAsStructureType())
5139 Record = RT->getDecl();
5140 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5141 Record = UT->getDecl();
5142
5143 if (Record && getLangOpts().MicrosoftExt) {
5144 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5145 << Record->isUnion() << DS.getSourceRange();
5146 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5147 }
5148
5149 DeclaresAnything = false;
5150 }
5151 }
5152
5153 // Skip all the checks below if we have a type error.
5154 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5155 (TagD && TagD->isInvalidDecl()))
5156 return TagD;
5157
5158 if (getLangOpts().CPlusPlus &&
5159 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5160 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5161 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5162 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5163 DeclaresAnything = false;
5164
5165 if (!DS.isMissingDeclaratorOk()) {
5166 // Customize diagnostic for a typedef missing a name.
5167 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5168 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5169 << DS.getSourceRange();
5170 else
5171 DeclaresAnything = false;
5172 }
5173
5174 if (DS.isModulePrivateSpecified() &&
5175 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5176 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5177 << Tag->getTagKind()
5178 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5179
5180 ActOnDocumentableDecl(TagD);
5181
5182 // C 6.7/2:
5183 // A declaration [...] shall declare at least a declarator [...], a tag,
5184 // or the members of an enumeration.
5185 // C++ [dcl.dcl]p3:
5186 // [If there are no declarators], and except for the declaration of an
5187 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5188 // names into the program, or shall redeclare a name introduced by a
5189 // previous declaration.
5190 if (!DeclaresAnything) {
5191 // In C, we allow this as a (popular) extension / bug. Don't bother
5192 // producing further diagnostics for redundant qualifiers after this.
5193 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5194 ? diag::err_no_declarators
5195 : diag::ext_no_declarators)
5196 << DS.getSourceRange();
5197 return TagD;
5198 }
5199
5200 // C++ [dcl.stc]p1:
5201 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5202 // init-declarator-list of the declaration shall not be empty.
5203 // C++ [dcl.fct.spec]p1:
5204 // If a cv-qualifier appears in a decl-specifier-seq, the
5205 // init-declarator-list of the declaration shall not be empty.
5206 //
5207 // Spurious qualifiers here appear to be valid in C.
5208 unsigned DiagID = diag::warn_standalone_specifier;
5209 if (getLangOpts().CPlusPlus)
5210 DiagID = diag::ext_standalone_specifier;
5211
5212 // Note that a linkage-specification sets a storage class, but
5213 // 'extern "C" struct foo;' is actually valid and not theoretically
5214 // useless.
5215 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5216 if (SCS == DeclSpec::SCS_mutable)
5217 // Since mutable is not a viable storage class specifier in C, there is
5218 // no reason to treat it as an extension. Instead, diagnose as an error.
5219 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5220 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5221 Diag(DS.getStorageClassSpecLoc(), DiagID)
5222 << DeclSpec::getSpecifierName(SCS);
5223 }
5224
5225 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5226 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5227 << DeclSpec::getSpecifierName(TSCS);
5228 if (DS.getTypeQualifiers()) {
5229 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5230 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5231 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5232 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5233 // Restrict is covered above.
5234 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5235 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5236 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5237 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5238 }
5239
5240 // Warn about ignored type attributes, for example:
5241 // __attribute__((aligned)) struct A;
5242 // Attributes should be placed after tag to apply to type declaration.
5243 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5244 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5245 if (TypeSpecType == DeclSpec::TST_class ||
5246 TypeSpecType == DeclSpec::TST_struct ||
5247 TypeSpecType == DeclSpec::TST_interface ||
5248 TypeSpecType == DeclSpec::TST_union ||
5249 TypeSpecType == DeclSpec::TST_enum) {
5250 for (const ParsedAttr &AL : DS.getAttributes())
5251 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5252 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5253 for (const ParsedAttr &AL : DeclAttrs)
5254 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5255 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5256 }
5257 }
5258
5259 return TagD;
5260}
5261
5262/// We are trying to inject an anonymous member into the given scope;
5263/// check if there's an existing declaration that can't be overloaded.
5264///
5265/// \return true if this is a forbidden redeclaration
5266static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5267 Scope *S,
5268 DeclContext *Owner,
5269 DeclarationName Name,
5270 SourceLocation NameLoc,
5271 bool IsUnion) {
5272 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5273 Sema::ForVisibleRedeclaration);
5274 if (!SemaRef.LookupName(R, S)) return false;
5275
5276 // Pick a representative declaration.
5277 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5278 assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl"
) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "clang/lib/Sema/SemaDecl.cpp", 5278, __extension__ __PRETTY_FUNCTION__
))
;
5279
5280 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5281 return false;
5282
5283 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5284 << IsUnion << Name;
5285 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5286
5287 return true;
5288}
5289
5290/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5291/// anonymous struct or union AnonRecord into the owning context Owner
5292/// and scope S. This routine will be invoked just after we realize
5293/// that an unnamed union or struct is actually an anonymous union or
5294/// struct, e.g.,
5295///
5296/// @code
5297/// union {
5298/// int i;
5299/// float f;
5300/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5301/// // f into the surrounding scope.x
5302/// @endcode
5303///
5304/// This routine is recursive, injecting the names of nested anonymous
5305/// structs/unions into the owning context and scope as well.
5306static bool
5307InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5308 RecordDecl *AnonRecord, AccessSpecifier AS,
5309 SmallVectorImpl<NamedDecl *> &Chaining) {
5310 bool Invalid = false;
5311
5312 // Look every FieldDecl and IndirectFieldDecl with a name.
5313 for (auto *D : AnonRecord->decls()) {
5314 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5315 cast<NamedDecl>(D)->getDeclName()) {
5316 ValueDecl *VD = cast<ValueDecl>(D);
5317 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5318 VD->getLocation(),
5319 AnonRecord->isUnion())) {
5320 // C++ [class.union]p2:
5321 // The names of the members of an anonymous union shall be
5322 // distinct from the names of any other entity in the
5323 // scope in which the anonymous union is declared.
5324 Invalid = true;
5325 } else {
5326 // C++ [class.union]p2:
5327 // For the purpose of name lookup, after the anonymous union
5328 // definition, the members of the anonymous union are
5329 // considered to have been defined in the scope in which the
5330 // anonymous union is declared.
5331 unsigned OldChainingSize = Chaining.size();
5332 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5333 Chaining.append(IF->chain_begin(), IF->chain_end());
5334 else
5335 Chaining.push_back(VD);
5336
5337 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "clang/lib/Sema/SemaDecl.cpp"
, 5337, __extension__ __PRETTY_FUNCTION__))
;
5338 NamedDecl **NamedChain =
5339 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5340 for (unsigned i = 0; i < Chaining.size(); i++)
5341 NamedChain[i] = Chaining[i];
5342
5343 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5344 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5345 VD->getType(), {NamedChain, Chaining.size()});
5346
5347 for (const auto *Attr : VD->attrs())
5348 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5349
5350 IndirectField->setAccess(AS);
5351 IndirectField->setImplicit();
5352 SemaRef.PushOnScopeChains(IndirectField, S);
5353
5354 // That includes picking up the appropriate access specifier.
5355 if (AS != AS_none) IndirectField->setAccess(AS);
5356
5357 Chaining.resize(OldChainingSize);
5358 }
5359 }
5360 }
5361
5362 return Invalid;
5363}
5364
5365/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5366/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5367/// illegal input values are mapped to SC_None.
5368static StorageClass
5369StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5370 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5371 assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "clang/lib/Sema/SemaDecl.cpp", 5372, __extension__ __PRETTY_FUNCTION__
))
5372 "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "clang/lib/Sema/SemaDecl.cpp", 5372, __extension__ __PRETTY_FUNCTION__
))
;
5373 switch (StorageClassSpec) {
5374 case DeclSpec::SCS_unspecified: return SC_None;
5375 case DeclSpec::SCS_extern:
5376 if (DS.isExternInLinkageSpec())
5377 return SC_None;
5378 return SC_Extern;
5379 case DeclSpec::SCS_static: return SC_Static;
5380 case DeclSpec::SCS_auto: return SC_Auto;
5381 case DeclSpec::SCS_register: return SC_Register;
5382 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5383 // Illegal SCSs map to None: error reporting is up to the caller.
5384 case DeclSpec::SCS_mutable: // Fall through.
5385 case DeclSpec::SCS_typedef: return SC_None;
5386 }
5387 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "clang/lib/Sema/SemaDecl.cpp", 5387)
;
5388}
5389
5390static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5391 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "clang/lib/Sema/SemaDecl.cpp", 5391, __extension__ __PRETTY_FUNCTION__
))
;
5392
5393 for (const auto *I : Record->decls()) {
5394 const auto *FD = dyn_cast<FieldDecl>(I);
5395 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5396 FD = IFD->getAnonField();
5397 if (FD && FD->hasInClassInitializer())
5398 return FD->getLocation();
5399 }
5400
5401 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "clang/lib/Sema/SemaDecl.cpp", 5401)
;
5402}
5403
5404static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5405 SourceLocation DefaultInitLoc) {
5406 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5407 return;
5408
5409 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5410 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5411}
5412
5413static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5414 CXXRecordDecl *AnonUnion) {
5415 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5416 return;
5417
5418 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5419}
5420
5421/// BuildAnonymousStructOrUnion - Handle the declaration of an
5422/// anonymous structure or union. Anonymous unions are a C++ feature
5423/// (C++ [class.union]) and a C11 feature; anonymous structures
5424/// are a C11 feature and GNU C++ extension.
5425Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5426 AccessSpecifier AS,
5427 RecordDecl *Record,
5428 const PrintingPolicy &Policy) {
5429 DeclContext *Owner = Record->getDeclContext();
5430
5431 // Diagnose whether this anonymous struct/union is an extension.
5432 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5433 Diag(Record->getLocation(), diag::ext_anonymous_union);
5434 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5435 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5436 else if (!Record->isUnion() && !getLangOpts().C11)
5437 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5438
5439 // C and C++ require different kinds of checks for anonymous
5440 // structs/unions.
5441 bool Invalid = false;
5442 if (getLangOpts().CPlusPlus) {
5443 const char *PrevSpec = nullptr;
5444 if (Record->isUnion()) {
5445 // C++ [class.union]p6:
5446 // C++17 [class.union.anon]p2:
5447 // Anonymous unions declared in a named namespace or in the
5448 // global namespace shall be declared static.
5449 unsigned DiagID;
5450 DeclContext *OwnerScope = Owner->getRedeclContext();
5451 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5452 (OwnerScope->isTranslationUnit() ||
5453 (OwnerScope->isNamespace() &&
5454 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5455 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5456 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5457
5458 // Recover by adding 'static'.
5459 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5460 PrevSpec, DiagID, Policy);
5461 }
5462 // C++ [class.union]p6:
5463 // A storage class is not allowed in a declaration of an
5464 // anonymous union in a class scope.
5465 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5466 isa<RecordDecl>(Owner)) {
5467 Diag(DS.getStorageClassSpecLoc(),
5468 diag::err_anonymous_union_with_storage_spec)
5469 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5470
5471 // Recover by removing the storage specifier.
5472 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5473 SourceLocation(),
5474 PrevSpec, DiagID, Context.getPrintingPolicy());
5475 }
5476 }
5477
5478 // Ignore const/volatile/restrict qualifiers.
5479 if (DS.getTypeQualifiers()) {
5480 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5481 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5482 << Record->isUnion() << "const"
5483 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5484 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5485 Diag(DS.getVolatileSpecLoc(),
5486 diag::ext_anonymous_struct_union_qualified)
5487 << Record->isUnion() << "volatile"
5488 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5489 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5490 Diag(DS.getRestrictSpecLoc(),
5491 diag::ext_anonymous_struct_union_qualified)
5492 << Record->isUnion() << "restrict"
5493 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5494 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5495 Diag(DS.getAtomicSpecLoc(),
5496 diag::ext_anonymous_struct_union_qualified)
5497 << Record->isUnion() << "_Atomic"
5498 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5499 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5500 Diag(DS.getUnalignedSpecLoc(),
5501 diag::ext_anonymous_struct_union_qualified)
5502 << Record->isUnion() << "__unaligned"
5503 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5504
5505 DS.ClearTypeQualifiers();
5506 }
5507
5508 // C++ [class.union]p2:
5509 // The member-specification of an anonymous union shall only
5510 // define non-static data members. [Note: nested types and
5511 // functions cannot be declared within an anonymous union. ]
5512 for (auto *Mem : Record->decls()) {
5513 // Ignore invalid declarations; we already diagnosed them.
5514 if (Mem->isInvalidDecl())
5515 continue;
5516
5517 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5518 // C++ [class.union]p3:
5519 // An anonymous union shall not have private or protected
5520 // members (clause 11).
5521 assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void
(0) : __assert_fail ("FD->getAccess() != AS_none", "clang/lib/Sema/SemaDecl.cpp"
, 5521, __extension__ __PRETTY_FUNCTION__))
;
5522 if (FD->getAccess() != AS_public) {
5523 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5524 << Record->isUnion() << (FD->getAccess() == AS_protected);
5525 Invalid = true;
5526 }
5527
5528 // C++ [class.union]p1
5529 // An object of a class with a non-trivial constructor, a non-trivial
5530 // copy constructor, a non-trivial destructor, or a non-trivial copy
5531 // assignment operator cannot be a member of a union, nor can an
5532 // array of such objects.
5533 if (CheckNontrivialField(FD))
5534 Invalid = true;
5535 } else if (Mem->isImplicit()) {
5536 // Any implicit members are fine.
5537 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5538 // This is a type that showed up in an
5539 // elaborated-type-specifier inside the anonymous struct or
5540 // union, but which actually declares a type outside of the
5541 // anonymous struct or union. It's okay.
5542 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5543 if (!MemRecord->isAnonymousStructOrUnion() &&
5544 MemRecord->getDeclName()) {
5545 // Visual C++ allows type definition in anonymous struct or union.
5546 if (getLangOpts().MicrosoftExt)
5547 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5548 << Record->isUnion();
5549 else {
5550 // This is a nested type declaration.
5551 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5552 << Record->isUnion();
5553 Invalid = true;
5554 }
5555 } else {
5556 // This is an anonymous type definition within another anonymous type.
5557 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5558 // not part of standard C++.
5559 Diag(MemRecord->getLocation(),
5560 diag::ext_anonymous_record_with_anonymous_type)
5561 << Record->isUnion();
5562 }
5563 } else if (isa<AccessSpecDecl>(Mem)) {
5564 // Any access specifier is fine.
5565 } else if (isa<StaticAssertDecl>(Mem)) {
5566 // In C++1z, static_assert declarations are also fine.
5567 } else {
5568 // We have something that isn't a non-static data
5569 // member. Complain about it.
5570 unsigned DK = diag::err_anonymous_record_bad_member;
5571 if (isa<TypeDecl>(Mem))
5572 DK = diag::err_anonymous_record_with_type;
5573 else if (isa<FunctionDecl>(Mem))
5574 DK = diag::err_anonymous_record_with_function;
5575 else if (isa<VarDecl>(Mem))
5576 DK = diag::err_anonymous_record_with_static;
5577
5578 // Visual C++ allows type definition in anonymous struct or union.
5579 if (getLangOpts().MicrosoftExt &&
5580 DK == diag::err_anonymous_record_with_type)
5581 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5582 << Record->isUnion();
5583 else {
5584 Diag(Mem->getLocation(), DK) << Record->isUnion();
5585 Invalid = true;
5586 }
5587 }
5588 }
5589
5590 // C++11 [class.union]p8 (DR1460):
5591 // At most one variant member of a union may have a
5592 // brace-or-equal-initializer.
5593 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5594 Owner->isRecord())
5595 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5596 cast<CXXRecordDecl>(Record));
5597 }
5598
5599 if (!Record->isUnion() && !Owner->isRecord()) {
5600 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5601 << getLangOpts().CPlusPlus;
5602 Invalid = true;
5603 }
5604
5605 // C++ [dcl.dcl]p3:
5606 // [If there are no declarators], and except for the declaration of an
5607 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5608 // names into the program
5609 // C++ [class.mem]p2:
5610 // each such member-declaration shall either declare at least one member
5611 // name of the class or declare at least one unnamed bit-field
5612 //
5613 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5614 if (getLangOpts().CPlusPlus && Record->field_empty())
5615 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5616
5617 // Mock up a declarator.
5618 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5619 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5620 assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "clang/lib/Sema/SemaDecl.cpp", 5620, __extension__ __PRETTY_FUNCTION__
))
;
5621
5622 // Create a declaration for this anonymous struct/union.
5623 NamedDecl *Anon = nullptr;
5624 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5625 Anon = FieldDecl::Create(
5626 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5627 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5628 /*BitWidth=*/nullptr, /*Mutable=*/false,
5629 /*InitStyle=*/ICIS_NoInit);
5630 Anon->setAccess(AS);
5631 ProcessDeclAttributes(S, Anon, Dc);
5632
5633 if (getLangOpts().CPlusPlus)
5634 FieldCollector->Add(cast<FieldDecl>(Anon));
5635 } else {
5636 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5637 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5638 if (SCSpec == DeclSpec::SCS_mutable) {
5639 // mutable can only appear on non-static class members, so it's always
5640 // an error here
5641 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5642 Invalid = true;
5643 SC = SC_None;
5644 }
5645
5646 assert(DS.getAttributes().empty() && "No attribute expected")(static_cast <bool> (DS.getAttributes().empty() &&
"No attribute expected") ? void (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\""
, "clang/lib/Sema/SemaDecl.cpp", 5646, __extension__ __PRETTY_FUNCTION__
))
;
5647 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5648 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5649 Context.getTypeDeclType(Record), TInfo, SC);
5650
5651 // Default-initialize the implicit variable. This initialization will be
5652 // trivial in almost all cases, except if a union member has an in-class
5653 // initializer:
5654 // union { int n = 0; };
5655 ActOnUninitializedDecl(Anon);
5656 }
5657 Anon->setImplicit();
5658
5659 // Mark this as an anonymous struct/union type.
5660 Record->setAnonymousStructOrUnion(true);
5661
5662 // Add the anonymous struct/union object to the current
5663 // context. We'll be referencing this object when we refer to one of
5664 // its members.
5665 Owner->addDecl(Anon);
5666
5667 // Inject the members of the anonymous struct/union into the owning
5668 // context and into the identifier resolver chain for name lookup
5669 // purposes.
5670 SmallVector<NamedDecl*, 2> Chain;
5671 Chain.push_back(Anon);
5672
5673 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5674 Invalid = true;
5675
5676 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5677 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5678 MangleNumberingContext *MCtx;
5679 Decl *ManglingContextDecl;
5680 std::tie(MCtx, ManglingContextDecl) =
5681 getCurrentMangleNumberContext(NewVD->getDeclContext());
5682 if (MCtx) {
5683 Context.setManglingNumber(
5684 NewVD, MCtx->getManglingNumber(
5685 NewVD, getMSManglingNumber(getLangOpts(), S)));
5686 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5687 }
5688 }
5689 }
5690
5691 if (Invalid)
5692 Anon->setInvalidDecl();
5693
5694 return Anon;
5695}
5696
5697/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5698/// Microsoft C anonymous structure.
5699/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5700/// Example:
5701///
5702/// struct A { int a; };
5703/// struct B { struct A; int b; };
5704///
5705/// void foo() {
5706/// B var;
5707/// var.a = 3;
5708/// }
5709///
5710Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5711 RecordDecl *Record) {
5712 assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!"
) ? void (0) : __assert_fail ("Record && \"expected a record!\""
, "clang/lib/Sema/SemaDecl.cpp", 5712, __extension__ __PRETTY_FUNCTION__
))
;
5713
5714 // Mock up a declarator.
5715 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5716 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5717 assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "clang/lib/Sema/SemaDecl.cpp", 5717, __extension__ __PRETTY_FUNCTION__
))
;
5718
5719 auto *ParentDecl = cast<RecordDecl>(CurContext);
5720 QualType RecTy = Context.getTypeDeclType(Record);
5721
5722 // Create a declaration for this anonymous struct.
5723 NamedDecl *Anon =
5724 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5725 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5726 /*BitWidth=*/nullptr, /*Mutable=*/false,
5727 /*InitStyle=*/ICIS_NoInit);
5728 Anon->setImplicit();
5729
5730 // Add the anonymous struct object to the current context.
5731 CurContext->addDecl(Anon);
5732
5733 // Inject the members of the anonymous struct into the current
5734 // context and into the identifier resolver chain for name lookup
5735 // purposes.
5736 SmallVector<NamedDecl*, 2> Chain;
5737 Chain.push_back(Anon);
5738
5739 RecordDecl *RecordDef = Record->getDefinition();
5740 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5741 diag::err_field_incomplete_or_sizeless) ||
5742 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5743 AS_none, Chain)) {
5744 Anon->setInvalidDecl();
5745 ParentDecl->setInvalidDecl();
5746 }
5747
5748 return Anon;
5749}
5750
5751/// GetNameForDeclarator - Determine the full declaration name for the
5752/// given Declarator.
5753DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5754 return GetNameFromUnqualifiedId(D.getName());
5755}
5756
5757/// Retrieves the declaration name from a parsed unqualified-id.
5758DeclarationNameInfo
5759Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5760 DeclarationNameInfo NameInfo;
5761 NameInfo.setLoc(Name.StartLocation);
5762
5763 switch (Name.getKind()) {
5764
5765 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5766 case UnqualifiedIdKind::IK_Identifier:
5767 NameInfo.setName(Name.Identifier);
5768 return NameInfo;
5769
5770 case UnqualifiedIdKind::IK_DeductionGuideName: {
5771 // C++ [temp.deduct.guide]p3:
5772 // The simple-template-id shall name a class template specialization.
5773 // The template-name shall be the same identifier as the template-name
5774 // of the simple-template-id.
5775 // These together intend to imply that the template-name shall name a
5776 // class template.
5777 // FIXME: template<typename T> struct X {};
5778 // template<typename T> using Y = X<T>;
5779 // Y(int) -> Y<int>;
5780 // satisfies these rules but does not name a class template.
5781 TemplateName TN = Name.TemplateName.get().get();
5782 auto *Template = TN.getAsTemplateDecl();
5783 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5784 Diag(Name.StartLocation,
5785 diag::err_deduction_guide_name_not_class_template)
5786 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5787 if (Template)
5788 Diag(Template->getLocation(), diag::note_template_decl_here);
5789 return DeclarationNameInfo();
5790 }
5791
5792 NameInfo.setName(
5793 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5794 return NameInfo;
5795 }
5796
5797 case UnqualifiedIdKind::IK_OperatorFunctionId:
5798 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5799 Name.OperatorFunctionId.Operator));
5800 NameInfo.setCXXOperatorNameRange(SourceRange(
5801 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5802 return NameInfo;
5803
5804 case UnqualifiedIdKind::IK_LiteralOperatorId:
5805 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5806 Name.Identifier));
5807 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5808 return NameInfo;
5809
5810 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5811 TypeSourceInfo *TInfo;
5812 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5813 if (Ty.isNull())
5814 return DeclarationNameInfo();
5815 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5816 Context.getCanonicalType(Ty)));
5817 NameInfo.setNamedTypeInfo(TInfo);
5818 return NameInfo;
5819 }
5820
5821 case UnqualifiedIdKind::IK_ConstructorName: {
5822 TypeSourceInfo *TInfo;
5823 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5824 if (Ty.isNull())
5825 return DeclarationNameInfo();
5826 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5827 Context.getCanonicalType(Ty)));
5828 NameInfo.setNamedTypeInfo(TInfo);
5829 return NameInfo;
5830 }
5831
5832 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5833 // In well-formed code, we can only have a constructor
5834 // template-id that refers to the current context, so go there
5835 // to find the actual type being constructed.
5836 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5837 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5838 return DeclarationNameInfo();
5839
5840 // Determine the type of the class being constructed.
5841 QualType CurClassType = Context.getTypeDeclType(CurClass);
5842
5843 // FIXME: Check two things: that the template-id names the same type as
5844 // CurClassType, and that the template-id does not occur when the name
5845 // was qualified.
5846
5847 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5848 Context.getCanonicalType(CurClassType)));
5849 // FIXME: should we retrieve TypeSourceInfo?
5850 NameInfo.setNamedTypeInfo(nullptr);
5851 return NameInfo;
5852 }
5853
5854 case UnqualifiedIdKind::IK_DestructorName: {
5855 TypeSourceInfo *TInfo;
5856 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5857 if (Ty.isNull())
5858 return DeclarationNameInfo();
5859 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5860 Context.getCanonicalType(Ty)));
5861 NameInfo.setNamedTypeInfo(TInfo);
5862 return NameInfo;
5863 }
5864
5865 case UnqualifiedIdKind::IK_TemplateId: {
5866 TemplateName TName = Name.TemplateId->Template.get();
5867 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5868 return Context.getNameForTemplate(TName, TNameLoc);
5869 }
5870
5871 } // switch (Name.getKind())
5872
5873 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "clang/lib/Sema/SemaDecl.cpp"
, 5873)
;
5874}
5875
5876static QualType getCoreType(QualType Ty) {
5877 do {
5878 if (Ty->isPointerType() || Ty->isReferenceType())
5879 Ty = Ty->getPointeeType();
5880 else if (Ty->isArrayType())
5881 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5882 else
5883 return Ty.withoutLocalFastQualifiers();
5884 } while (true);
5885}
5886
5887/// hasSimilarParameters - Determine whether the C++ functions Declaration
5888/// and Definition have "nearly" matching parameters. This heuristic is
5889/// used to improve diagnostics in the case where an out-of-line function
5890/// definition doesn't match any declaration within the class or namespace.
5891/// Also sets Params to the list of indices to the parameters that differ
5892/// between the declaration and the definition. If hasSimilarParameters
5893/// returns true and Params is empty, then all of the parameters match.
5894static bool hasSimilarParameters(ASTContext &Context,
5895 FunctionDecl *Declaration,
5896 FunctionDecl *Definition,
5897 SmallVectorImpl<unsigned> &Params) {
5898 Params.clear();
5899 if (Declaration->param_size() != Definition->param_size())
5900 return false;
5901 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5902