Bug Summary

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