Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 9912, column 19
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-store=region -analyzer-opt-analyze-nested-blocks -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 -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/include -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-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -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-2021-11-10-160236-22541-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/clang/lib/Sema/SemaDecl.cpp

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