Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 3780, column 35
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 -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 -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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~++20210926122410+d23fd8ae8906/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() &&
17
Calling 'Decl::getFriendObjectKind'
23
Returning from 'Decl::getFriendObjectKind'
25
Taking false branch
1585 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
24
Assuming the condition is false
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
25.1
'NewM' is null
25.1
'NewM' is null
&& NewM->Kind == Module::PrivateModuleFragment)
1595 NewM = NewM->Parent;
1596 if (OldM
25.2
'OldM' is null
25.2
'OldM' is null
&& OldM->Kind == Module::PrivateModuleFragment)
1597 OldM = OldM->Parent;
1598
1599 if (NewM
25.3
'NewM' is equal to 'OldM'
25.3
'NewM' is equal to 'OldM'
== OldM)
26
Taking true branch
1600 return false;
27
Returning zero, which participates in a condition later
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~++20210926122410+d23fd8ae8906/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 auto iter = RefsMinusAssignments.find(VD);
1948 if (iter == RefsMinusAssignments.end())
1949 return;
1950
1951 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 1952, __extension__ __PRETTY_FUNCTION__))
1952 "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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 1952, __extension__ __PRETTY_FUNCTION__))
;
1953 if (iter->getSecond() != 0)
1954 return;
1955 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1956 : diag::warn_unused_but_set_variable;
1957 Diag(VD->getLocation(), DiagID) << VD;
1958}
1959
1960static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1961 // Verify that we have no forward references left. If so, there was a goto
1962 // or address of a label taken, but no definition of it. Label fwd
1963 // definitions are indicated with a null substmt which is also not a resolved
1964 // MS inline assembly label name.
1965 bool Diagnose = false;
1966 if (L->isMSAsmLabel())
1967 Diagnose = !L->isResolvedMSAsmLabel();
1968 else
1969 Diagnose = L->getStmt() == nullptr;
1970 if (Diagnose)
1971 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1972}
1973
1974void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1975 S->mergeNRVOIntoParent();
1976
1977 if (S->decl_empty()) return;
1978 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
1979 "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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
;
1980
1981 for (auto *TmpD : S->decls()) {
1982 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 1982, __extension__ __PRETTY_FUNCTION__))
;
1983
1984 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 1984, __extension__ __PRETTY_FUNCTION__))
;
1985 NamedDecl *D = cast<NamedDecl>(TmpD);
1986
1987 // Diagnose unused variables in this scope.
1988 if (!S->hasUnrecoverableErrorOccurred()) {
1989 DiagnoseUnusedDecl(D);
1990 if (const auto *RD = dyn_cast<RecordDecl>(D))
1991 DiagnoseUnusedNestedTypedefs(RD);
1992 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1993 DiagnoseUnusedButSetDecl(VD);
1994 RefsMinusAssignments.erase(VD);
1995 }
1996 }
1997
1998 if (!D->getDeclName()) continue;
1999
2000 // If this was a forward reference to a label, verify it was defined.
2001 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2002 CheckPoppedLabel(LD, *this);
2003
2004 // Remove this name from our lexical scope, and warn on it if we haven't
2005 // already.
2006 IdResolver.RemoveDecl(D);
2007 auto ShadowI = ShadowingDecls.find(D);
2008 if (ShadowI != ShadowingDecls.end()) {
2009 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2010 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2011 << D << FD << FD->getParent();
2012 Diag(FD->getLocation(), diag::note_previous_declaration);
2013 }
2014 ShadowingDecls.erase(ShadowI);
2015 }
2016 }
2017}
2018
2019/// Look for an Objective-C class in the translation unit.
2020///
2021/// \param Id The name of the Objective-C class we're looking for. If
2022/// typo-correction fixes this name, the Id will be updated
2023/// to the fixed name.
2024///
2025/// \param IdLoc The location of the name in the translation unit.
2026///
2027/// \param DoTypoCorrection If true, this routine will attempt typo correction
2028/// if there is no class with the given name.
2029///
2030/// \returns The declaration of the named Objective-C class, or NULL if the
2031/// class could not be found.
2032ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2033 SourceLocation IdLoc,
2034 bool DoTypoCorrection) {
2035 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2036 // creation from this context.
2037 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2038
2039 if (!IDecl && DoTypoCorrection) {
2040 // Perform typo correction at the given location, but only if we
2041 // find an Objective-C class name.
2042 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2043 if (TypoCorrection C =
2044 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2045 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2046 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2047 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2048 Id = IDecl->getIdentifier();
2049 }
2050 }
2051 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2052 // This routine must always return a class definition, if any.
2053 if (Def && Def->getDefinition())
2054 Def = Def->getDefinition();
2055 return Def;
2056}
2057
2058/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2059/// from S, where a non-field would be declared. This routine copes
2060/// with the difference between C and C++ scoping rules in structs and
2061/// unions. For example, the following code is well-formed in C but
2062/// ill-formed in C++:
2063/// @code
2064/// struct S6 {
2065/// enum { BAR } e;
2066/// };
2067///
2068/// void test_S6() {
2069/// struct S6 a;
2070/// a.e = BAR;
2071/// }
2072/// @endcode
2073/// For the declaration of BAR, this routine will return a different
2074/// scope. The scope S will be the scope of the unnamed enumeration
2075/// within S6. In C++, this routine will return the scope associated
2076/// with S6, because the enumeration's scope is a transparent
2077/// context but structures can contain non-field names. In C, this
2078/// routine will return the translation unit scope, since the
2079/// enumeration's scope is a transparent context and structures cannot
2080/// contain non-field names.
2081Scope *Sema::getNonFieldDeclScope(Scope *S) {
2082 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2083 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2084 (S->isClassScope() && !getLangOpts().CPlusPlus))
2085 S = S->getParent();
2086 return S;
2087}
2088
2089static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2090 ASTContext::GetBuiltinTypeError Error) {
2091 switch (Error) {
2092 case ASTContext::GE_None:
2093 return "";
2094 case ASTContext::GE_Missing_type:
2095 return BuiltinInfo.getHeaderName(ID);
2096 case ASTContext::GE_Missing_stdio:
2097 return "stdio.h";
2098 case ASTContext::GE_Missing_setjmp:
2099 return "setjmp.h";
2100 case ASTContext::GE_Missing_ucontext:
2101 return "ucontext.h";
2102 }
2103 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 2103)
;
2104}
2105
2106FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2107 unsigned ID, SourceLocation Loc) {
2108 DeclContext *Parent = Context.getTranslationUnitDecl();
2109
2110 if (getLangOpts().CPlusPlus) {
2111 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2112 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2113 CLinkageDecl->setImplicit();
2114 Parent->addDecl(CLinkageDecl);
2115 Parent = CLinkageDecl;
2116 }
2117
2118 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2119 /*TInfo=*/nullptr, SC_Extern,
2120 getCurFPFeatures().isFPConstrained(),
2121 false, Type->isFunctionProtoType());
2122 New->setImplicit();
2123 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2124
2125 // Create Decl objects for each parameter, adding them to the
2126 // FunctionDecl.
2127 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2128 SmallVector<ParmVarDecl *, 16> Params;
2129 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2130 ParmVarDecl *parm = ParmVarDecl::Create(
2131 Context, New, SourceLocation(), SourceLocation(), nullptr,
2132 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2133 parm->setScopeInfo(0, i);
2134 Params.push_back(parm);
2135 }
2136 New->setParams(Params);
2137 }
2138
2139 AddKnownFunctionAttributes(New);
2140 return New;
2141}
2142
2143/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2144/// file scope. lazily create a decl for it. ForRedeclaration is true
2145/// if we're creating this built-in in anticipation of redeclaring the
2146/// built-in.
2147NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2148 Scope *S, bool ForRedeclaration,
2149 SourceLocation Loc) {
2150 LookupNecessaryTypesForBuiltin(S, ID);
2151
2152 ASTContext::GetBuiltinTypeError Error;
2153 QualType R = Context.GetBuiltinType(ID, Error);
2154 if (Error) {
2155 if (!ForRedeclaration)
2156 return nullptr;
2157
2158 // If we have a builtin without an associated type we should not emit a
2159 // warning when we were not able to find a type for it.
2160 if (Error == ASTContext::GE_Missing_type ||
2161 Context.BuiltinInfo.allowTypeMismatch(ID))
2162 return nullptr;
2163
2164 // If we could not find a type for setjmp it is because the jmp_buf type was
2165 // not defined prior to the setjmp declaration.
2166 if (Error == ASTContext::GE_Missing_setjmp) {
2167 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2168 << Context.BuiltinInfo.getName(ID);
2169 return nullptr;
2170 }
2171
2172 // Generally, we emit a warning that the declaration requires the
2173 // appropriate header.
2174 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2175 << getHeaderName(Context.BuiltinInfo, ID, Error)
2176 << Context.BuiltinInfo.getName(ID);
2177 return nullptr;
2178 }
2179
2180 if (!ForRedeclaration &&
2181 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2182 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2183 Diag(Loc, diag::ext_implicit_lib_function_decl)
2184 << Context.BuiltinInfo.getName(ID) << R;
2185 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2186 Diag(Loc, diag::note_include_header_or_declare)
2187 << Header << Context.BuiltinInfo.getName(ID);
2188 }
2189
2190 if (R.isNull())
2191 return nullptr;
2192
2193 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2194 RegisterLocallyScopedExternCDecl(New, S);
2195
2196 // TUScope is the translation-unit scope to insert this function into.
2197 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2198 // relate Scopes to DeclContexts, and probably eliminate CurContext
2199 // entirely, but we're not there yet.
2200 DeclContext *SavedContext = CurContext;
2201 CurContext = New->getDeclContext();
2202 PushOnScopeChains(New, TUScope);
2203 CurContext = SavedContext;
2204 return New;
2205}
2206
2207/// Typedef declarations don't have linkage, but they still denote the same
2208/// entity if their types are the same.
2209/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2210/// isSameEntity.
2211static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2212 TypedefNameDecl *Decl,
2213 LookupResult &Previous) {
2214 // This is only interesting when modules are enabled.
2215 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2216 return;
2217
2218 // Empty sets are uninteresting.
2219 if (Previous.empty())
2220 return;
2221
2222 LookupResult::Filter Filter = Previous.makeFilter();
2223 while (Filter.hasNext()) {
2224 NamedDecl *Old = Filter.next();
2225
2226 // Non-hidden declarations are never ignored.
2227 if (S.isVisible(Old))
2228 continue;
2229
2230 // Declarations of the same entity are not ignored, even if they have
2231 // different linkages.
2232 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2233 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2234 Decl->getUnderlyingType()))
2235 continue;
2236
2237 // If both declarations give a tag declaration a typedef name for linkage
2238 // purposes, then they declare the same entity.
2239 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2240 Decl->getAnonDeclWithTypedefName())
2241 continue;
2242 }
2243
2244 Filter.erase();
2245 }
2246
2247 Filter.done();
2248}
2249
2250bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2251 QualType OldType;
2252 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2253 OldType = OldTypedef->getUnderlyingType();
2254 else
2255 OldType = Context.getTypeDeclType(Old);
2256 QualType NewType = New->getUnderlyingType();
2257
2258 if (NewType->isVariablyModifiedType()) {
2259 // Must not redefine a typedef with a variably-modified type.
2260 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2261 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2262 << Kind << NewType;
2263 if (Old->getLocation().isValid())
2264 notePreviousDefinition(Old, New->getLocation());
2265 New->setInvalidDecl();
2266 return true;
2267 }
2268
2269 if (OldType != NewType &&
2270 !OldType->isDependentType() &&
2271 !NewType->isDependentType() &&
2272 !Context.hasSameType(OldType, NewType)) {
2273 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2274 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2275 << Kind << NewType << OldType;
2276 if (Old->getLocation().isValid())
2277 notePreviousDefinition(Old, New->getLocation());
2278 New->setInvalidDecl();
2279 return true;
2280 }
2281 return false;
2282}
2283
2284/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2285/// same name and scope as a previous declaration 'Old'. Figure out
2286/// how to resolve this situation, merging decls or emitting
2287/// diagnostics as appropriate. If there was an error, set New to be invalid.
2288///
2289void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2290 LookupResult &OldDecls) {
2291 // If the new decl is known invalid already, don't bother doing any
2292 // merging checks.
2293 if (New->isInvalidDecl()) return;
2294
2295 // Allow multiple definitions for ObjC built-in typedefs.
2296 // FIXME: Verify the underlying types are equivalent!
2297 if (getLangOpts().ObjC) {
2298 const IdentifierInfo *TypeID = New->getIdentifier();
2299 switch (TypeID->getLength()) {
2300 default: break;
2301 case 2:
2302 {
2303 if (!TypeID->isStr("id"))
2304 break;
2305 QualType T = New->getUnderlyingType();
2306 if (!T->isPointerType())
2307 break;
2308 if (!T->isVoidPointerType()) {
2309 QualType PT = T->castAs<PointerType>()->getPointeeType();
2310 if (!PT->isStructureType())
2311 break;
2312 }
2313 Context.setObjCIdRedefinitionType(T);
2314 // Install the built-in type for 'id', ignoring the current definition.
2315 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2316 return;
2317 }
2318 case 5:
2319 if (!TypeID->isStr("Class"))
2320 break;
2321 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2322 // Install the built-in type for 'Class', ignoring the current definition.
2323 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2324 return;
2325 case 3:
2326 if (!TypeID->isStr("SEL"))
2327 break;
2328 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2329 // Install the built-in type for 'SEL', ignoring the current definition.
2330 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2331 return;
2332 }
2333 // Fall through - the typedef name was not a builtin type.
2334 }
2335
2336 // Verify the old decl was also a type.
2337 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2338 if (!Old) {
2339 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2340 << New->getDeclName();
2341
2342 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2343 if (OldD->getLocation().isValid())
2344 notePreviousDefinition(OldD, New->getLocation());
2345
2346 return New->setInvalidDecl();
2347 }
2348
2349 // If the old declaration is invalid, just give up here.
2350 if (Old->isInvalidDecl())
2351 return New->setInvalidDecl();
2352
2353 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2354 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2355 auto *NewTag = New->getAnonDeclWithTypedefName();
2356 NamedDecl *Hidden = nullptr;
2357 if (OldTag && NewTag &&
2358 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2359 !hasVisibleDefinition(OldTag, &Hidden)) {
2360 // There is a definition of this tag, but it is not visible. Use it
2361 // instead of our tag.
2362 New->setTypeForDecl(OldTD->getTypeForDecl());
2363 if (OldTD->isModed())
2364 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2365 OldTD->getUnderlyingType());
2366 else
2367 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2368
2369 // Make the old tag definition visible.
2370 makeMergedDefinitionVisible(Hidden);
2371
2372 // If this was an unscoped enumeration, yank all of its enumerators
2373 // out of the scope.
2374 if (isa<EnumDecl>(NewTag)) {
2375 Scope *EnumScope = getNonFieldDeclScope(S);
2376 for (auto *D : NewTag->decls()) {
2377 auto *ED = cast<EnumConstantDecl>(D);
2378 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 2378, __extension__ __PRETTY_FUNCTION__))
;
2379 EnumScope->RemoveDecl(ED);
2380 IdResolver.RemoveDecl(ED);
2381 ED->getLexicalDeclContext()->removeDecl(ED);
2382 }
2383 }
2384 }
2385 }
2386
2387 // If the typedef types are not identical, reject them in all languages and
2388 // with any extensions enabled.
2389 if (isIncompatibleTypedef(Old, New))
2390 return;
2391
2392 // The types match. Link up the redeclaration chain and merge attributes if
2393 // the old declaration was a typedef.
2394 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2395 New->setPreviousDecl(Typedef);
2396 mergeDeclAttributes(New, Old);
2397 }
2398
2399 if (getLangOpts().MicrosoftExt)
2400 return;
2401
2402 if (getLangOpts().CPlusPlus) {
2403 // C++ [dcl.typedef]p2:
2404 // In a given non-class scope, a typedef specifier can be used to
2405 // redefine the name of any type declared in that scope to refer
2406 // to the type to which it already refers.
2407 if (!isa<CXXRecordDecl>(CurContext))
2408 return;
2409
2410 // C++0x [dcl.typedef]p4:
2411 // In a given class scope, a typedef specifier can be used to redefine
2412 // any class-name declared in that scope that is not also a typedef-name
2413 // to refer to the type to which it already refers.
2414 //
2415 // This wording came in via DR424, which was a correction to the
2416 // wording in DR56, which accidentally banned code like:
2417 //
2418 // struct S {
2419 // typedef struct A { } A;
2420 // };
2421 //
2422 // in the C++03 standard. We implement the C++0x semantics, which
2423 // allow the above but disallow
2424 //
2425 // struct S {
2426 // typedef int I;
2427 // typedef int I;
2428 // };
2429 //
2430 // since that was the intent of DR56.
2431 if (!isa<TypedefNameDecl>(Old))
2432 return;
2433
2434 Diag(New->getLocation(), diag::err_redefinition)
2435 << New->getDeclName();
2436 notePreviousDefinition(Old, New->getLocation());
2437 return New->setInvalidDecl();
2438 }
2439
2440 // Modules always permit redefinition of typedefs, as does C11.
2441 if (getLangOpts().Modules || getLangOpts().C11)
2442 return;
2443
2444 // If we have a redefinition of a typedef in C, emit a warning. This warning
2445 // is normally mapped to an error, but can be controlled with
2446 // -Wtypedef-redefinition. If either the original or the redefinition is
2447 // in a system header, don't emit this for compatibility with GCC.
2448 if (getDiagnostics().getSuppressSystemWarnings() &&
2449 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2450 (Old->isImplicit() ||
2451 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2452 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2453 return;
2454
2455 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2456 << New->getDeclName();
2457 notePreviousDefinition(Old, New->getLocation());
2458}
2459
2460/// DeclhasAttr - returns true if decl Declaration already has the target
2461/// attribute.
2462static bool DeclHasAttr(const Decl *D, const Attr *A) {
2463 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2464 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2465 for (const auto *i : D->attrs())
2466 if (i->getKind() == A->getKind()) {
2467 if (Ann) {
2468 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2469 return true;
2470 continue;
2471 }
2472 // FIXME: Don't hardcode this check
2473 if (OA && isa<OwnershipAttr>(i))
2474 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2475 return true;
2476 }
2477
2478 return false;
2479}
2480
2481static bool isAttributeTargetADefinition(Decl *D) {
2482 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2483 return VD->isThisDeclarationADefinition();
2484 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2485 return TD->isCompleteDefinition() || TD->isBeingDefined();
2486 return true;
2487}
2488
2489/// Merge alignment attributes from \p Old to \p New, taking into account the
2490/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2491///
2492/// \return \c true if any attributes were added to \p New.
2493static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2494 // Look for alignas attributes on Old, and pick out whichever attribute
2495 // specifies the strictest alignment requirement.
2496 AlignedAttr *OldAlignasAttr = nullptr;
2497 AlignedAttr *OldStrictestAlignAttr = nullptr;
2498 unsigned OldAlign = 0;
2499 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2500 // FIXME: We have no way of representing inherited dependent alignments
2501 // in a case like:
2502 // template<int A, int B> struct alignas(A) X;
2503 // template<int A, int B> struct alignas(B) X {};
2504 // For now, we just ignore any alignas attributes which are not on the
2505 // definition in such a case.
2506 if (I->isAlignmentDependent())
2507 return false;
2508
2509 if (I->isAlignas())
2510 OldAlignasAttr = I;
2511
2512 unsigned Align = I->getAlignment(S.Context);
2513 if (Align > OldAlign) {
2514 OldAlign = Align;
2515 OldStrictestAlignAttr = I;
2516 }
2517 }
2518
2519 // Look for alignas attributes on New.
2520 AlignedAttr *NewAlignasAttr = nullptr;
2521 unsigned NewAlign = 0;
2522 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2523 if (I->isAlignmentDependent())
2524 return false;
2525
2526 if (I->isAlignas())
2527 NewAlignasAttr = I;
2528
2529 unsigned Align = I->getAlignment(S.Context);
2530 if (Align > NewAlign)
2531 NewAlign = Align;
2532 }
2533
2534 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2535 // Both declarations have 'alignas' attributes. We require them to match.
2536 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2537 // fall short. (If two declarations both have alignas, they must both match
2538 // every definition, and so must match each other if there is a definition.)
2539
2540 // If either declaration only contains 'alignas(0)' specifiers, then it
2541 // specifies the natural alignment for the type.
2542 if (OldAlign == 0 || NewAlign == 0) {
2543 QualType Ty;
2544 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2545 Ty = VD->getType();
2546 else
2547 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2548
2549 if (OldAlign == 0)
2550 OldAlign = S.Context.getTypeAlign(Ty);
2551 if (NewAlign == 0)
2552 NewAlign = S.Context.getTypeAlign(Ty);
2553 }
2554
2555 if (OldAlign != NewAlign) {
2556 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2557 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2558 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2559 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2560 }
2561 }
2562
2563 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2564 // C++11 [dcl.align]p6:
2565 // if any declaration of an entity has an alignment-specifier,
2566 // every defining declaration of that entity shall specify an
2567 // equivalent alignment.
2568 // C11 6.7.5/7:
2569 // If the definition of an object does not have an alignment
2570 // specifier, any other declaration of that object shall also
2571 // have no alignment specifier.
2572 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2573 << OldAlignasAttr;
2574 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2575 << OldAlignasAttr;
2576 }
2577
2578 bool AnyAdded = false;
2579
2580 // Ensure we have an attribute representing the strictest alignment.
2581 if (OldAlign > NewAlign) {
2582 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2583 Clone->setInherited(true);
2584 New->addAttr(Clone);
2585 AnyAdded = true;
2586 }
2587
2588 // Ensure we have an alignas attribute if the old declaration had one.
2589 if (OldAlignasAttr && !NewAlignasAttr &&
2590 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2591 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2592 Clone->setInherited(true);
2593 New->addAttr(Clone);
2594 AnyAdded = true;
2595 }
2596
2597 return AnyAdded;
2598}
2599
2600#define WANT_DECL_MERGE_LOGIC
2601#include "clang/Sema/AttrParsedAttrImpl.inc"
2602#undef WANT_DECL_MERGE_LOGIC
2603
2604static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2605 const InheritableAttr *Attr,
2606 Sema::AvailabilityMergeKind AMK) {
2607 // Diagnose any mutual exclusions between the attribute that we want to add
2608 // and attributes that already exist on the declaration.
2609 if (!DiagnoseMutualExclusions(S, D, Attr))
2610 return false;
2611
2612 // This function copies an attribute Attr from a previous declaration to the
2613 // new declaration D if the new declaration doesn't itself have that attribute
2614 // yet or if that attribute allows duplicates.
2615 // If you're adding a new attribute that requires logic different from
2616 // "use explicit attribute on decl if present, else use attribute from
2617 // previous decl", for example if the attribute needs to be consistent
2618 // between redeclarations, you need to call a custom merge function here.
2619 InheritableAttr *NewAttr = nullptr;
2620 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2621 NewAttr = S.mergeAvailabilityAttr(
2622 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2623 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2624 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2625 AA->getPriority());
2626 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2627 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2628 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2629 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2630 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2631 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2632 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2633 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2634 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2635 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2636 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2637 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2638 FA->getFirstArg());
2639 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2640 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2641 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2642 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2643 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2644 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2645 IA->getInheritanceModel());
2646 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2647 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2648 &S.Context.Idents.get(AA->getSpelling()));
2649 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2650 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2651 isa<CUDAGlobalAttr>(Attr))) {
2652 // CUDA target attributes are part of function signature for
2653 // overloading purposes and must not be merged.
2654 return false;
2655 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2656 NewAttr = S.mergeMinSizeAttr(D, *MA);
2657 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2658 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2659 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2660 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2661 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2662 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2663 else if (isa<AlignedAttr>(Attr))
2664 // AlignedAttrs are handled separately, because we need to handle all
2665 // such attributes on a declaration at the same time.
2666 NewAttr = nullptr;
2667 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2668 (AMK == Sema::AMK_Override ||
2669 AMK == Sema::AMK_ProtocolImplementation ||
2670 AMK == Sema::AMK_OptionalProtocolImplementation))
2671 NewAttr = nullptr;
2672 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2673 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2674 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2675 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2676 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2677 NewAttr = S.mergeImportNameAttr(D, *INA);
2678 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2679 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2680 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2681 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2682 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr))
2683 NewAttr = S.mergeBTFTagAttr(D, *BTFA);
2684 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2685 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2686
2687 if (NewAttr) {
2688 NewAttr->setInherited(true);
2689 D->addAttr(NewAttr);
2690 if (isa<MSInheritanceAttr>(NewAttr))
2691 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2692 return true;
2693 }
2694
2695 return false;
2696}
2697
2698static const NamedDecl *getDefinition(const Decl *D) {
2699 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2700 return TD->getDefinition();
2701 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2702 const VarDecl *Def = VD->getDefinition();
2703 if (Def)
2704 return Def;
2705 return VD->getActingDefinition();
2706 }
2707 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2708 const FunctionDecl *Def = nullptr;
2709 if (FD->isDefined(Def, true))
2710 return Def;
2711 }
2712 return nullptr;
2713}
2714
2715static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2716 for (const auto *Attribute : D->attrs())
2717 if (Attribute->getKind() == Kind)
2718 return true;
2719 return false;
2720}
2721
2722/// checkNewAttributesAfterDef - If we already have a definition, check that
2723/// there are no new attributes in this declaration.
2724static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2725 if (!New->hasAttrs())
2726 return;
2727
2728 const NamedDecl *Def = getDefinition(Old);
2729 if (!Def || Def == New)
2730 return;
2731
2732 AttrVec &NewAttributes = New->getAttrs();
2733 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2734 const Attr *NewAttribute = NewAttributes[I];
2735
2736 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2738 Sema::SkipBodyInfo SkipBody;
2739 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2740
2741 // If we're skipping this definition, drop the "alias" attribute.
2742 if (SkipBody.ShouldSkip) {
2743 NewAttributes.erase(NewAttributes.begin() + I);
2744 --E;
2745 continue;
2746 }
2747 } else {
2748 VarDecl *VD = cast<VarDecl>(New);
2749 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2750 VarDecl::TentativeDefinition
2751 ? diag::err_alias_after_tentative
2752 : diag::err_redefinition;
2753 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2754 if (Diag == diag::err_redefinition)
2755 S.notePreviousDefinition(Def, VD->getLocation());
2756 else
2757 S.Diag(Def->getLocation(), diag::note_previous_definition);
2758 VD->setInvalidDecl();
2759 }
2760 ++I;
2761 continue;
2762 }
2763
2764 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2765 // Tentative definitions are only interesting for the alias check above.
2766 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2767 ++I;
2768 continue;
2769 }
2770 }
2771
2772 if (hasAttribute(Def, NewAttribute->getKind())) {
2773 ++I;
2774 continue; // regular attr merging will take care of validating this.
2775 }
2776
2777 if (isa<C11NoReturnAttr>(NewAttribute)) {
2778 // C's _Noreturn is allowed to be added to a function after it is defined.
2779 ++I;
2780 continue;
2781 } else if (isa<UuidAttr>(NewAttribute)) {
2782 // msvc will allow a subsequent definition to add an uuid to a class
2783 ++I;
2784 continue;
2785 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2786 if (AA->isAlignas()) {
2787 // C++11 [dcl.align]p6:
2788 // if any declaration of an entity has an alignment-specifier,
2789 // every defining declaration of that entity shall specify an
2790 // equivalent alignment.
2791 // C11 6.7.5/7:
2792 // If the definition of an object does not have an alignment
2793 // specifier, any other declaration of that object shall also
2794 // have no alignment specifier.
2795 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2796 << AA;
2797 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2798 << AA;
2799 NewAttributes.erase(NewAttributes.begin() + I);
2800 --E;
2801 continue;
2802 }
2803 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2804 // If there is a C definition followed by a redeclaration with this
2805 // attribute then there are two different definitions. In C++, prefer the
2806 // standard diagnostics.
2807 if (!S.getLangOpts().CPlusPlus) {
2808 S.Diag(NewAttribute->getLocation(),
2809 diag::err_loader_uninitialized_redeclaration);
2810 S.Diag(Def->getLocation(), diag::note_previous_definition);
2811 NewAttributes.erase(NewAttributes.begin() + I);
2812 --E;
2813 continue;
2814 }
2815 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2816 cast<VarDecl>(New)->isInline() &&
2817 !cast<VarDecl>(New)->isInlineSpecified()) {
2818 // Don't warn about applying selectany to implicitly inline variables.
2819 // Older compilers and language modes would require the use of selectany
2820 // to make such variables inline, and it would have no effect if we
2821 // honored it.
2822 ++I;
2823 continue;
2824 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2825 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2826 // declarations after defintions.
2827 ++I;
2828 continue;
2829 }
2830
2831 S.Diag(NewAttribute->getLocation(),
2832 diag::warn_attribute_precede_definition);
2833 S.Diag(Def->getLocation(), diag::note_previous_definition);
2834 NewAttributes.erase(NewAttributes.begin() + I);
2835 --E;
2836 }
2837}
2838
2839static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2840 const ConstInitAttr *CIAttr,
2841 bool AttrBeforeInit) {
2842 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2843
2844 // Figure out a good way to write this specifier on the old declaration.
2845 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2846 // enough of the attribute list spelling information to extract that without
2847 // heroics.
2848 std::string SuitableSpelling;
2849 if (S.getLangOpts().CPlusPlus20)
2850 SuitableSpelling = std::string(
2851 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2852 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2853 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2854 InsertLoc, {tok::l_square, tok::l_square,
2855 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2856 S.PP.getIdentifierInfo("require_constant_initialization"),
2857 tok::r_square, tok::r_square}));
2858 if (SuitableSpelling.empty())
2859 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2860 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2861 S.PP.getIdentifierInfo("require_constant_initialization"),
2862 tok::r_paren, tok::r_paren}));
2863 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2864 SuitableSpelling = "constinit";
2865 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2866 SuitableSpelling = "[[clang::require_constant_initialization]]";
2867 if (SuitableSpelling.empty())
2868 SuitableSpelling = "__attribute__((require_constant_initialization))";
2869 SuitableSpelling += " ";
2870
2871 if (AttrBeforeInit) {
2872 // extern constinit int a;
2873 // int a = 0; // error (missing 'constinit'), accepted as extension
2874 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 2874, __extension__ __PRETTY_FUNCTION__))
;
2875 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2876 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2877 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2878 } else {
2879 // int a = 0;
2880 // constinit extern int a; // error (missing 'constinit')
2881 S.Diag(CIAttr->getLocation(),
2882 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2883 : diag::warn_require_const_init_added_too_late)
2884 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2885 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2886 << CIAttr->isConstinit()
2887 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2888 }
2889}
2890
2891/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2892void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2893 AvailabilityMergeKind AMK) {
2894 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2895 UsedAttr *NewAttr = OldAttr->clone(Context);
2896 NewAttr->setInherited(true);
2897 New->addAttr(NewAttr);
2898 }
2899 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2900 RetainAttr *NewAttr = OldAttr->clone(Context);
2901 NewAttr->setInherited(true);
2902 New->addAttr(NewAttr);
2903 }
2904
2905 if (!Old->hasAttrs() && !New->hasAttrs())
2906 return;
2907
2908 // [dcl.constinit]p1:
2909 // If the [constinit] specifier is applied to any declaration of a
2910 // variable, it shall be applied to the initializing declaration.
2911 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2912 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2913 if (bool(OldConstInit) != bool(NewConstInit)) {
2914 const auto *OldVD = cast<VarDecl>(Old);
2915 auto *NewVD = cast<VarDecl>(New);
2916
2917 // Find the initializing declaration. Note that we might not have linked
2918 // the new declaration into the redeclaration chain yet.
2919 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2920 if (!InitDecl &&
2921 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2922 InitDecl = NewVD;
2923
2924 if (InitDecl == NewVD) {
2925 // This is the initializing declaration. If it would inherit 'constinit',
2926 // that's ill-formed. (Note that we do not apply this to the attribute
2927 // form).
2928 if (OldConstInit && OldConstInit->isConstinit())
2929 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2930 /*AttrBeforeInit=*/true);
2931 } else if (NewConstInit) {
2932 // This is the first time we've been told that this declaration should
2933 // have a constant initializer. If we already saw the initializing
2934 // declaration, this is too late.
2935 if (InitDecl && InitDecl != NewVD) {
2936 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2937 /*AttrBeforeInit=*/false);
2938 NewVD->dropAttr<ConstInitAttr>();
2939 }
2940 }
2941 }
2942
2943 // Attributes declared post-definition are currently ignored.
2944 checkNewAttributesAfterDef(*this, New, Old);
2945
2946 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2947 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2948 if (!OldA->isEquivalent(NewA)) {
2949 // This redeclaration changes __asm__ label.
2950 Diag(New->getLocation(), diag::err_different_asm_label);
2951 Diag(OldA->getLocation(), diag::note_previous_declaration);
2952 }
2953 } else if (Old->isUsed()) {
2954 // This redeclaration adds an __asm__ label to a declaration that has
2955 // already been ODR-used.
2956 Diag(New->getLocation(), diag::err_late_asm_label_name)
2957 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2958 }
2959 }
2960
2961 // Re-declaration cannot add abi_tag's.
2962 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2963 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2964 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2965 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2966 NewTag) == OldAbiTagAttr->tags_end()) {
2967 Diag(NewAbiTagAttr->getLocation(),
2968 diag::err_new_abi_tag_on_redeclaration)
2969 << NewTag;
2970 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2971 }
2972 }
2973 } else {
2974 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2975 Diag(Old->getLocation(), diag::note_previous_declaration);
2976 }
2977 }
2978
2979 // This redeclaration adds a section attribute.
2980 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2981 if (auto *VD = dyn_cast<VarDecl>(New)) {
2982 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2983 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2984 Diag(Old->getLocation(), diag::note_previous_declaration);
2985 }
2986 }
2987 }
2988
2989 // Redeclaration adds code-seg attribute.
2990 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2991 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2992 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2993 Diag(New->getLocation(), diag::warn_mismatched_section)
2994 << 0 /*codeseg*/;
2995 Diag(Old->getLocation(), diag::note_previous_declaration);
2996 }
2997
2998 if (!Old->hasAttrs())
2999 return;
3000
3001 bool foundAny = New->hasAttrs();
3002
3003 // Ensure that any moving of objects within the allocated map is done before
3004 // we process them.
3005 if (!foundAny) New->setAttrs(AttrVec());
3006
3007 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3008 // Ignore deprecated/unavailable/availability attributes if requested.
3009 AvailabilityMergeKind LocalAMK = AMK_None;
3010 if (isa<DeprecatedAttr>(I) ||
3011 isa<UnavailableAttr>(I) ||
3012 isa<AvailabilityAttr>(I)) {
3013 switch (AMK) {
3014 case AMK_None:
3015 continue;
3016
3017 case AMK_Redeclaration:
3018 case AMK_Override:
3019 case AMK_ProtocolImplementation:
3020 case AMK_OptionalProtocolImplementation:
3021 LocalAMK = AMK;
3022 break;
3023 }
3024 }
3025
3026 // Already handled.
3027 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3028 continue;
3029
3030 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3031 foundAny = true;
3032 }
3033
3034 if (mergeAlignedAttrs(*this, New, Old))
3035 foundAny = true;
3036
3037 if (!foundAny) New->dropAttrs();
3038}
3039
3040/// mergeParamDeclAttributes - Copy attributes from the old parameter
3041/// to the new one.
3042static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3043 const ParmVarDecl *oldDecl,
3044 Sema &S) {
3045 // C++11 [dcl.attr.depend]p2:
3046 // The first declaration of a function shall specify the
3047 // carries_dependency attribute for its declarator-id if any declaration
3048 // of the function specifies the carries_dependency attribute.
3049 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3050 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3051 S.Diag(CDA->getLocation(),
3052 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3053 // Find the first declaration of the parameter.
3054 // FIXME: Should we build redeclaration chains for function parameters?
3055 const FunctionDecl *FirstFD =
3056 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3057 const ParmVarDecl *FirstVD =
3058 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3059 S.Diag(FirstVD->getLocation(),
3060 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3061 }
3062
3063 if (!oldDecl->hasAttrs())
3064 return;
3065
3066 bool foundAny = newDecl->hasAttrs();
3067
3068 // Ensure that any moving of objects within the allocated map is
3069 // done before we process them.
3070 if (!foundAny) newDecl->setAttrs(AttrVec());
3071
3072 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3073 if (!DeclHasAttr(newDecl, I)) {
3074 InheritableAttr *newAttr =
3075 cast<InheritableParamAttr>(I->clone(S.Context));
3076 newAttr->setInherited(true);
3077 newDecl->addAttr(newAttr);
3078 foundAny = true;
3079 }
3080 }
3081
3082 if (!foundAny) newDecl->dropAttrs();
3083}
3084
3085static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3086 const ParmVarDecl *OldParam,
3087 Sema &S) {
3088 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3089 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3090 if (*Oldnullability != *Newnullability) {
3091 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3092 << DiagNullabilityKind(
3093 *Newnullability,
3094 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3095 != 0))
3096 << DiagNullabilityKind(
3097 *Oldnullability,
3098 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3099 != 0));
3100 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3101 }
3102 } else {
3103 QualType NewT = NewParam->getType();
3104 NewT = S.Context.getAttributedType(
3105 AttributedType::getNullabilityAttrKind(*Oldnullability),
3106 NewT, NewT);
3107 NewParam->setType(NewT);
3108 }
3109 }
3110}
3111
3112namespace {
3113
3114/// Used in MergeFunctionDecl to keep track of function parameters in
3115/// C.
3116struct GNUCompatibleParamWarning {
3117 ParmVarDecl *OldParm;
3118 ParmVarDecl *NewParm;
3119 QualType PromotedType;
3120};
3121
3122} // end anonymous namespace
3123
3124// Determine whether the previous declaration was a definition, implicit
3125// declaration, or a declaration.
3126template <typename T>
3127static std::pair<diag::kind, SourceLocation>
3128getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3129 diag::kind PrevDiag;
3130 SourceLocation OldLocation = Old->getLocation();
3131 if (Old->isThisDeclarationADefinition())
3132 PrevDiag = diag::note_previous_definition;
3133 else if (Old->isImplicit()) {
3134 PrevDiag = diag::note_previous_implicit_declaration;
3135 if (OldLocation.isInvalid())
3136 OldLocation = New->getLocation();
3137 } else
3138 PrevDiag = diag::note_previous_declaration;
3139 return std::make_pair(PrevDiag, OldLocation);
3140}
3141
3142/// canRedefineFunction - checks if a function can be redefined. Currently,
3143/// only extern inline functions can be redefined, and even then only in
3144/// GNU89 mode.
3145static bool canRedefineFunction(const FunctionDecl *FD,
3146 const LangOptions& LangOpts) {
3147 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3148 !LangOpts.CPlusPlus &&
3149 FD->isInlineSpecified() &&
3150 FD->getStorageClass() == SC_Extern);
3151}
3152
3153const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3154 const AttributedType *AT = T->getAs<AttributedType>();
3155 while (AT && !AT->isCallingConv())
3156 AT = AT->getModifiedType()->getAs<AttributedType>();
3157 return AT;
3158}
3159
3160template <typename T>
3161static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3162 const DeclContext *DC = Old->getDeclContext();
3163 if (DC->isRecord())
52
Calling 'DeclContext::isRecord'
55
Returning from 'DeclContext::isRecord'
56
Taking false branch
3164 return false;
3165
3166 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3167 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
57
Assuming 'OldLinkage' is not equal to CXXLanguageLinkage
3168 return true;
3169 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
58
Assuming 'OldLinkage' is not equal to CLanguageLinkage
3170 return true;
3171 return false;
59
Returning zero, which participates in a condition later
3172}
3173
3174template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3175static bool isExternC(VarTemplateDecl *) { return false; }
3176static bool isExternC(FunctionTemplateDecl *) { return false; }
3177
3178/// Check whether a redeclaration of an entity introduced by a
3179/// using-declaration is valid, given that we know it's not an overload
3180/// (nor a hidden tag declaration).
3181template<typename ExpectedDecl>
3182static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3183 ExpectedDecl *New) {
3184 // C++11 [basic.scope.declarative]p4:
3185 // Given a set of declarations in a single declarative region, each of
3186 // which specifies the same unqualified name,
3187 // -- they shall all refer to the same entity, or all refer to functions
3188 // and function templates; or
3189 // -- exactly one declaration shall declare a class name or enumeration
3190 // name that is not a typedef name and the other declarations shall all
3191 // refer to the same variable or enumerator, or all refer to functions
3192 // and function templates; in this case the class name or enumeration
3193 // name is hidden (3.3.10).
3194
3195 // C++11 [namespace.udecl]p14:
3196 // If a function declaration in namespace scope or block scope has the
3197 // same name and the same parameter-type-list as a function introduced
3198 // by a using-declaration, and the declarations do not declare the same
3199 // function, the program is ill-formed.
3200
3201 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3202 if (Old &&
3203 !Old->getDeclContext()->getRedeclContext()->Equals(
3204 New->getDeclContext()->getRedeclContext()) &&
3205 !(isExternC(Old) && isExternC(New)))
3206 Old = nullptr;
3207
3208 if (!Old) {
3209 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3210 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3211 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3212 return true;
3213 }
3214 return false;
3215}
3216
3217static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3218 const FunctionDecl *B) {
3219 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3219, __extension__ __PRETTY_FUNCTION__))
;
3220
3221 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3222 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3223 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3224 if (AttrA == AttrB)
3225 return true;
3226 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3227 AttrA->isDynamic() == AttrB->isDynamic();
3228 };
3229
3230 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3231}
3232
3233/// If necessary, adjust the semantic declaration context for a qualified
3234/// declaration to name the correct inline namespace within the qualifier.
3235static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3236 DeclaratorDecl *OldD) {
3237 // The only case where we need to update the DeclContext is when
3238 // redeclaration lookup for a qualified name finds a declaration
3239 // in an inline namespace within the context named by the qualifier:
3240 //
3241 // inline namespace N { int f(); }
3242 // int ::f(); // Sema DC needs adjusting from :: to N::.
3243 //
3244 // For unqualified declarations, the semantic context *can* change
3245 // along the redeclaration chain (for local extern declarations,
3246 // extern "C" declarations, and friend declarations in particular).
3247 if (!NewD->getQualifier())
4
Taking true branch
3248 return;
5
Returning without writing to 'OldD->InvalidDecl', which participates in a condition later
3249
3250 // NewD is probably already in the right context.
3251 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3252 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3253 if (NamedDC->Equals(SemaDC))
3254 return;
3255
3256 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3258, __extension__ __PRETTY_FUNCTION__))
3257 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3258, __extension__ __PRETTY_FUNCTION__))
3258 "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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3258, __extension__ __PRETTY_FUNCTION__))
;
3259
3260 auto *LexDC = NewD->getLexicalDeclContext();
3261 auto FixSemaDC = [=](NamedDecl *D) {
3262 if (!D)
3263 return;
3264 D->setDeclContext(SemaDC);
3265 D->setLexicalDeclContext(LexDC);
3266 };
3267
3268 FixSemaDC(NewD);
3269 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3270 FixSemaDC(FD->getDescribedFunctionTemplate());
3271 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3272 FixSemaDC(VD->getDescribedVarTemplate());
3273}
3274
3275/// MergeFunctionDecl - We just parsed a function 'New' from
3276/// declarator D which has the same name and scope as a previous
3277/// declaration 'Old'. Figure out how to resolve this situation,
3278/// merging decls or emitting diagnostics as appropriate.
3279///
3280/// In C++, New and Old must be declarations that are not
3281/// overloaded. Use IsOverload to determine whether New and Old are
3282/// overloaded, and to select the Old declaration that New should be
3283/// merged with.
3284///
3285/// Returns true if there was an error, false otherwise.
3286bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3287 Scope *S, bool MergeTypeWithOld) {
3288 // Verify the old decl was also a function.
3289 FunctionDecl *Old = OldD->getAsFunction();
3290 if (!Old) {
1
Assuming 'Old' is non-null
2
Taking false branch
3291 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3292 if (New->getFriendObjectKind()) {
3293 Diag(New->getLocation(), diag::err_using_decl_friend);
3294 Diag(Shadow->getTargetDecl()->getLocation(),
3295 diag::note_using_decl_target);
3296 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3297 << 0;
3298 return true;
3299 }
3300
3301 // Check whether the two declarations might declare the same function or
3302 // function template.
3303 if (FunctionTemplateDecl *NewTemplate =
3304 New->getDescribedFunctionTemplate()) {
3305 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3306 NewTemplate))
3307 return true;
3308 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3309 ->getAsFunction();
3310 } else {
3311 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3312 return true;
3313 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3314 }
3315 } else {
3316 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3317 << New->getDeclName();
3318 notePreviousDefinition(OldD, New->getLocation());
3319 return true;
3320 }
3321 }
3322
3323 // If the old declaration was found in an inline namespace and the new
3324 // declaration was qualified, update the DeclContext to match.
3325 adjustDeclContextForDeclaratorDecl(New, Old);
3
Calling 'adjustDeclContextForDeclaratorDecl'
6
Returning from 'adjustDeclContextForDeclaratorDecl'
3326
3327 // If the old declaration is invalid, just give up here.
3328 if (Old->isInvalidDecl())
7
Assuming the condition is false
8
Taking false branch
3329 return true;
3330
3331 // Disallow redeclaration of some builtins.
3332 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
9
Assuming the condition is false
10
Taking false branch
3333 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3334 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3335 << Old << Old->getType();
3336 return true;
3337 }
3338
3339 diag::kind PrevDiag;
3340 SourceLocation OldLocation;
3341 std::tie(PrevDiag, OldLocation) =
3342 getNoteDiagForInvalidRedeclaration(Old, New);
3343
3344 // Don't complain about this if we're in GNU89 mode and the old function
3345 // is an extern inline function.
3346 // Don't complain about specializations. They are not supposed to have
3347 // storage classes.
3348 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
11
Assuming 'New' is not a 'CXXMethodDecl'
12
Assuming 'Old' is not a 'CXXMethodDecl'
3349 New->getStorageClass() == SC_Static &&
13
Assuming the condition is false
3350 Old->hasExternalFormalLinkage() &&
3351 !New->getTemplateSpecializationInfo() &&
3352 !canRedefineFunction(Old, getLangOpts())) {
3353 if (getLangOpts().MicrosoftExt) {
3354 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3355 Diag(OldLocation, PrevDiag);
3356 } else {
3357 Diag(New->getLocation(), diag::err_static_non_static) << New;
3358 Diag(OldLocation, PrevDiag);
3359 return true;
3360 }
3361 }
3362
3363 if (const auto *ILA
13.1
'ILA' is null
13.1
'ILA' is null
= New->getAttr<InternalLinkageAttr>())
14
Taking false branch
3364 if (!Old->hasAttr<InternalLinkageAttr>()) {
3365 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3366 << ILA;
3367 Diag(Old->getLocation(), diag::note_previous_declaration);
3368 New->dropAttr<InternalLinkageAttr>();
3369 }
3370
3371 if (auto *EA
14.1
'EA' is null
14.1
'EA' is null
= New->getAttr<ErrorAttr>()) {
15
Taking false branch
3372 if (!Old->hasAttr<ErrorAttr>()) {
3373 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3374 Diag(Old->getLocation(), diag::note_previous_declaration);
3375 New->dropAttr<ErrorAttr>();
3376 }
3377 }
3378
3379 if (CheckRedeclarationModuleOwnership(New, Old))
16
Calling 'Sema::CheckRedeclarationModuleOwnership'
28
Returning from 'Sema::CheckRedeclarationModuleOwnership'
29
Taking false branch
3380 return true;
3381
3382 if (!getLangOpts().CPlusPlus) {
30
Assuming field 'CPlusPlus' is not equal to 0
31
Taking false branch
3383 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3384 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3385 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3386 << New << OldOvl;
3387
3388 // Try our best to find a decl that actually has the overloadable
3389 // attribute for the note. In most cases (e.g. programs with only one
3390 // broken declaration/definition), this won't matter.
3391 //
3392 // FIXME: We could do this if we juggled some extra state in
3393 // OverloadableAttr, rather than just removing it.
3394 const Decl *DiagOld = Old;
3395 if (OldOvl) {
3396 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3397 const auto *A = D->getAttr<OverloadableAttr>();
3398 return A && !A->isImplicit();
3399 });
3400 // If we've implicitly added *all* of the overloadable attrs to this
3401 // chain, emitting a "previous redecl" note is pointless.
3402 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3403 }
3404
3405 if (DiagOld)
3406 Diag(DiagOld->getLocation(),
3407 diag::note_attribute_overloadable_prev_overload)
3408 << OldOvl;
3409
3410 if (OldOvl)
3411 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3412 else
3413 New->dropAttr<OverloadableAttr>();
3414 }
3415 }
3416
3417 // If a function is first declared with a calling convention, but is later
3418 // declared or defined without one, all following decls assume the calling
3419 // convention of the first.
3420 //
3421 // It's OK if a function is first declared without a calling convention,
3422 // but is later declared or defined with the default calling convention.
3423 //
3424 // To test if either decl has an explicit calling convention, we look for
3425 // AttributedType sugar nodes on the type as written. If they are missing or
3426 // were canonicalized away, we assume the calling convention was implicit.
3427 //
3428 // Note also that we DO NOT return at this point, because we still have
3429 // other tests to run.
3430 QualType OldQType = Context.getCanonicalType(Old->getType());
3431 QualType NewQType = Context.getCanonicalType(New->getType());
3432 const FunctionType *OldType = cast<FunctionType>(OldQType);
3433 const FunctionType *NewType = cast<FunctionType>(NewQType);
3434 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3435 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3436 bool RequiresAdjustment = false;
3437
3438 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
32
Assuming the condition is false
3439 FunctionDecl *First = Old->getFirstDecl();
3440 const FunctionType *FT =
3441 First->getType().getCanonicalType()->castAs<FunctionType>();
3442 FunctionType::ExtInfo FI = FT->getExtInfo();
3443 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3444 if (!NewCCExplicit) {
3445 // Inherit the CC from the previous declaration if it was specified
3446 // there but not here.
3447 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3448 RequiresAdjustment = true;
3449 } else if (Old->getBuiltinID()) {
3450 // Builtin attribute isn't propagated to the new one yet at this point,
3451 // so we check if the old one is a builtin.
3452
3453 // Calling Conventions on a Builtin aren't really useful and setting a
3454 // default calling convention and cdecl'ing some builtin redeclarations is
3455 // common, so warn and ignore the calling convention on the redeclaration.
3456 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3457 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3458 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3459 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3460 RequiresAdjustment = true;
3461 } else {
3462 // Calling conventions aren't compatible, so complain.
3463 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3464 Diag(New->getLocation(), diag::err_cconv_change)
3465 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3466 << !FirstCCExplicit
3467 << (!FirstCCExplicit ? "" :
3468 FunctionType::getNameForCallConv(FI.getCC()));
3469
3470 // Put the note on the first decl, since it is the one that matters.
3471 Diag(First->getLocation(), diag::note_previous_declaration);
3472 return true;
3473 }
3474 }
3475
3476 // FIXME: diagnose the other way around?
3477 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
33
Assuming the condition is false
3478 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3479 RequiresAdjustment = true;
3480 }
3481
3482 // Merge regparm attribute.
3483 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
34
Taking false branch
3484 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3485 if (NewTypeInfo.getHasRegParm()) {
3486 Diag(New->getLocation(), diag::err_regparm_mismatch)
3487 << NewType->getRegParmType()
3488 << OldType->getRegParmType();
3489 Diag(OldLocation, diag::note_previous_declaration);
3490 return true;
3491 }
3492
3493 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3494 RequiresAdjustment = true;
3495 }
3496
3497 // Merge ns_returns_retained attribute.
3498 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
35
Assuming the condition is false
36
Taking false branch
3499 if (NewTypeInfo.getProducesResult()) {
3500 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3501 << "'ns_returns_retained'";
3502 Diag(OldLocation, diag::note_previous_declaration);
3503 return true;
3504 }
3505
3506 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3507 RequiresAdjustment = true;
3508 }
3509
3510 if (OldTypeInfo.getNoCallerSavedRegs() !=
37
Assuming the condition is false
38
Taking false branch
3511 NewTypeInfo.getNoCallerSavedRegs()) {
3512 if (NewTypeInfo.getNoCallerSavedRegs()) {
3513 AnyX86NoCallerSavedRegistersAttr *Attr =
3514 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3515 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3516 Diag(OldLocation, diag::note_previous_declaration);
3517 return true;
3518 }
3519
3520 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3521 RequiresAdjustment = true;
3522 }
3523
3524 if (RequiresAdjustment
38.1
'RequiresAdjustment' is false
38.1
'RequiresAdjustment' is false
) {
3525 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3526 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3527 New->setType(QualType(AdjustedType, 0));
3528 NewQType = Context.getCanonicalType(New->getType());
3529 }
3530
3531 // If this redeclaration makes the function inline, we may need to add it to
3532 // UndefinedButUsed.
3533 if (!Old->isInlined() && New->isInlined() &&
39
Assuming the condition is false
3534 !New->hasAttr<GNUInlineAttr>() &&
3535 !getLangOpts().GNUInline &&
3536 Old->isUsed(false) &&
3537 !Old->isDefined() && !New->isThisDeclarationADefinition())
3538 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3539 SourceLocation()));
3540
3541 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3542 // about it.
3543 if (New->hasAttr<GNUInlineAttr>() &&
3544 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3545 UndefinedButUsed.erase(Old->getCanonicalDecl());
3546 }
3547
3548 // If pass_object_size params don't match up perfectly, this isn't a valid
3549 // redeclaration.
3550 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
40
Assuming the condition is false
3551 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3552 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3553 << New->getDeclName();
3554 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3555 return true;
3556 }
3557
3558 if (getLangOpts().CPlusPlus
40.1
Field 'CPlusPlus' is not equal to 0
40.1
Field 'CPlusPlus' is not equal to 0
) {
41
Taking true branch
3559 // C++1z [over.load]p2
3560 // Certain function declarations cannot be overloaded:
3561 // -- Function declarations that differ only in the return type,
3562 // the exception specification, or both cannot be overloaded.
3563
3564 // Check the exception specifications match. This may recompute the type of
3565 // both Old and New if it resolved exception specifications, so grab the
3566 // types again after this. Because this updates the type, we do this before
3567 // any of the other checks below, which may update the "de facto" NewQType
3568 // but do not necessarily update the type of New.
3569 if (CheckEquivalentExceptionSpec(Old, New))
42
Assuming the condition is false
43
Taking false branch
3570 return true;
3571 OldQType = Context.getCanonicalType(Old->getType());
3572 NewQType = Context.getCanonicalType(New->getType());
3573
3574 // Go back to the type source info to compare the declared return types,
3575 // per C++1y [dcl.type.auto]p13:
3576 // Redeclarations or specializations of a function or function template
3577 // with a declared return type that uses a placeholder type shall also
3578 // use that placeholder, not a deduced type.
3579 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3580 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3581 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
44
Assuming the condition is false
3582 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3583 OldDeclaredReturnType)) {
3584 QualType ResQT;
3585 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3586 OldDeclaredReturnType->isObjCObjectPointerType())
3587 // FIXME: This does the wrong thing for a deduced return type.
3588 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3589 if (ResQT.isNull()) {
3590 if (New->isCXXClassMember() && New->isOutOfLine())
3591 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3592 << New << New->getReturnTypeSourceRange();
3593 else
3594 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3595 << New->getReturnTypeSourceRange();
3596 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3597 << Old->getReturnTypeSourceRange();
3598 return true;
3599 }
3600 else
3601 NewQType = ResQT;
3602 }
3603
3604 QualType OldReturnType = OldType->getReturnType();
3605 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3606 if (OldReturnType != NewReturnType) {
45
Taking false branch
3607 // If this function has a deduced return type and has already been
3608 // defined, copy the deduced value from the old declaration.
3609 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3610 if (OldAT && OldAT->isDeduced()) {
3611 New->setType(
3612 SubstAutoType(New->getType(),
3613 OldAT->isDependentType() ? Context.DependentTy
3614 : OldAT->getDeducedType()));
3615 NewQType = Context.getCanonicalType(
3616 SubstAutoType(NewQType,
3617 OldAT->isDependentType() ? Context.DependentTy
3618 : OldAT->getDeducedType()));
3619 }
3620 }
3621
3622 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
46
Assuming 'Old' is not a 'CXXMethodDecl'
3623 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
47
Assuming 'New' is not a 'CXXMethodDecl'
3624 if (OldMethod
47.1
'OldMethod' is null
47.1
'OldMethod' is null
&& NewMethod) {
3625 // Preserve triviality.
3626 NewMethod->setTrivial(OldMethod->isTrivial());
3627
3628 // MSVC allows explicit template specialization at class scope:
3629 // 2 CXXMethodDecls referring to the same function will be injected.
3630 // We don't want a redeclaration error.
3631 bool IsClassScopeExplicitSpecialization =
3632 OldMethod->isFunctionTemplateSpecialization() &&
3633 NewMethod->isFunctionTemplateSpecialization();
3634 bool isFriend = NewMethod->getFriendObjectKind();
3635
3636 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3637 !IsClassScopeExplicitSpecialization) {
3638 // -- Member function declarations with the same name and the
3639 // same parameter types cannot be overloaded if any of them
3640 // is a static member function declaration.
3641 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3642 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3643 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3644 return true;
3645 }
3646
3647 // C++ [class.mem]p1:
3648 // [...] A member shall not be declared twice in the
3649 // member-specification, except that a nested class or member
3650 // class template can be declared and then later defined.
3651 if (!inTemplateInstantiation()) {
3652 unsigned NewDiag;
3653 if (isa<CXXConstructorDecl>(OldMethod))
3654 NewDiag = diag::err_constructor_redeclared;
3655 else if (isa<CXXDestructorDecl>(NewMethod))
3656 NewDiag = diag::err_destructor_redeclared;
3657 else if (isa<CXXConversionDecl>(NewMethod))
3658 NewDiag = diag::err_conv_function_redeclared;
3659 else
3660 NewDiag = diag::err_member_redeclared;
3661
3662 Diag(New->getLocation(), NewDiag);
3663 } else {
3664 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3665 << New << New->getType();
3666 }
3667 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3668 return true;
3669
3670 // Complain if this is an explicit declaration of a special
3671 // member that was initially declared implicitly.
3672 //
3673 // As an exception, it's okay to befriend such methods in order
3674 // to permit the implicit constructor/destructor/operator calls.
3675 } else if (OldMethod->isImplicit()) {
3676 if (isFriend) {
3677 NewMethod->setImplicit();
3678 } else {
3679 Diag(NewMethod->getLocation(),
3680 diag::err_definition_of_implicitly_declared_member)
3681 << New << getSpecialMember(OldMethod);
3682 return true;
3683 }
3684 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3685 Diag(NewMethod->getLocation(),
3686 diag::err_definition_of_explicitly_defaulted_member)
3687 << getSpecialMember(OldMethod);
3688 return true;
3689 }
3690 }
3691
3692 // C++11 [dcl.attr.noreturn]p1:
3693 // The first declaration of a function shall specify the noreturn
3694 // attribute if any declaration of that function specifies the noreturn
3695 // attribute.
3696 if (const auto *NRA
47.2
'NRA' is null
47.2
'NRA' is null
= New->getAttr<CXX11NoReturnAttr>())
48
Taking false branch
3697 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3698 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3699 << NRA;
3700 Diag(Old->getLocation(), diag::note_previous_declaration);
3701 }
3702
3703 // C++11 [dcl.attr.depend]p2:
3704 // The first declaration of a function shall specify the
3705 // carries_dependency attribute for its declarator-id if any declaration
3706 // of the function specifies the carries_dependency attribute.
3707 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3708 if (CDA
48.1
'CDA' is null
48.1
'CDA' is null
&& !Old->hasAttr<CarriesDependencyAttr>()) {
3709 Diag(CDA->getLocation(),
3710 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3711 Diag(Old->getFirstDecl()->getLocation(),
3712 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3713 }
3714
3715 // (C++98 8.3.5p3):
3716 // All declarations for a function shall agree exactly in both the
3717 // return type and the parameter-type-list.
3718 // We also want to respect all the extended bits except noreturn.
3719
3720 // noreturn should now match unless the old type info didn't have it.
3721 QualType OldQTypeForComparison = OldQType;
3722 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
49
Assuming the condition is false
50
Taking false branch
3723 auto *OldType = OldQType->castAs<FunctionProtoType>();
3724 const FunctionType *OldTypeForComparison
3725 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3726 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3727 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3727, __extension__ __PRETTY_FUNCTION__))
;
3728 }
3729
3730 if (haveIncompatibleLanguageLinkages(Old, New)) {
51
Calling 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
60
Returning from 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
61
Taking false branch
3731 // As a special case, retain the language linkage from previous
3732 // declarations of a friend function as an extension.
3733 //
3734 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3735 // and is useful because there's otherwise no way to specify language
3736 // linkage within class scope.
3737 //
3738 // Check cautiously as the friend object kind isn't yet complete.
3739 if (New->getFriendObjectKind() != Decl::FOK_None) {
3740 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3741 Diag(OldLocation, PrevDiag);
3742 } else {
3743 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3744 Diag(OldLocation, PrevDiag);
3745 return true;
3746 }
3747 }
3748
3749 // If the function types are compatible, merge the declarations. Ignore the
3750 // exception specifier because it was already checked above in
3751 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3752 // about incompatible types under -fms-compatibility.
3753 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
62
Assuming the condition is false
63
Taking false branch
3754 NewQType))
3755 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3756
3757 // If the types are imprecise (due to dependent constructs in friends or
3758 // local extern declarations), it's OK if they differ. We'll check again
3759 // during instantiation.
3760 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
64
Calling 'Sema::canFullyTypeCheckRedeclaration'
68
Returning from 'Sema::canFullyTypeCheckRedeclaration'
3761 return false;
3762
3763 // Fall through for conflicting redeclarations and redefinitions.
3764 }
3765
3766 // C: Function types need to be compatible, not identical. This handles
3767 // duplicate function decls like "void f(int); void f(enum X);" properly.
3768 if (!getLangOpts().CPlusPlus &&
69
Assuming field 'CPlusPlus' is 0
71
Taking true branch
3769 Context.typesAreCompatible(OldQType, NewQType)) {
70
Assuming the condition is true
3770 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
72
Assuming the object is not a 'FunctionType'
3771 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
73
Assuming the object is not a 'FunctionType'
74
'NewFuncType' initialized to a null pointer value
3772 const FunctionProtoType *OldProto = nullptr;
3773 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
75
Assuming 'MergeTypeWithOld' is true
76
Assuming 'NewFuncType' is a 'FunctionNoProtoType'
3774 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
77
Assuming 'OldProto' is non-null
3775 // The old declaration provided a function prototype, but the
3776 // new declaration does not. Merge in the prototype.
3777 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3777, __extension__ __PRETTY_FUNCTION__))
;
78
Taking true branch
79
'?' condition is true
3778 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3779 NewQType =
3780 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
80
Called C++ object pointer is null
3781 OldProto->getExtProtoInfo());
3782 New->setType(NewQType);
3783 New->setHasInheritedPrototype();
3784
3785 // Synthesize parameters with the same types.
3786 SmallVector<ParmVarDecl*, 16> Params;
3787 for (const auto &ParamType : OldProto->param_types()) {
3788 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3789 SourceLocation(), nullptr,
3790 ParamType, /*TInfo=*/nullptr,
3791 SC_None, nullptr);
3792 Param->setScopeInfo(0, Params.size());
3793 Param->setImplicit();
3794 Params.push_back(Param);
3795 }
3796
3797 New->setParams(Params);
3798 }
3799
3800 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3801 }
3802
3803 // Check if the function types are compatible when pointer size address
3804 // spaces are ignored.
3805 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3806 return false;
3807
3808 // GNU C permits a K&R definition to follow a prototype declaration
3809 // if the declared types of the parameters in the K&R definition
3810 // match the types in the prototype declaration, even when the
3811 // promoted types of the parameters from the K&R definition differ
3812 // from the types in the prototype. GCC then keeps the types from
3813 // the prototype.
3814 //
3815 // If a variadic prototype is followed by a non-variadic K&R definition,
3816 // the K&R definition becomes variadic. This is sort of an edge case, but
3817 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3818 // C99 6.9.1p8.
3819 if (!getLangOpts().CPlusPlus &&
3820 Old->hasPrototype() && !New->hasPrototype() &&
3821 New->getType()->getAs<FunctionProtoType>() &&
3822 Old->getNumParams() == New->getNumParams()) {
3823 SmallVector<QualType, 16> ArgTypes;
3824 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3825 const FunctionProtoType *OldProto
3826 = Old->getType()->getAs<FunctionProtoType>();
3827 const FunctionProtoType *NewProto
3828 = New->getType()->getAs<FunctionProtoType>();
3829
3830 // Determine whether this is the GNU C extension.
3831 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3832 NewProto->getReturnType());
3833 bool LooseCompatible = !MergedReturn.isNull();
3834 for (unsigned Idx = 0, End = Old->getNumParams();
3835 LooseCompatible && Idx != End; ++Idx) {
3836 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3837 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3838 if (Context.typesAreCompatible(OldParm->getType(),
3839 NewProto->getParamType(Idx))) {
3840 ArgTypes.push_back(NewParm->getType());
3841 } else if (Context.typesAreCompatible(OldParm->getType(),
3842 NewParm->getType(),
3843 /*CompareUnqualified=*/true)) {
3844 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3845 NewProto->getParamType(Idx) };
3846 Warnings.push_back(Warn);
3847 ArgTypes.push_back(NewParm->getType());
3848 } else
3849 LooseCompatible = false;
3850 }
3851
3852 if (LooseCompatible) {
3853 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3854 Diag(Warnings[Warn].NewParm->getLocation(),
3855 diag::ext_param_promoted_not_compatible_with_prototype)
3856 << Warnings[Warn].PromotedType
3857 << Warnings[Warn].OldParm->getType();
3858 if (Warnings[Warn].OldParm->getLocation().isValid())
3859 Diag(Warnings[Warn].OldParm->getLocation(),
3860 diag::note_previous_declaration);
3861 }
3862
3863 if (MergeTypeWithOld)
3864 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3865 OldProto->getExtProtoInfo()));
3866 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3867 }
3868
3869 // Fall through to diagnose conflicting types.
3870 }
3871
3872 // A function that has already been declared has been redeclared or
3873 // defined with a different type; show an appropriate diagnostic.
3874
3875 // If the previous declaration was an implicitly-generated builtin
3876 // declaration, then at the very least we should use a specialized note.
3877 unsigned BuiltinID;
3878 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3879 // If it's actually a library-defined builtin function like 'malloc'
3880 // or 'printf', just warn about the incompatible redeclaration.
3881 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3882 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3883 Diag(OldLocation, diag::note_previous_builtin_declaration)
3884 << Old << Old->getType();
3885 return false;
3886 }
3887
3888 PrevDiag = diag::note_previous_builtin_declaration;
3889 }
3890
3891 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3892 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3893 return true;
3894}
3895
3896/// Completes the merge of two function declarations that are
3897/// known to be compatible.
3898///
3899/// This routine handles the merging of attributes and other
3900/// properties of function declarations from the old declaration to
3901/// the new declaration, once we know that New is in fact a
3902/// redeclaration of Old.
3903///
3904/// \returns false
3905bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3906 Scope *S, bool MergeTypeWithOld) {
3907 // Merge the attributes
3908 mergeDeclAttributes(New, Old);
3909
3910 // Merge "pure" flag.
3911 if (Old->isPure())
3912 New->setPure();
3913
3914 // Merge "used" flag.
3915 if (Old->getMostRecentDecl()->isUsed(false))
3916 New->setIsUsed();
3917
3918 // Merge attributes from the parameters. These can mismatch with K&R
3919 // declarations.
3920 if (New->getNumParams() == Old->getNumParams())
3921 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3922 ParmVarDecl *NewParam = New->getParamDecl(i);
3923 ParmVarDecl *OldParam = Old->getParamDecl(i);
3924 mergeParamDeclAttributes(NewParam, OldParam, *this);
3925 mergeParamDeclTypes(NewParam, OldParam, *this);
3926 }
3927
3928 if (getLangOpts().CPlusPlus)
3929 return MergeCXXFunctionDecl(New, Old, S);
3930
3931 // Merge the function types so the we get the composite types for the return
3932 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3933 // was visible.
3934 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3935 if (!Merged.isNull() && MergeTypeWithOld)
3936 New->setType(Merged);
3937
3938 return false;
3939}
3940
3941void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3942 ObjCMethodDecl *oldMethod) {
3943 // Merge the attributes, including deprecated/unavailable
3944 AvailabilityMergeKind MergeKind =
3945 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3946 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3947 : AMK_ProtocolImplementation)
3948 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3949 : AMK_Override;
3950
3951 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3952
3953 // Merge attributes from the parameters.
3954 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3955 oe = oldMethod->param_end();
3956 for (ObjCMethodDecl::param_iterator
3957 ni = newMethod->param_begin(), ne = newMethod->param_end();
3958 ni != ne && oi != oe; ++ni, ++oi)
3959 mergeParamDeclAttributes(*ni, *oi, *this);
3960
3961 CheckObjCMethodOverride(newMethod, oldMethod);
3962}
3963
3964static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3965 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 3965, __extension__ __PRETTY_FUNCTION__))
;
3966
3967 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3968 ? diag::err_redefinition_different_type
3969 : diag::err_redeclaration_different_type)
3970 << New->getDeclName() << New->getType() << Old->getType();
3971
3972 diag::kind PrevDiag;
3973 SourceLocation OldLocation;
3974 std::tie(PrevDiag, OldLocation)
3975 = getNoteDiagForInvalidRedeclaration(Old, New);
3976 S.Diag(OldLocation, PrevDiag);
3977 New->setInvalidDecl();
3978}
3979
3980/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3981/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3982/// emitting diagnostics as appropriate.
3983///
3984/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3985/// to here in AddInitializerToDecl. We can't check them before the initializer
3986/// is attached.
3987void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3988 bool MergeTypeWithOld) {
3989 if (New->isInvalidDecl() || Old->isInvalidDecl())
3990 return;
3991
3992 QualType MergedT;
3993 if (getLangOpts().CPlusPlus) {
3994 if (New->getType()->isUndeducedType()) {
3995 // We don't know what the new type is until the initializer is attached.
3996 return;
3997 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3998 // These could still be something that needs exception specs checked.
3999 return MergeVarDeclExceptionSpecs(New, Old);
4000 }
4001 // C++ [basic.link]p10:
4002 // [...] the types specified by all declarations referring to a given
4003 // object or function shall be identical, except that declarations for an
4004 // array object can specify array types that differ by the presence or
4005 // absence of a major array bound (8.3.4).
4006 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4007 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4008 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4009
4010 // We are merging a variable declaration New into Old. If it has an array
4011 // bound, and that bound differs from Old's bound, we should diagnose the
4012 // mismatch.
4013 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4014 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4015 PrevVD = PrevVD->getPreviousDecl()) {
4016 QualType PrevVDTy = PrevVD->getType();
4017 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4018 continue;
4019
4020 if (!Context.hasSameType(New->getType(), PrevVDTy))
4021 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4022 }
4023 }
4024
4025 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4026 if (Context.hasSameType(OldArray->getElementType(),
4027 NewArray->getElementType()))
4028 MergedT = New->getType();
4029 }
4030 // FIXME: Check visibility. New is hidden but has a complete type. If New
4031 // has no array bound, it should not inherit one from Old, if Old is not
4032 // visible.
4033 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4034 if (Context.hasSameType(OldArray->getElementType(),
4035 NewArray->getElementType()))
4036 MergedT = Old->getType();
4037 }
4038 }
4039 else if (New->getType()->isObjCObjectPointerType() &&
4040 Old->getType()->isObjCObjectPointerType()) {
4041 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4042 Old->getType());
4043 }
4044 } else {
4045 // C 6.2.7p2:
4046 // All declarations that refer to the same object or function shall have
4047 // compatible type.
4048 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4049 }
4050 if (MergedT.isNull()) {
4051 // It's OK if we couldn't merge types if either type is dependent, for a
4052 // block-scope variable. In other cases (static data members of class
4053 // templates, variable templates, ...), we require the types to be
4054 // equivalent.
4055 // FIXME: The C++ standard doesn't say anything about this.
4056 if ((New->getType()->isDependentType() ||
4057 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4058 // If the old type was dependent, we can't merge with it, so the new type
4059 // becomes dependent for now. We'll reproduce the original type when we
4060 // instantiate the TypeSourceInfo for the variable.
4061 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4062 New->setType(Context.DependentTy);
4063 return;
4064 }
4065 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4066 }
4067
4068 // Don't actually update the type on the new declaration if the old
4069 // declaration was an extern declaration in a different scope.
4070 if (MergeTypeWithOld)
4071 New->setType(MergedT);
4072}
4073
4074static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4075 LookupResult &Previous) {
4076 // C11 6.2.7p4:
4077 // For an identifier with internal or external linkage declared
4078 // in a scope in which a prior declaration of that identifier is
4079 // visible, if the prior declaration specifies internal or
4080 // external linkage, the type of the identifier at the later
4081 // declaration becomes the composite type.
4082 //
4083 // If the variable isn't visible, we do not merge with its type.
4084 if (Previous.isShadowed())
4085 return false;
4086
4087 if (S.getLangOpts().CPlusPlus) {
4088 // C++11 [dcl.array]p3:
4089 // If there is a preceding declaration of the entity in the same
4090 // scope in which the bound was specified, an omitted array bound
4091 // is taken to be the same as in that earlier declaration.
4092 return NewVD->isPreviousDeclInSameBlockScope() ||
4093 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4094 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4095 } else {
4096 // If the old declaration was function-local, don't merge with its
4097 // type unless we're in the same function.
4098 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4099 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4100 }
4101}
4102
4103/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4104/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4105/// situation, merging decls or emitting diagnostics as appropriate.
4106///
4107/// Tentative definition rules (C99 6.9.2p2) are checked by
4108/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4109/// definitions here, since the initializer hasn't been attached.
4110///
4111void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4112 // If the new decl is already invalid, don't do any other checking.
4113 if (New->isInvalidDecl())
4114 return;
4115
4116 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4117 return;
4118
4119 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4120
4121 // Verify the old decl was also a variable or variable template.
4122 VarDecl *Old = nullptr;
4123 VarTemplateDecl *OldTemplate = nullptr;
4124 if (Previous.isSingleResult()) {
4125 if (NewTemplate) {
4126 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4127 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4128
4129 if (auto *Shadow =
4130 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4131 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4132 return New->setInvalidDecl();
4133 } else {
4134 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4135
4136 if (auto *Shadow =
4137 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4138 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4139 return New->setInvalidDecl();
4140 }
4141 }
4142 if (!Old) {
4143 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4144 << New->getDeclName();
4145 notePreviousDefinition(Previous.getRepresentativeDecl(),
4146 New->getLocation());
4147 return New->setInvalidDecl();
4148 }
4149
4150 // If the old declaration was found in an inline namespace and the new
4151 // declaration was qualified, update the DeclContext to match.
4152 adjustDeclContextForDeclaratorDecl(New, Old);
4153
4154 // Ensure the template parameters are compatible.
4155 if (NewTemplate &&
4156 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4157 OldTemplate->getTemplateParameters(),
4158 /*Complain=*/true, TPL_TemplateMatch))
4159 return New->setInvalidDecl();
4160
4161 // C++ [class.mem]p1:
4162 // A member shall not be declared twice in the member-specification [...]
4163 //
4164 // Here, we need only consider static data members.
4165 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4166 Diag(New->getLocation(), diag::err_duplicate_member)
4167 << New->getIdentifier();
4168 Diag(Old->getLocation(), diag::note_previous_declaration);
4169 New->setInvalidDecl();
4170 }
4171
4172 mergeDeclAttributes(New, Old);
4173 // Warn if an already-declared variable is made a weak_import in a subsequent
4174 // declaration
4175 if (New->hasAttr<WeakImportAttr>() &&
4176 Old->getStorageClass() == SC_None &&
4177 !Old->hasAttr<WeakImportAttr>()) {
4178 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4179 Diag(Old->getLocation(), diag::note_previous_declaration);
4180 // Remove weak_import attribute on new declaration.
4181 New->dropAttr<WeakImportAttr>();
4182 }
4183
4184 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4185 if (!Old->hasAttr<InternalLinkageAttr>()) {
4186 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4187 << ILA;
4188 Diag(Old->getLocation(), diag::note_previous_declaration);
4189 New->dropAttr<InternalLinkageAttr>();
4190 }
4191
4192 // Merge the types.
4193 VarDecl *MostRecent = Old->getMostRecentDecl();
4194 if (MostRecent != Old) {
4195 MergeVarDeclTypes(New, MostRecent,
4196 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4197 if (New->isInvalidDecl())
4198 return;
4199 }
4200
4201 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4202 if (New->isInvalidDecl())
4203 return;
4204
4205 diag::kind PrevDiag;
4206 SourceLocation OldLocation;
4207 std::tie(PrevDiag, OldLocation) =
4208 getNoteDiagForInvalidRedeclaration(Old, New);
4209
4210 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4211 if (New->getStorageClass() == SC_Static &&
4212 !New->isStaticDataMember() &&
4213 Old->hasExternalFormalLinkage()) {
4214 if (getLangOpts().MicrosoftExt) {
4215 Diag(New->getLocation(), diag::ext_static_non_static)
4216 << New->getDeclName();
4217 Diag(OldLocation, PrevDiag);
4218 } else {
4219 Diag(New->getLocation(), diag::err_static_non_static)
4220 << New->getDeclName();
4221 Diag(OldLocation, PrevDiag);
4222 return New->setInvalidDecl();
4223 }
4224 }
4225 // C99 6.2.2p4:
4226 // For an identifier declared with the storage-class specifier
4227 // extern in a scope in which a prior declaration of that
4228 // identifier is visible,23) if the prior declaration specifies
4229 // internal or external linkage, the linkage of the identifier at
4230 // the later declaration is the same as the linkage specified at
4231 // the prior declaration. If no prior declaration is visible, or
4232 // if the prior declaration specifies no linkage, then the
4233 // identifier has external linkage.
4234 if (New->hasExternalStorage() && Old->hasLinkage())
4235 /* Okay */;
4236 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4237 !New->isStaticDataMember() &&
4238 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4239 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4240 Diag(OldLocation, PrevDiag);
4241 return New->setInvalidDecl();
4242 }
4243
4244 // Check if extern is followed by non-extern and vice-versa.
4245 if (New->hasExternalStorage() &&
4246 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4247 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4248 Diag(OldLocation, PrevDiag);
4249 return New->setInvalidDecl();
4250 }
4251 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4252 !New->hasExternalStorage()) {
4253 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4254 Diag(OldLocation, PrevDiag);
4255 return New->setInvalidDecl();
4256 }
4257
4258 if (CheckRedeclarationModuleOwnership(New, Old))
4259 return;
4260
4261 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4262
4263 // FIXME: The test for external storage here seems wrong? We still
4264 // need to check for mismatches.
4265 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4266 // Don't complain about out-of-line definitions of static members.
4267 !(Old->getLexicalDeclContext()->isRecord() &&
4268 !New->getLexicalDeclContext()->isRecord())) {
4269 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4270 Diag(OldLocation, PrevDiag);
4271 return New->setInvalidDecl();
4272 }
4273
4274 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4275 if (VarDecl *Def = Old->getDefinition()) {
4276 // C++1z [dcl.fcn.spec]p4:
4277 // If the definition of a variable appears in a translation unit before
4278 // its first declaration as inline, the program is ill-formed.
4279 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4280 Diag(Def->getLocation(), diag::note_previous_definition);
4281 }
4282 }
4283
4284 // If this redeclaration makes the variable inline, we may need to add it to
4285 // UndefinedButUsed.
4286 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4287 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4288 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4289 SourceLocation()));
4290
4291 if (New->getTLSKind() != Old->getTLSKind()) {
4292 if (!Old->getTLSKind()) {
4293 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4294 Diag(OldLocation, PrevDiag);
4295 } else if (!New->getTLSKind()) {
4296 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4297 Diag(OldLocation, PrevDiag);
4298 } else {
4299 // Do not allow redeclaration to change the variable between requiring
4300 // static and dynamic initialization.
4301 // FIXME: GCC allows this, but uses the TLS keyword on the first
4302 // declaration to determine the kind. Do we need to be compatible here?
4303 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4304 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4305 Diag(OldLocation, PrevDiag);
4306 }
4307 }
4308
4309 // C++ doesn't have tentative definitions, so go right ahead and check here.
4310 if (getLangOpts().CPlusPlus &&
4311 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4312 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4313 Old->getCanonicalDecl()->isConstexpr()) {
4314 // This definition won't be a definition any more once it's been merged.
4315 Diag(New->getLocation(),
4316 diag::warn_deprecated_redundant_constexpr_static_def);
4317 } else if (VarDecl *Def = Old->getDefinition()) {
4318 if (checkVarDeclRedefinition(Def, New))
4319 return;
4320 }
4321 }
4322
4323 if (haveIncompatibleLanguageLinkages(Old, New)) {
4324 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4325 Diag(OldLocation, PrevDiag);
4326 New->setInvalidDecl();
4327 return;
4328 }
4329
4330 // Merge "used" flag.
4331 if (Old->getMostRecentDecl()->isUsed(false))
4332 New->setIsUsed();
4333
4334 // Keep a chain of previous declarations.
4335 New->setPreviousDecl(Old);
4336 if (NewTemplate)
4337 NewTemplate->setPreviousDecl(OldTemplate);
4338
4339 // Inherit access appropriately.
4340 New->setAccess(Old->getAccess());
4341 if (NewTemplate)
4342 NewTemplate->setAccess(New->getAccess());
4343
4344 if (Old->isInline())
4345 New->setImplicitlyInline();
4346}
4347
4348void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4349 SourceManager &SrcMgr = getSourceManager();
4350 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4351 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4352 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4353 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4354 auto &HSI = PP.getHeaderSearchInfo();
4355 StringRef HdrFilename =
4356 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4357
4358 auto noteFromModuleOrInclude = [&](Module *Mod,
4359 SourceLocation IncLoc) -> bool {
4360 // Redefinition errors with modules are common with non modular mapped
4361 // headers, example: a non-modular header H in module A that also gets
4362 // included directly in a TU. Pointing twice to the same header/definition
4363 // is confusing, try to get better diagnostics when modules is on.
4364 if (IncLoc.isValid()) {
4365 if (Mod) {
4366 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4367 << HdrFilename.str() << Mod->getFullModuleName();
4368 if (!Mod->DefinitionLoc.isInvalid())
4369 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4370 << Mod->getFullModuleName();
4371 } else {
4372 Diag(IncLoc, diag::note_redefinition_include_same_file)
4373 << HdrFilename.str();
4374 }
4375 return true;
4376 }
4377
4378 return false;
4379 };
4380
4381 // Is it the same file and same offset? Provide more information on why
4382 // this leads to a redefinition error.
4383 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4384 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4385 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4386 bool EmittedDiag =
4387 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4388 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4389
4390 // If the header has no guards, emit a note suggesting one.
4391 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4392 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4393
4394 if (EmittedDiag)
4395 return;
4396 }
4397
4398 // Redefinition coming from different files or couldn't do better above.
4399 if (Old->getLocation().isValid())
4400 Diag(Old->getLocation(), diag::note_previous_definition);
4401}
4402
4403/// We've just determined that \p Old and \p New both appear to be definitions
4404/// of the same variable. Either diagnose or fix the problem.
4405bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4406 if (!hasVisibleDefinition(Old) &&
4407 (New->getFormalLinkage() == InternalLinkage ||
4408 New->isInline() ||
4409 New->getDescribedVarTemplate() ||
4410 New->getNumTemplateParameterLists() ||
4411 New->getDeclContext()->isDependentContext())) {
4412 // The previous definition is hidden, and multiple definitions are
4413 // permitted (in separate TUs). Demote this to a declaration.
4414 New->demoteThisDefinitionToDeclaration();
4415
4416 // Make the canonical definition visible.
4417 if (auto *OldTD = Old->getDescribedVarTemplate())
4418 makeMergedDefinitionVisible(OldTD);
4419 makeMergedDefinitionVisible(Old);
4420 return false;
4421 } else {
4422 Diag(New->getLocation(), diag::err_redefinition) << New;
4423 notePreviousDefinition(Old, New->getLocation());
4424 New->setInvalidDecl();
4425 return true;
4426 }
4427}
4428
4429/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4430/// no declarator (e.g. "struct foo;") is parsed.
4431Decl *
4432Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4433 RecordDecl *&AnonRecord) {
4434 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4435 AnonRecord);
4436}
4437
4438// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4439// disambiguate entities defined in different scopes.
4440// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4441// compatibility.
4442// We will pick our mangling number depending on which version of MSVC is being
4443// targeted.
4444static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4445 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4446 ? S->getMSCurManglingNumber()
4447 : S->getMSLastManglingNumber();
4448}
4449
4450void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4451 if (!Context.getLangOpts().CPlusPlus)
4452 return;
4453
4454 if (isa<CXXRecordDecl>(Tag->getParent())) {
4455 // If this tag is the direct child of a class, number it if
4456 // it is anonymous.
4457 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4458 return;
4459 MangleNumberingContext &MCtx =
4460 Context.getManglingNumberContext(Tag->getParent());
4461 Context.setManglingNumber(
4462 Tag, MCtx.getManglingNumber(
4463 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4464 return;
4465 }
4466
4467 // If this tag isn't a direct child of a class, number it if it is local.
4468 MangleNumberingContext *MCtx;
4469 Decl *ManglingContextDecl;
4470 std::tie(MCtx, ManglingContextDecl) =
4471 getCurrentMangleNumberContext(Tag->getDeclContext());
4472 if (MCtx) {
4473 Context.setManglingNumber(
4474 Tag, MCtx->getManglingNumber(
4475 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4476 }
4477}
4478
4479namespace {
4480struct NonCLikeKind {
4481 enum {
4482 None,
4483 BaseClass,
4484 DefaultMemberInit,
4485 Lambda,
4486 Friend,
4487 OtherMember,
4488 Invalid,
4489 } Kind = None;
4490 SourceRange Range;
4491
4492 explicit operator bool() { return Kind != None; }
4493};
4494}
4495
4496/// Determine whether a class is C-like, according to the rules of C++
4497/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4498static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4499 if (RD->isInvalidDecl())
4500 return {NonCLikeKind::Invalid, {}};
4501
4502 // C++ [dcl.typedef]p9: [P1766R1]
4503 // An unnamed class with a typedef name for linkage purposes shall not
4504 //
4505 // -- have any base classes
4506 if (RD->getNumBases())
4507 return {NonCLikeKind::BaseClass,
4508 SourceRange(RD->bases_begin()->getBeginLoc(),
4509 RD->bases_end()[-1].getEndLoc())};
4510 bool Invalid = false;
4511 for (Decl *D : RD->decls()) {
4512 // Don't complain about things we already diagnosed.
4513 if (D->isInvalidDecl()) {
4514 Invalid = true;
4515 continue;
4516 }
4517
4518 // -- have any [...] default member initializers
4519 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4520 if (FD->hasInClassInitializer()) {
4521 auto *Init = FD->getInClassInitializer();
4522 return {NonCLikeKind::DefaultMemberInit,
4523 Init ? Init->getSourceRange() : D->getSourceRange()};
4524 }
4525 continue;
4526 }
4527
4528 // FIXME: We don't allow friend declarations. This violates the wording of
4529 // P1766, but not the intent.
4530 if (isa<FriendDecl>(D))
4531 return {NonCLikeKind::Friend, D->getSourceRange()};
4532
4533 // -- declare any members other than non-static data members, member
4534 // enumerations, or member classes,
4535 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4536 isa<EnumDecl>(D))
4537 continue;
4538 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4539 if (!MemberRD) {
4540 if (D->isImplicit())
4541 continue;
4542 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4543 }
4544
4545 // -- contain a lambda-expression,
4546 if (MemberRD->isLambda())
4547 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4548
4549 // and all member classes shall also satisfy these requirements
4550 // (recursively).
4551 if (MemberRD->isThisDeclarationADefinition()) {
4552 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4553 return Kind;
4554 }
4555 }
4556
4557 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4558}
4559
4560void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4561 TypedefNameDecl *NewTD) {
4562 if (TagFromDeclSpec->isInvalidDecl())
4563 return;
4564
4565 // Do nothing if the tag already has a name for linkage purposes.
4566 if (TagFromDeclSpec->hasNameForLinkage())
4567 return;
4568
4569 // A well-formed anonymous tag must always be a TUK_Definition.
4570 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 4570, __extension__ __PRETTY_FUNCTION__))
;
4571
4572 // The type must match the tag exactly; no qualifiers allowed.
4573 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4574 Context.getTagDeclType(TagFromDeclSpec))) {
4575 if (getLangOpts().CPlusPlus)
4576 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4577 return;
4578 }
4579
4580 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4581 // An unnamed class with a typedef name for linkage purposes shall [be
4582 // C-like].
4583 //
4584 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4585 // shouldn't happen, but there are constructs that the language rule doesn't
4586 // disallow for which we can't reasonably avoid computing linkage early.
4587 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4588 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4589 : NonCLikeKind();
4590 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4591 if (NonCLike || ChangesLinkage) {
4592 if (NonCLike.Kind == NonCLikeKind::Invalid)
4593 return;
4594
4595 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4596 if (ChangesLinkage) {
4597 // If the linkage changes, we can't accept this as an extension.
4598 if (NonCLike.Kind == NonCLikeKind::None)
4599 DiagID = diag::err_typedef_changes_linkage;
4600 else
4601 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4602 }
4603
4604 SourceLocation FixitLoc =
4605 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4606 llvm::SmallString<40> TextToInsert;
4607 TextToInsert += ' ';
4608 TextToInsert += NewTD->getIdentifier()->getName();
4609
4610 Diag(FixitLoc, DiagID)
4611 << isa<TypeAliasDecl>(NewTD)
4612 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4613 if (NonCLike.Kind != NonCLikeKind::None) {
4614 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4615 << NonCLike.Kind - 1 << NonCLike.Range;
4616 }
4617 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4618 << NewTD << isa<TypeAliasDecl>(NewTD);
4619
4620 if (ChangesLinkage)
4621 return;
4622 }
4623
4624 // Otherwise, set this as the anon-decl typedef for the tag.
4625 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4626}
4627
4628static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4629 switch (T) {
4630 case DeclSpec::TST_class:
4631 return 0;
4632 case DeclSpec::TST_struct:
4633 return 1;
4634 case DeclSpec::TST_interface:
4635 return 2;
4636 case DeclSpec::TST_union:
4637 return 3;
4638 case DeclSpec::TST_enum:
4639 return 4;
4640 default:
4641 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 4641)
;
4642 }
4643}
4644
4645/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4646/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4647/// parameters to cope with template friend declarations.
4648Decl *
4649Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4650 MultiTemplateParamsArg TemplateParams,
4651 bool IsExplicitInstantiation,
4652 RecordDecl *&AnonRecord) {
4653 Decl *TagD = nullptr;
4654 TagDecl *Tag = nullptr;
4655 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4656 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4657 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4658 DS.getTypeSpecType() == DeclSpec::TST_union ||
4659 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4660 TagD = DS.getRepAsDecl();
4661
4662 if (!TagD) // We probably had an error
4663 return nullptr;
4664
4665 // Note that the above type specs guarantee that the
4666 // type rep is a Decl, whereas in many of the others
4667 // it's a Type.
4668 if (isa<TagDecl>(TagD))
4669 Tag = cast<TagDecl>(TagD);
4670 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4671 Tag = CTD->getTemplatedDecl();
4672 }
4673
4674 if (Tag) {
4675 handleTagNumbering(Tag, S);
4676 Tag->setFreeStanding();
4677 if (Tag->isInvalidDecl())
4678 return Tag;
4679 }
4680
4681 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4682 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4683 // or incomplete types shall not be restrict-qualified."
4684 if (TypeQuals & DeclSpec::TQ_restrict)
4685 Diag(DS.getRestrictSpecLoc(),
4686 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4687 << DS.getSourceRange();
4688 }
4689
4690 if (DS.isInlineSpecified())
4691 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4692 << getLangOpts().CPlusPlus17;
4693
4694 if (DS.hasConstexprSpecifier()) {
4695 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4696 // and definitions of functions and variables.
4697 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4698 // the declaration of a function or function template
4699 if (Tag)
4700 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4701 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4702 << static_cast<int>(DS.getConstexprSpecifier());
4703 else
4704 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4705 << static_cast<int>(DS.getConstexprSpecifier());
4706 // Don't emit warnings after this error.
4707 return TagD;
4708 }
4709
4710 DiagnoseFunctionSpecifiers(DS);
4711
4712 if (DS.isFriendSpecified()) {
4713 // If we're dealing with a decl but not a TagDecl, assume that
4714 // whatever routines created it handled the friendship aspect.
4715 if (TagD && !Tag)
4716 return nullptr;
4717 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4718 }
4719
4720 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4721 bool IsExplicitSpecialization =
4722 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4723 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4724 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4725 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4726 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4727 // nested-name-specifier unless it is an explicit instantiation
4728 // or an explicit specialization.
4729 //
4730 // FIXME: We allow class template partial specializations here too, per the
4731 // obvious intent of DR1819.
4732 //
4733 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4734 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4735 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4736 return nullptr;
4737 }
4738
4739 // Track whether this decl-specifier declares anything.
4740 bool DeclaresAnything = true;
4741
4742 // Handle anonymous struct definitions.
4743 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4744 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4745 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4746 if (getLangOpts().CPlusPlus ||
4747 Record->getDeclContext()->isRecord()) {
4748 // If CurContext is a DeclContext that can contain statements,
4749 // RecursiveASTVisitor won't visit the decls that
4750 // BuildAnonymousStructOrUnion() will put into CurContext.
4751 // Also store them here so that they can be part of the
4752 // DeclStmt that gets created in this case.
4753 // FIXME: Also return the IndirectFieldDecls created by
4754 // BuildAnonymousStructOr union, for the same reason?
4755 if (CurContext->isFunctionOrMethod())
4756 AnonRecord = Record;
4757 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4758 Context.getPrintingPolicy());
4759 }
4760
4761 DeclaresAnything = false;
4762 }
4763 }
4764
4765 // C11 6.7.2.1p2:
4766 // A struct-declaration that does not declare an anonymous structure or
4767 // anonymous union shall contain a struct-declarator-list.
4768 //
4769 // This rule also existed in C89 and C99; the grammar for struct-declaration
4770 // did not permit a struct-declaration without a struct-declarator-list.
4771 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4772 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4773 // Check for Microsoft C extension: anonymous struct/union member.
4774 // Handle 2 kinds of anonymous struct/union:
4775 // struct STRUCT;
4776 // union UNION;
4777 // and
4778 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4779 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4780 if ((Tag && Tag->getDeclName()) ||
4781 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4782 RecordDecl *Record = nullptr;
4783 if (Tag)
4784 Record = dyn_cast<RecordDecl>(Tag);
4785 else if (const RecordType *RT =
4786 DS.getRepAsType().get()->getAsStructureType())
4787 Record = RT->getDecl();
4788 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4789 Record = UT->getDecl();
4790
4791 if (Record && getLangOpts().MicrosoftExt) {
4792 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4793 << Record->isUnion() << DS.getSourceRange();
4794 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4795 }
4796
4797 DeclaresAnything = false;
4798 }
4799 }
4800
4801 // Skip all the checks below if we have a type error.
4802 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4803 (TagD && TagD->isInvalidDecl()))
4804 return TagD;
4805
4806 if (getLangOpts().CPlusPlus &&
4807 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4808 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4809 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4810 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4811 DeclaresAnything = false;
4812
4813 if (!DS.isMissingDeclaratorOk()) {
4814 // Customize diagnostic for a typedef missing a name.
4815 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4816 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4817 << DS.getSourceRange();
4818 else
4819 DeclaresAnything = false;
4820 }
4821
4822 if (DS.isModulePrivateSpecified() &&
4823 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4824 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4825 << Tag->getTagKind()
4826 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4827
4828 ActOnDocumentableDecl(TagD);
4829
4830 // C 6.7/2:
4831 // A declaration [...] shall declare at least a declarator [...], a tag,
4832 // or the members of an enumeration.
4833 // C++ [dcl.dcl]p3:
4834 // [If there are no declarators], and except for the declaration of an
4835 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4836 // names into the program, or shall redeclare a name introduced by a
4837 // previous declaration.
4838 if (!DeclaresAnything) {
4839 // In C, we allow this as a (popular) extension / bug. Don't bother
4840 // producing further diagnostics for redundant qualifiers after this.
4841 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4842 ? diag::err_no_declarators
4843 : diag::ext_no_declarators)
4844 << DS.getSourceRange();
4845 return TagD;
4846 }
4847
4848 // C++ [dcl.stc]p1:
4849 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4850 // init-declarator-list of the declaration shall not be empty.
4851 // C++ [dcl.fct.spec]p1:
4852 // If a cv-qualifier appears in a decl-specifier-seq, the
4853 // init-declarator-list of the declaration shall not be empty.
4854 //
4855 // Spurious qualifiers here appear to be valid in C.
4856 unsigned DiagID = diag::warn_standalone_specifier;
4857 if (getLangOpts().CPlusPlus)
4858 DiagID = diag::ext_standalone_specifier;
4859
4860 // Note that a linkage-specification sets a storage class, but
4861 // 'extern "C" struct foo;' is actually valid and not theoretically
4862 // useless.
4863 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4864 if (SCS == DeclSpec::SCS_mutable)
4865 // Since mutable is not a viable storage class specifier in C, there is
4866 // no reason to treat it as an extension. Instead, diagnose as an error.
4867 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4868 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4869 Diag(DS.getStorageClassSpecLoc(), DiagID)
4870 << DeclSpec::getSpecifierName(SCS);
4871 }
4872
4873 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4874 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4875 << DeclSpec::getSpecifierName(TSCS);
4876 if (DS.getTypeQualifiers()) {
4877 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4878 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4879 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4880 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4881 // Restrict is covered above.
4882 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4883 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4884 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4885 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4886 }
4887
4888 // Warn about ignored type attributes, for example:
4889 // __attribute__((aligned)) struct A;
4890 // Attributes should be placed after tag to apply to type declaration.
4891 if (!DS.getAttributes().empty()) {
4892 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4893 if (TypeSpecType == DeclSpec::TST_class ||
4894 TypeSpecType == DeclSpec::TST_struct ||
4895 TypeSpecType == DeclSpec::TST_interface ||
4896 TypeSpecType == DeclSpec::TST_union ||
4897 TypeSpecType == DeclSpec::TST_enum) {
4898 for (const ParsedAttr &AL : DS.getAttributes())
4899 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4900 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4901 }
4902 }
4903
4904 return TagD;
4905}
4906
4907/// We are trying to inject an anonymous member into the given scope;
4908/// check if there's an existing declaration that can't be overloaded.
4909///
4910/// \return true if this is a forbidden redeclaration
4911static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4912 Scope *S,
4913 DeclContext *Owner,
4914 DeclarationName Name,
4915 SourceLocation NameLoc,
4916 bool IsUnion) {
4917 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4918 Sema::ForVisibleRedeclaration);
4919 if (!SemaRef.LookupName(R, S)) return false;
4920
4921 // Pick a representative declaration.
4922 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4923 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 4923, __extension__ __PRETTY_FUNCTION__))
;
4924
4925 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4926 return false;
4927
4928 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4929 << IsUnion << Name;
4930 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4931
4932 return true;
4933}
4934
4935/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4936/// anonymous struct or union AnonRecord into the owning context Owner
4937/// and scope S. This routine will be invoked just after we realize
4938/// that an unnamed union or struct is actually an anonymous union or
4939/// struct, e.g.,
4940///
4941/// @code
4942/// union {
4943/// int i;
4944/// float f;
4945/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4946/// // f into the surrounding scope.x
4947/// @endcode
4948///
4949/// This routine is recursive, injecting the names of nested anonymous
4950/// structs/unions into the owning context and scope as well.
4951static bool
4952InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4953 RecordDecl *AnonRecord, AccessSpecifier AS,
4954 SmallVectorImpl<NamedDecl *> &Chaining) {
4955 bool Invalid = false;
4956
4957 // Look every FieldDecl and IndirectFieldDecl with a name.
4958 for (auto *D : AnonRecord->decls()) {
4959 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4960 cast<NamedDecl>(D)->getDeclName()) {
4961 ValueDecl *VD = cast<ValueDecl>(D);
4962 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4963 VD->getLocation(),
4964 AnonRecord->isUnion())) {
4965 // C++ [class.union]p2:
4966 // The names of the members of an anonymous union shall be
4967 // distinct from the names of any other entity in the
4968 // scope in which the anonymous union is declared.
4969 Invalid = true;
4970 } else {
4971 // C++ [class.union]p2:
4972 // For the purpose of name lookup, after the anonymous union
4973 // definition, the members of the anonymous union are
4974 // considered to have been defined in the scope in which the
4975 // anonymous union is declared.
4976 unsigned OldChainingSize = Chaining.size();
4977 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4978 Chaining.append(IF->chain_begin(), IF->chain_end());
4979 else
4980 Chaining.push_back(VD);
4981
4982 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 4982, __extension__ __PRETTY_FUNCTION__))
;
4983 NamedDecl **NamedChain =
4984 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4985 for (unsigned i = 0; i < Chaining.size(); i++)
4986 NamedChain[i] = Chaining[i];
4987
4988 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4989 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4990 VD->getType(), {NamedChain, Chaining.size()});
4991
4992 for (const auto *Attr : VD->attrs())
4993 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4994
4995 IndirectField->setAccess(AS);
4996 IndirectField->setImplicit();
4997 SemaRef.PushOnScopeChains(IndirectField, S);
4998
4999 // That includes picking up the appropriate access specifier.
5000 if (AS != AS_none) IndirectField->setAccess(AS);
5001
5002 Chaining.resize(OldChainingSize);
5003 }
5004 }
5005 }
5006
5007 return Invalid;
5008}
5009
5010/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5011/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5012/// illegal input values are mapped to SC_None.
5013static StorageClass
5014StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5015 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5016 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5017, __extension__ __PRETTY_FUNCTION__))
5017 "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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5017, __extension__ __PRETTY_FUNCTION__))
;
5018 switch (StorageClassSpec) {
5019 case DeclSpec::SCS_unspecified: return SC_None;
5020 case DeclSpec::SCS_extern:
5021 if (DS.isExternInLinkageSpec())
5022 return SC_None;
5023 return SC_Extern;
5024 case DeclSpec::SCS_static: return SC_Static;
5025 case DeclSpec::SCS_auto: return SC_Auto;
5026 case DeclSpec::SCS_register: return SC_Register;
5027 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5028 // Illegal SCSs map to None: error reporting is up to the caller.
5029 case DeclSpec::SCS_mutable: // Fall through.
5030 case DeclSpec::SCS_typedef: return SC_None;
5031 }
5032 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5032)
;
5033}
5034
5035static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5036 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5036, __extension__ __PRETTY_FUNCTION__))
;
5037
5038 for (const auto *I : Record->decls()) {
5039 const auto *FD = dyn_cast<FieldDecl>(I);
5040 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5041 FD = IFD->getAnonField();
5042 if (FD && FD->hasInClassInitializer())
5043 return FD->getLocation();
5044 }
5045
5046 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5046)
;
5047}
5048
5049static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5050 SourceLocation DefaultInitLoc) {
5051 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5052 return;
5053
5054 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5055 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5056}
5057
5058static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5059 CXXRecordDecl *AnonUnion) {
5060 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5061 return;
5062
5063 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5064}
5065
5066/// BuildAnonymousStructOrUnion - Handle the declaration of an
5067/// anonymous structure or union. Anonymous unions are a C++ feature
5068/// (C++ [class.union]) and a C11 feature; anonymous structures
5069/// are a C11 feature and GNU C++ extension.
5070Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5071 AccessSpecifier AS,
5072 RecordDecl *Record,
5073 const PrintingPolicy &Policy) {
5074 DeclContext *Owner = Record->getDeclContext();
5075
5076 // Diagnose whether this anonymous struct/union is an extension.
5077 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5078 Diag(Record->getLocation(), diag::ext_anonymous_union);
5079 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5080 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5081 else if (!Record->isUnion() && !getLangOpts().C11)
5082 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5083
5084 // C and C++ require different kinds of checks for anonymous
5085 // structs/unions.
5086 bool Invalid = false;
5087 if (getLangOpts().CPlusPlus) {
5088 const char *PrevSpec = nullptr;
5089 if (Record->isUnion()) {
5090 // C++ [class.union]p6:
5091 // C++17 [class.union.anon]p2:
5092 // Anonymous unions declared in a named namespace or in the
5093 // global namespace shall be declared static.
5094 unsigned DiagID;
5095 DeclContext *OwnerScope = Owner->getRedeclContext();
5096 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5097 (OwnerScope->isTranslationUnit() ||
5098 (OwnerScope->isNamespace() &&
5099 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5100 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5101 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5102
5103 // Recover by adding 'static'.
5104 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5105 PrevSpec, DiagID, Policy);
5106 }
5107 // C++ [class.union]p6:
5108 // A storage class is not allowed in a declaration of an
5109 // anonymous union in a class scope.
5110 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5111 isa<RecordDecl>(Owner)) {
5112 Diag(DS.getStorageClassSpecLoc(),
5113 diag::err_anonymous_union_with_storage_spec)
5114 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5115
5116 // Recover by removing the storage specifier.
5117 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5118 SourceLocation(),
5119 PrevSpec, DiagID, Context.getPrintingPolicy());
5120 }
5121 }
5122
5123 // Ignore const/volatile/restrict qualifiers.
5124 if (DS.getTypeQualifiers()) {
5125 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5126 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5127 << Record->isUnion() << "const"
5128 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5129 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5130 Diag(DS.getVolatileSpecLoc(),
5131 diag::ext_anonymous_struct_union_qualified)
5132 << Record->isUnion() << "volatile"
5133 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5134 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5135 Diag(DS.getRestrictSpecLoc(),
5136 diag::ext_anonymous_struct_union_qualified)
5137 << Record->isUnion() << "restrict"
5138 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5139 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5140 Diag(DS.getAtomicSpecLoc(),
5141 diag::ext_anonymous_struct_union_qualified)
5142 << Record->isUnion() << "_Atomic"
5143 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5144 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5145 Diag(DS.getUnalignedSpecLoc(),
5146 diag::ext_anonymous_struct_union_qualified)
5147 << Record->isUnion() << "__unaligned"
5148 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5149
5150 DS.ClearTypeQualifiers();
5151 }
5152
5153 // C++ [class.union]p2:
5154 // The member-specification of an anonymous union shall only
5155 // define non-static data members. [Note: nested types and
5156 // functions cannot be declared within an anonymous union. ]
5157 for (auto *Mem : Record->decls()) {
5158 // Ignore invalid declarations; we already diagnosed them.
5159 if (Mem->isInvalidDecl())
5160 continue;
5161
5162 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5163 // C++ [class.union]p3:
5164 // An anonymous union shall not have private or protected
5165 // members (clause 11).
5166 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5166, __extension__ __PRETTY_FUNCTION__))
;
5167 if (FD->getAccess() != AS_public) {
5168 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5169 << Record->isUnion() << (FD->getAccess() == AS_protected);
5170 Invalid = true;
5171 }
5172
5173 // C++ [class.union]p1
5174 // An object of a class with a non-trivial constructor, a non-trivial
5175 // copy constructor, a non-trivial destructor, or a non-trivial copy
5176 // assignment operator cannot be a member of a union, nor can an
5177 // array of such objects.
5178 if (CheckNontrivialField(FD))
5179 Invalid = true;
5180 } else if (Mem->isImplicit()) {
5181 // Any implicit members are fine.
5182 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5183 // This is a type that showed up in an
5184 // elaborated-type-specifier inside the anonymous struct or
5185 // union, but which actually declares a type outside of the
5186 // anonymous struct or union. It's okay.
5187 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5188 if (!MemRecord->isAnonymousStructOrUnion() &&
5189 MemRecord->getDeclName()) {
5190 // Visual C++ allows type definition in anonymous struct or union.
5191 if (getLangOpts().MicrosoftExt)
5192 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5193 << Record->isUnion();
5194 else {
5195 // This is a nested type declaration.
5196 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5197 << Record->isUnion();
5198 Invalid = true;
5199 }
5200 } else {
5201 // This is an anonymous type definition within another anonymous type.
5202 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5203 // not part of standard C++.
5204 Diag(MemRecord->getLocation(),
5205 diag::ext_anonymous_record_with_anonymous_type)
5206 << Record->isUnion();
5207 }
5208 } else if (isa<AccessSpecDecl>(Mem)) {
5209 // Any access specifier is fine.
5210 } else if (isa<StaticAssertDecl>(Mem)) {
5211 // In C++1z, static_assert declarations are also fine.
5212 } else {
5213 // We have something that isn't a non-static data
5214 // member. Complain about it.
5215 unsigned DK = diag::err_anonymous_record_bad_member;
5216 if (isa<TypeDecl>(Mem))
5217 DK = diag::err_anonymous_record_with_type;
5218 else if (isa<FunctionDecl>(Mem))
5219 DK = diag::err_anonymous_record_with_function;
5220 else if (isa<VarDecl>(Mem))
5221 DK = diag::err_anonymous_record_with_static;
5222
5223 // Visual C++ allows type definition in anonymous struct or union.
5224 if (getLangOpts().MicrosoftExt &&
5225 DK == diag::err_anonymous_record_with_type)
5226 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5227 << Record->isUnion();
5228 else {
5229 Diag(Mem->getLocation(), DK) << Record->isUnion();
5230 Invalid = true;
5231 }
5232 }
5233 }
5234
5235 // C++11 [class.union]p8 (DR1460):
5236 // At most one variant member of a union may have a
5237 // brace-or-equal-initializer.
5238 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5239 Owner->isRecord())
5240 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5241 cast<CXXRecordDecl>(Record));
5242 }
5243
5244 if (!Record->isUnion() && !Owner->isRecord()) {
5245 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5246 << getLangOpts().CPlusPlus;
5247 Invalid = true;
5248 }
5249
5250 // C++ [dcl.dcl]p3:
5251 // [If there are no declarators], and except for the declaration of an
5252 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5253 // names into the program
5254 // C++ [class.mem]p2:
5255 // each such member-declaration shall either declare at least one member
5256 // name of the class or declare at least one unnamed bit-field
5257 //
5258 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5259 if (getLangOpts().CPlusPlus && Record->field_empty())
5260 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5261
5262 // Mock up a declarator.
5263 Declarator Dc(DS, DeclaratorContext::Member);
5264 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5265 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5265, __extension__ __PRETTY_FUNCTION__))
;
5266
5267 // Create a declaration for this anonymous struct/union.
5268 NamedDecl *Anon = nullptr;
5269 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5270 Anon = FieldDecl::Create(
5271 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5272 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5273 /*BitWidth=*/nullptr, /*Mutable=*/false,
5274 /*InitStyle=*/ICIS_NoInit);
5275 Anon->setAccess(AS);
5276 ProcessDeclAttributes(S, Anon, Dc);
5277
5278 if (getLangOpts().CPlusPlus)
5279 FieldCollector->Add(cast<FieldDecl>(Anon));
5280 } else {
5281 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5282 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5283 if (SCSpec == DeclSpec::SCS_mutable) {
5284 // mutable can only appear on non-static class members, so it's always
5285 // an error here
5286 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5287 Invalid = true;
5288 SC = SC_None;
5289 }
5290
5291 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5291, __extension__ __PRETTY_FUNCTION__))
;
5292 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5293 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5294 Context.getTypeDeclType(Record), TInfo, SC);
5295
5296 // Default-initialize the implicit variable. This initialization will be
5297 // trivial in almost all cases, except if a union member has an in-class
5298 // initializer:
5299 // union { int n = 0; };
5300 if (!Invalid)
5301 ActOnUninitializedDecl(Anon);
5302 }
5303 Anon->setImplicit();
5304
5305 // Mark this as an anonymous struct/union type.
5306 Record->setAnonymousStructOrUnion(true);
5307
5308 // Add the anonymous struct/union object to the current
5309 // context. We'll be referencing this object when we refer to one of
5310 // its members.
5311 Owner->addDecl(Anon);
5312
5313 // Inject the members of the anonymous struct/union into the owning
5314 // context and into the identifier resolver chain for name lookup
5315 // purposes.
5316 SmallVector<NamedDecl*, 2> Chain;
5317 Chain.push_back(Anon);
5318
5319 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5320 Invalid = true;
5321
5322 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5323 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5324 MangleNumberingContext *MCtx;
5325 Decl *ManglingContextDecl;
5326 std::tie(MCtx, ManglingContextDecl) =
5327 getCurrentMangleNumberContext(NewVD->getDeclContext());
5328 if (MCtx) {
5329 Context.setManglingNumber(
5330 NewVD, MCtx->getManglingNumber(
5331 NewVD, getMSManglingNumber(getLangOpts(), S)));
5332 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5333 }
5334 }
5335 }
5336
5337 if (Invalid)
5338 Anon->setInvalidDecl();
5339
5340 return Anon;
5341}
5342
5343/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5344/// Microsoft C anonymous structure.
5345/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5346/// Example:
5347///
5348/// struct A { int a; };
5349/// struct B { struct A; int b; };
5350///
5351/// void foo() {
5352/// B var;
5353/// var.a = 3;
5354/// }
5355///
5356Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5357 RecordDecl *Record) {
5358 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5358, __extension__ __PRETTY_FUNCTION__))
;
5359
5360 // Mock up a declarator.
5361 Declarator Dc(DS, DeclaratorContext::TypeName);
5362 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5363 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~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5363, __extension__ __PRETTY_FUNCTION__))
;
5364
5365 auto *ParentDecl = cast<RecordDecl>(CurContext);
5366 QualType RecTy = Context.getTypeDeclType(Record);
5367
5368 // Create a declaration for this anonymous struct.
5369 NamedDecl *Anon =
5370 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5371 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5372 /*BitWidth=*/nullptr, /*Mutable=*/false,
5373 /*InitStyle=*/ICIS_NoInit);
5374 Anon->setImplicit();
5375
5376 // Add the anonymous struct object to the current context.
5377 CurContext->addDecl(Anon);
5378
5379 // Inject the members of the anonymous struct into the current
5380 // context and into the identifier resolver chain for name lookup
5381 // purposes.
5382 SmallVector<NamedDecl*, 2> Chain;
5383 Chain.push_back(Anon);
5384
5385 RecordDecl *RecordDef = Record->getDefinition();
5386 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5387 diag::err_field_incomplete_or_sizeless) ||
5388 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5389 AS_none, Chain)) {
5390 Anon->setInvalidDecl();
5391 ParentDecl->setInvalidDecl();
5392 }
5393
5394 return Anon;
5395}
5396
5397/// GetNameForDeclarator - Determine the full declaration name for the
5398/// given Declarator.
5399DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5400 return GetNameFromUnqualifiedId(D.getName());
5401}
5402
5403/// Retrieves the declaration name from a parsed unqualified-id.
5404DeclarationNameInfo
5405Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5406 DeclarationNameInfo NameInfo;
5407 NameInfo.setLoc(Name.StartLocation);
5408
5409 switch (Name.getKind()) {
5410
5411 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5412 case UnqualifiedIdKind::IK_Identifier:
5413 NameInfo.setName(Name.Identifier);
5414 return NameInfo;
5415
5416 case UnqualifiedIdKind::IK_DeductionGuideName: {
5417 // C++ [temp.deduct.guide]p3:
5418 // The simple-template-id shall name a class template specialization.
5419 // The template-name shall be the same identifier as the template-name
5420 // of the simple-template-id.
5421 // These together intend to imply that the template-name shall name a
5422 // class template.
5423 // FIXME: template<typename T> struct X {};
5424 // template<typename T> using Y = X<T>;
5425 // Y(int) -> Y<int>;
5426 // satisfies these rules but does not name a class template.
5427 TemplateName TN = Name.TemplateName.get().get();
5428 auto *Template = TN.getAsTemplateDecl();
5429 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5430 Diag(Name.StartLocation,
5431 diag::err_deduction_guide_name_not_class_template)
5432 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5433 if (Template)
5434 Diag(Template->getLocation(), diag::note_template_decl_here);
5435 return DeclarationNameInfo();
5436 }
5437
5438 NameInfo.setName(
5439 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5440 return NameInfo;
5441 }
5442
5443 case UnqualifiedIdKind::IK_OperatorFunctionId:
5444 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5445 Name.OperatorFunctionId.Operator));
5446 NameInfo.setCXXOperatorNameRange(SourceRange(
5447 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5448 return NameInfo;
5449
5450 case UnqualifiedIdKind::IK_LiteralOperatorId:
5451 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5452 Name.Identifier));
5453 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5454 return NameInfo;
5455
5456 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5457 TypeSourceInfo *TInfo;
5458 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5459 if (Ty.isNull())
5460 return DeclarationNameInfo();
5461 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5462 Context.getCanonicalType(Ty)));
5463 NameInfo.setNamedTypeInfo(TInfo);
5464 return NameInfo;
5465 }
5466
5467 case UnqualifiedIdKind::IK_ConstructorName: {
5468 TypeSourceInfo *TInfo;
5469 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5470 if (Ty.isNull())
5471 return DeclarationNameInfo();
5472 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5473 Context.getCanonicalType(Ty)));
5474 NameInfo.setNamedTypeInfo(TInfo);
5475 return NameInfo;
5476 }
5477
5478 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5479 // In well-formed code, we can only have a constructor
5480 // template-id that refers to the current context, so go there
5481 // to find the actual type being constructed.
5482 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5483 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5484 return DeclarationNameInfo();
5485
5486 // Determine the type of the class being constructed.
5487 QualType CurClassType = Context.getTypeDeclType(CurClass);
5488
5489 // FIXME: Check two things: that the template-id names the same type as
5490 // CurClassType, and that the template-id does not occur when the name
5491 // was qualified.
5492
5493 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5494 Context.getCanonicalType(CurClassType)));
5495 // FIXME: should we retrieve TypeSourceInfo?
5496 NameInfo.setNamedTypeInfo(nullptr);
5497 return NameInfo;
5498 }
5499
5500 case UnqualifiedIdKind::IK_DestructorName: {
5501 TypeSourceInfo *TInfo;
5502 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5503 if (Ty.isNull())
5504 return DeclarationNameInfo();
5505 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5506 Context.getCanonicalType(Ty)));
5507 NameInfo.setNamedTypeInfo(TInfo);
5508 return NameInfo;
5509 }
5510
5511 case UnqualifiedIdKind::IK_TemplateId: {
5512 TemplateName TName = Name.TemplateId->Template.get();
5513 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5514 return Context.getNameForTemplate(TName, TNameLoc);
5515 }
5516
5517 } // switch (Name.getKind())
5518
5519 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Sema/SemaDecl.cpp"
, 5519)
;
5520}
5521
5522static QualType getCoreType(QualType Ty) {
5523 do {
5524 if (Ty->isPointerType() || Ty->isReferenceType())
5525 Ty = Ty->getPointeeType();
5526 else if (Ty->isArrayType())
5527 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5528 else
5529 return Ty.withoutLocalFastQualifiers();
5530 } while (true);
5531}
5532
5533/// hasSimilarParameters - Determine whether the C++ functions Declaration
5534/// and Definition have "nearly" matching parameters. This heuristic is
5535/// used to improve diagnostics in the case where an out-of-line function
5536/// definition doesn't match any declaration within the class or namespace.
5537/// Also sets Params to the list of indices to the parameters that differ
5538/// between the declaration and the definition. If hasSimilarParameters
5539/// returns true and Params is empty, then all of the parameters match.
5540static bool hasSimilarParameters(ASTContext &Context,
5541 FunctionDecl *Declaration,
5542 FunctionDecl *Definition,
5543 SmallVectorImpl<unsigned> &Params) {
5544 Params.clear();
5545 if (Declaration->param_size() != Definition->param_size())
5546 return false;
5547 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5548 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5549 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5550
5551 // The parameter types are identical
5552 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5553 continue;
5554
5555 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5556 QualType DefParamBaseTy = getCoreType(DefParamTy);
5557 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5558 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5559
5560 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5561 (DeclTyName && DeclTyName == DefTyName))
5562 Params.push_back(Idx);
5563 else // The two parameters aren't even close
5564 return false;
5565 }
5566
5567 return true;
5568}
5569
5570/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5571/// declarator needs to be rebuilt in the current instantiation.
5572/// Any bits of declarator which appear before the name are valid for
5573/// consideration here. That's specifically the type in the decl spec
5574/// and the base type in any member-pointer chunks.
5575static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5576 DeclarationName Name) {
5577 // The types we specifically need to rebuild are:
5578 // - typenames, typeofs, and decltypes
5579 // - types which will become injected class names
5580 // Of course, we also need to rebuild any type referencing such a
5581 // type. It's safest to just say "dependent", but we call out a
5582 // few cases here.
5583
5584 DeclSpec &DS = D.getMutableDeclSpec();
5585 switch (DS.getTypeSpecType()) {
5586 case DeclSpec::TST_typename:
5587 case DeclSpec::TST_typeofType:
5588 case DeclSpec::TST_underlyingType:
5589 case DeclSpec::TST_atomic: {
5590 // Grab the type from the parser.
5591 TypeSourceInfo *TSI = nullptr;
5592 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5593 if (T.isNull() || !T->isInstantiationDependentType()) break;
5594
5595 // Make sure there's a type source info. This isn't really much
5596 // of a waste; most dependent types should have type source info
5597 // attached already.
5598 if (!TSI)
5599 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5600
5601 // Rebuild the type in the current instantiation.
5602 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5603 if (!TSI) return true;
5604
5605 // Store the new type back in the decl spec.
5606 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5607 DS.UpdateTypeRep(LocType);
5608 break;
5609 }
5610
5611 case DeclSpec::TST_decltype:
5612 case DeclSpec::TST_typeofExpr: {
5613 Expr *E = DS.getRepAsExpr();
5614 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5615 if (Result.isInvalid()) return true;
5616 DS.UpdateExprRep(Result.get());
5617 break;
5618 }
5619
5620 default:
5621 // Nothing to do for these decl specs.
5622 break;
5623 }
5624
5625 // It doesn't matter what order we do this in.
5626 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5627 DeclaratorChunk &Chunk = D.getTypeObject(I);
5628
5629 // The only type information in the declarator which can come
5630 // before the declaration name is the base type of a member
5631 // pointer.
5632 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5633 continue;
5634
5635 // Rebuild the scope specifier in-place.
5636 CXXScopeSpec &SS = Chunk.Mem.Scope();
5637 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5638 return true;
5639 }
5640
5641 return false;
5642}
5643
5644void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5645 // Avoid warning twice on the same identifier, and don't warn on redeclaration