Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 9907, column 19
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -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 /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/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-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~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/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_wchar_t:
145 case tok::kw_bool:
146 case tok::kw___underlying_type:
147 case tok::kw___auto_type:
148 return true;
149
150 case tok::annot_typename:
151 case tok::kw_char16_t:
152 case tok::kw_char32_t:
153 case tok::kw_typeof:
154 case tok::annot_decltype:
155 case tok::kw_decltype:
156 return getLangOpts().CPlusPlus;
157
158 case tok::kw_char8_t:
159 return getLangOpts().Char8;
160
161 default:
162 break;
163 }
164
165 return false;
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = nullptr;
191 if (auto *BaseTT = Base.getType()->getAs<TagType>())
192 BaseRD = BaseTT->getAsCXXRecordDecl();
193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST || !TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
257 // lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262 cast<Type>(Context.getRecordType(RD)));
263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
276/// If the identifier refers to a type name within this scope,
277/// return the declaration of that type.
278///
279/// This routine performs ordinary name lookup of the identifier II
280/// within the given scope, with optional C++ scope specifier SS, to
281/// determine whether the name refers to a type. If so, returns an
282/// opaque pointer (actually a QualType) corresponding to that
283/// type. Otherwise, returns NULL.
284ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285 Scope *S, CXXScopeSpec *SS,
286 bool isClassName, bool HasTrailingDot,
287 ParsedType ObjectTypePtr,
288 bool IsCtorOrDtorName,
289 bool WantNontrivialTypeSourceInfo,
290 bool IsClassTemplateDeductionContext,
291 IdentifierInfo **CorrectedII) {
292 // FIXME: Consider allowing this outside C++1z mode as an extension.
293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295 !isClassName && !HasTrailingDot;
296
297 // Determine where we will perform name lookup.
298 DeclContext *LookupCtx = nullptr;
299 if (ObjectTypePtr) {
300 QualType ObjectType = ObjectTypePtr.get();
301 if (ObjectType->isRecordType())
302 LookupCtx = computeDeclContext(ObjectType);
303 } else if (SS && SS->isNotEmpty()) {
304 LookupCtx = computeDeclContext(*SS, false);
305
306 if (!LookupCtx) {
307 if (isDependentScopeSpecifier(*SS)) {
308 // C++ [temp.res]p3:
309 // A qualified-id that refers to a type and in which the
310 // nested-name-specifier depends on a template-parameter (14.6.2)
311 // shall be prefixed by the keyword typename to indicate that the
312 // qualified-id denotes a type, forming an
313 // elaborated-type-specifier (7.1.5.3).
314 //
315 // We therefore do not perform any name lookup if the result would
316 // refer to a member of an unknown specialization.
317 if (!isClassName && !IsCtorOrDtorName)
318 return nullptr;
319
320 // We know from the grammar that this name refers to a type,
321 // so build a dependent node to describe the type.
322 if (WantNontrivialTypeSourceInfo)
323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327 II, NameLoc);
328 return ParsedType::make(T);
329 }
330
331 return nullptr;
332 }
333
334 if (!LookupCtx->isDependentContext() &&
335 RequireCompleteDeclContext(*SS, LookupCtx))
336 return nullptr;
337 }
338
339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340 // lookup for class-names.
341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342 LookupOrdinaryName;
343 LookupResult Result(*this, &II, NameLoc, Kind);
344 if (LookupCtx) {
345 // Perform "qualified" name lookup into the declaration context we
346 // computed, which is either the type of the base of a member access
347 // expression or the declaration context associated with a prior
348 // nested-name-specifier.
349 LookupQualifiedName(Result, LookupCtx);
350
351 if (ObjectTypePtr && Result.empty()) {
352 // C++ [basic.lookup.classref]p3:
353 // If the unqualified-id is ~type-name, the type-name is looked up
354 // in the context of the entire postfix-expression. If the type T of
355 // the object expression is of a class type C, the type-name is also
356 // looked up in the scope of class C. At least one of the lookups shall
357 // find a name that refers to (possibly cv-qualified) T.
358 LookupName(Result, S);
359 }
360 } else {
361 // Perform unqualified name lookup.
362 LookupName(Result, S);
363
364 // For unqualified lookup in a class template in MSVC mode, look into
365 // dependent base classes where the primary class template is known.
366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367 if (ParsedType TypeInBase =
368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369 return TypeInBase;
370 }
371 }
372
373 NamedDecl *IIDecl = nullptr;
374 switch (Result.getResultKind()) {
375 case LookupResult::NotFound:
376 case LookupResult::NotFoundInCurrentInstantiation:
377 if (CorrectedII) {
378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379 AllowDeducedTemplate);
380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381 S, SS, CCC, CTK_ErrorRecovery);
382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383 TemplateTy Template;
384 bool MemberOfUnknownSpecialization;
385 UnqualifiedId TemplateName;
386 TemplateName.setIdentifier(NewII, NameLoc);
387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388 CXXScopeSpec NewSS, *NewSSPtr = SS;
389 if (SS && NNS) {
390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391 NewSSPtr = &NewSS;
392 }
393 if (Correction && (NNS || NewII != &II) &&
394 // Ignore a correction to a template type as the to-be-corrected
395 // identifier is not a template (typo correction for template names
396 // is handled elsewhere).
397 !(getLangOpts().CPlusPlus && NewSSPtr &&
398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399 Template, MemberOfUnknownSpecialization))) {
400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401 isClassName, HasTrailingDot, ObjectTypePtr,
402 IsCtorOrDtorName,
403 WantNontrivialTypeSourceInfo,
404 IsClassTemplateDeductionContext);
405 if (Ty) {
406 diagnoseTypo(Correction,
407 PDiag(diag::err_unknown_type_or_class_name_suggest)
408 << Result.getLookupName() << isClassName);
409 if (SS && NNS)
410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411 *CorrectedII = NewII;
412 return Ty;
413 }
414 }
415 }
416 // If typo correction failed or was not performed, fall through
417 LLVM_FALLTHROUGH[[gnu::fallthrough]];
418 case LookupResult::FoundOverloaded:
419 case LookupResult::FoundUnresolvedValue:
420 Result.suppressDiagnostics();
421 return nullptr;
422
423 case LookupResult::Ambiguous:
424 // Recover from type-hiding ambiguities by hiding the type. We'll
425 // do the lookup again when looking for an object, and we can
426 // diagnose the error then. If we don't do this, then the error
427 // about hiding the type will be immediately followed by an error
428 // that only makes sense if the identifier was treated like a type.
429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430 Result.suppressDiagnostics();
431 return nullptr;
432 }
433
434 // Look to see if we have a type anywhere in the list of results.
435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436 Res != ResEnd; ++Res) {
437 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439 RealRes) ||
440 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
441 if (!IIDecl ||
442 // Make the selection of the recovery decl deterministic.
443 RealRes->getLocation() < IIDecl->getLocation())
444 IIDecl = RealRes;
445 }
446 }
447
448 if (!IIDecl) {
449 // None of the entities we found is a type, so there is no way
450 // to even assume that the result is a type. In this case, don't
451 // complain about the ambiguity. The parser will either try to
452 // perform this lookup again (e.g., as an object name), which
453 // will produce the ambiguity, or will complain that it expected
454 // a type name.
455 Result.suppressDiagnostics();
456 return nullptr;
457 }
458
459 // We found a type within the ambiguous lookup; diagnose the
460 // ambiguity and then return that type. This might be the right
461 // answer, or it might not be, but it suppresses any attempt to
462 // perform the name lookup again.
463 break;
464
465 case LookupResult::Found:
466 IIDecl = Result.getFoundDecl();
467 break;
468 }
469
470 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 470, __extension__ __PRETTY_FUNCTION__))
;
471
472 QualType T;
473 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474 // C++ [class.qual]p2: A lookup that would find the injected-class-name
475 // instead names the constructors of the class, except when naming a class.
476 // This is ill-formed when we're not actually forming a ctor or dtor name.
477 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
480 FoundRD->isInjectedClassName() &&
481 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
482 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483 << &II << /*Type*/1;
484
485 DiagnoseUseOfDecl(IIDecl, NameLoc);
486
487 T = Context.getTypeDeclType(TD);
488 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491 if (!HasTrailingDot)
492 T = Context.getObjCInterfaceType(IDecl);
493 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494 (void)DiagnoseUseOfDecl(UD, NameLoc);
495 // Recover with 'int'
496 T = Context.IntTy;
497 } else if (AllowDeducedTemplate) {
498 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500 QualType(), false);
501 }
502
503 if (T.isNull()) {
504 // If it's not plausibly a type, suppress diagnostics.
505 Result.suppressDiagnostics();
506 return nullptr;
507 }
508
509 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510 // constructor or destructor name (in such a case, the scope specifier
511 // will be attached to the enclosing Expr or Decl node).
512 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
513 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
514 if (WantNontrivialTypeSourceInfo) {
515 // Construct a type with type-source information.
516 TypeLocBuilder Builder;
517 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518
519 T = getElaboratedType(ETK_None, *SS, T);
520 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521 ElabTL.setElaboratedKeywordLoc(SourceLocation());
522 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524 } else {
525 T = getElaboratedType(ETK_None, *SS, T);
526 }
527 }
528
529 return ParsedType::make(T);
530}
531
532// Builds a fake NNS for the given decl context.
533static NestedNameSpecifier *
534synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535 for (;; DC = DC->getLookupParent()) {
536 DC = DC->getPrimaryContext();
537 auto *ND = dyn_cast<NamespaceDecl>(DC);
538 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
539 return NestedNameSpecifier::Create(Context, nullptr, ND);
540 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542 RD->getTypeForDecl());
543 else if (isa<TranslationUnitDecl>(DC))
544 return NestedNameSpecifier::GlobalSpecifier(Context);
545 }
546 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 546)
;
547}
548
549/// Find the parent class with dependent bases of the innermost enclosing method
550/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551/// up allowing unqualified dependent type names at class-level, which MSVC
552/// correctly rejects.
553static const CXXRecordDecl *
554findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
556 DC = DC->getPrimaryContext();
557 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558 if (MD->getParent()->hasAnyDependentBases())
559 return MD->getParent();
560 }
561 return nullptr;
562}
563
564ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565 SourceLocation NameLoc,
566 bool IsTemplateTypeArg) {
567 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568
569 NestedNameSpecifier *NNS = nullptr;
570 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
571 // If we weren't able to parse a default template argument, delay lookup
572 // until instantiation time by making a non-dependent DependentTypeName. We
573 // pretend we saw a NestedNameSpecifier referring to the current scope, and
574 // lookup is retried.
575 // FIXME: This hurts our diagnostic quality, since we get errors like "no
576 // type named 'Foo' in 'current_namespace'" when the user didn't write any
577 // name specifiers.
578 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580 } else if (const CXXRecordDecl *RD =
581 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582 // Build a DependentNameType that will perform lookup into RD at
583 // instantiation time.
584 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585 RD->getTypeForDecl());
586
587 // Diagnose that this identifier was undeclared, and retry the lookup during
588 // template instantiation.
589 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590 << RD;
591 } else {
592 // This is not a situation that we should recover from.
593 return ParsedType();
594 }
595
596 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597
598 // Build type location information. We synthesized the qualifier, so we have
599 // to build a fake NestedNameSpecifierLoc.
600 NestedNameSpecifierLocBuilder NNSLocBuilder;
601 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603
604 TypeLocBuilder Builder;
605 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606 DepTL.setNameLoc(NameLoc);
607 DepTL.setElaboratedKeywordLoc(SourceLocation());
608 DepTL.setQualifierLoc(QualifierLoc);
609 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610}
611
612/// isTagName() - This method is called *for error recovery purposes only*
613/// to determine if the specified name is a valid tag name ("struct foo"). If
614/// so, this returns the TST for the tag corresponding to it (TST_enum,
615/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
616/// cases in C where the user forgot to specify the tag.
617DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618 // Do a tag name lookup in this scope.
619 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620 LookupName(R, S, false);
621 R.suppressDiagnostics();
622 if (R.getResultKind() == LookupResult::Found)
623 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624 switch (TD->getTagKind()) {
625 case TTK_Struct: return DeclSpec::TST_struct;
626 case TTK_Interface: return DeclSpec::TST_interface;
627 case TTK_Union: return DeclSpec::TST_union;
628 case TTK_Class: return DeclSpec::TST_class;
629 case TTK_Enum: return DeclSpec::TST_enum;
630 }
631 }
632
633 return DeclSpec::TST_unspecified;
634}
635
636/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637/// if a CXXScopeSpec's type is equal to the type of one of the base classes
638/// then downgrade the missing typename error to a warning.
639/// This is needed for MSVC compatibility; Example:
640/// @code
641/// template<class T> class A {
642/// public:
643/// typedef int TYPE;
644/// };
645/// template<class T> class B : public A<T> {
646/// public:
647/// A<T>::TYPE a; // no typename required because A<T> is a base class.
648/// };
649/// @endcode
650bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651 if (CurContext->isRecord()) {
652 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653 return true;
654
655 const Type *Ty = SS->getScopeRep()->getAsType();
656
657 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658 for (const auto &Base : RD->bases())
659 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
660 return true;
661 return S->isFunctionPrototypeScope();
662 }
663 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
664}
665
666void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667 SourceLocation IILoc,
668 Scope *S,
669 CXXScopeSpec *SS,
670 ParsedType &SuggestedType,
671 bool IsTemplateName) {
672 // Don't report typename errors for editor placeholders.
673 if (II->isEditorPlaceholder())
674 return;
675 // We don't have anything to suggest (yet).
676 SuggestedType = nullptr;
677
678 // There may have been a typo in the name of the type. Look up typo
679 // results, in case we have something that we can suggest.
680 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681 /*AllowTemplates=*/IsTemplateName,
682 /*AllowNonTemplates=*/!IsTemplateName);
683 if (TypoCorrection Corrected =
684 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685 CCC, CTK_ErrorRecovery)) {
686 // FIXME: Support error recovery for the template-name case.
687 bool CanRecover = !IsTemplateName;
688 if (Corrected.isKeyword()) {
689 // We corrected to a keyword.
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II);
694 II = Corrected.getCorrectionAsIdentifierInfo();
695 } else {
696 // We found a similarly-named type or interface; suggest that.
697 if (!SS || !SS->isSet()) {
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName ? diag::err_no_template_suggest
700 : diag::err_unknown_typename_suggest)
701 << II, CanRecover);
702 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
703 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705 II->getName().equals(CorrectedStr);
706 diagnoseTypo(Corrected,
707 PDiag(IsTemplateName
708 ? diag::err_no_member_template_suggest
709 : diag::err_unknown_nested_typename_suggest)
710 << II << DC << DroppedSpecifier << SS->getRange(),
711 CanRecover);
712 } else {
713 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 713)
;
714 }
715
716 if (!CanRecover)
717 return;
718
719 CXXScopeSpec tmpSS;
720 if (Corrected.getCorrectionSpecifier())
721 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722 SourceRange(IILoc));
723 // FIXME: Support class template argument deduction here.
724 SuggestedType =
725 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
727 /*IsCtorOrDtorName=*/false,
728 /*WantNontrivialTypeSourceInfo=*/true);
729 }
730 return;
731 }
732
733 if (getLangOpts().CPlusPlus && !IsTemplateName) {
734 // See if II is a class template that the user forgot to pass arguments to.
735 UnqualifiedId Name;
736 Name.setIdentifier(II, IILoc);
737 CXXScopeSpec EmptySS;
738 TemplateTy TemplateResult;
739 bool MemberOfUnknownSpecialization;
740 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
741 Name, nullptr, true, TemplateResult,
742 MemberOfUnknownSpecialization) == TNK_Type_template) {
743 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744 return;
745 }
746 }
747
748 // FIXME: Should we move the logic that tries to recover from a missing tag
749 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750
751 if (!SS || (!SS->isSet() && !SS->isInvalid()))
752 Diag(IILoc, IsTemplateName ? diag::err_no_template
753 : diag::err_unknown_typename)
754 << II;
755 else if (DeclContext *DC = computeDeclContext(*SS, false))
756 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
757 : diag::err_typename_nested_not_found)
758 << II << DC << SS->getRange();
759 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
760 SuggestedType =
761 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762 } else if (isDependentScopeSpecifier(*SS)) {
763 unsigned DiagID = diag::err_typename_missing;
764 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
765 DiagID = diag::ext_typename_missing;
766
767 Diag(SS->getRange().getBegin(), DiagID)
768 << SS->getScopeRep() << II->getName()
769 << SourceRange(SS->getRange().getBegin(), IILoc)
770 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771 SuggestedType = ActOnTypenameType(S, SourceLocation(),
772 *SS, *II, IILoc).get();
773 } else {
774 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
775 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
;
776 }
777}
778
779/// Determine whether the given result set contains either a type name
780/// or
781static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783 NextToken.is(tok::less);
784
785 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
786 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
787 return true;
788
789 if (CheckTemplate && isa<TemplateDecl>(*I))
790 return true;
791 }
792
793 return false;
794}
795
796static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797 Scope *S, CXXScopeSpec &SS,
798 IdentifierInfo *&Name,
799 SourceLocation NameLoc) {
800 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801 SemaRef.LookupParsedName(R, S, &SS);
802 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803 StringRef FixItTagName;
804 switch (Tag->getTagKind()) {
805 case TTK_Class:
806 FixItTagName = "class ";
807 break;
808
809 case TTK_Enum:
810 FixItTagName = "enum ";
811 break;
812
813 case TTK_Struct:
814 FixItTagName = "struct ";
815 break;
816
817 case TTK_Interface:
818 FixItTagName = "__interface ";
819 break;
820
821 case TTK_Union:
822 FixItTagName = "union ";
823 break;
824 }
825
826 StringRef TagName = FixItTagName.drop_back();
827 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830
831 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832 I != IEnd; ++I)
833 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834 << Name << TagName;
835
836 // Replace lookup results with just the tag decl.
837 Result.clear(Sema::LookupTagName);
838 SemaRef.LookupParsedName(Result, S, &SS);
839 return true;
840 }
841
842 return false;
843}
844
845/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847 QualType T, SourceLocation NameLoc) {
848 ASTContext &Context = S.Context;
849
850 TypeLocBuilder Builder;
851 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852
853 T = S.getElaboratedType(ETK_None, SS, T);
854 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855 ElabTL.setElaboratedKeywordLoc(SourceLocation());
856 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
858}
859
860Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861 IdentifierInfo *&Name,
862 SourceLocation NameLoc,
863 const Token &NextToken,
864 CorrectionCandidateCallback *CCC) {
865 DeclarationNameInfo NameInfo(Name, NameLoc);
866 ObjCMethodDecl *CurMethod = getCurMethodDecl();
867
868 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 869, __extension__ __PRETTY_FUNCTION__))
869 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 869, __extension__ __PRETTY_FUNCTION__))
;
870 if (getLangOpts().CPlusPlus && SS.isSet() &&
871 isCurrentClassName(*Name, S, &SS)) {
872 // Per [class.qual]p2, this names the constructors of SS, not the
873 // injected-class-name. We don't have a classification for that.
874 // There's not much point caching this result, since the parser
875 // will reject it later.
876 return NameClassification::Unknown();
877 }
878
879 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880 LookupParsedName(Result, S, &SS, !CurMethod);
881
882 if (SS.isInvalid())
883 return NameClassification::Error();
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
900 return NameClassification::Error();
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
906 LookupBuiltin(Result);
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
914 case LookupResult::NotFound:
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
920 if (getLangOpts().CPlusPlus)
921 return NameClassification::UndeclaredNonType();
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension.
935 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936 return NameClassification::NonType(D);
937 }
938
939 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
940 // In C++20 onwards, this could be an ADL-only call to a function
941 // template, and we're required to assume that this is a template name.
942 //
943 // FIXME: Find a way to still do typo correction in this case.
944 TemplateName Template =
945 Context.getAssumedTemplateName(NameInfo.getName());
946 return NameClassification::UndeclaredTemplate(Template);
947 }
948
949 // In C, we first see whether there is a tag type by the same name, in
950 // which case it's likely that the user just forgot to write "enum",
951 // "struct", or "union".
952 if (!getLangOpts().CPlusPlus && !SecondTry &&
953 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
954 break;
955 }
956
957 // Perform typo correction to determine if there is another name that is
958 // close to this name.
959 if (!SecondTry && CCC) {
960 SecondTry = true;
961 if (TypoCorrection Corrected =
962 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963 &SS, *CCC, CTK_ErrorRecovery)) {
964 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965 unsigned QualifiedDiag = diag::err_no_member_suggest;
966
967 NamedDecl *FirstDecl = Corrected.getFoundDecl();
968 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
970 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
971 UnqualifiedDiag = diag::err_no_template_suggest;
972 QualifiedDiag = diag::err_no_member_template_suggest;
973 } else if (UnderlyingFirstDecl &&
974 (isa<TypeDecl>(UnderlyingFirstDecl) ||
975 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
976 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
977 UnqualifiedDiag = diag::err_unknown_typename_suggest;
978 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979 }
980
981 if (SS.isEmpty()) {
982 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983 } else {// FIXME: is this even reachable? Test it.
984 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986 Name->getName().equals(CorrectedStr);
987 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988 << Name << computeDeclContext(SS, false)
989 << DroppedSpecifier << SS.getRange());
990 }
991
992 // Update the name, so that the caller has the new name.
993 Name = Corrected.getCorrectionAsIdentifierInfo();
994
995 // Typo correction corrected to a keyword.
996 if (Corrected.isKeyword())
997 return Name;
998
999 // Also update the LookupResult...
1000 // FIXME: This should probably go away at some point
1001 Result.clear();
1002 Result.setLookupName(Corrected.getCorrection());
1003 if (FirstDecl)
1004 Result.addDecl(FirstDecl);
1005
1006 // If we found an Objective-C instance variable, let
1007 // LookupInObjCMethod build the appropriate expression to
1008 // reference the ivar.
1009 // FIXME: This is a gross hack.
1010 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011 DeclResult R =
1012 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013 if (R.isInvalid())
1014 return NameClassification::Error();
1015 if (R.isUsable())
1016 return NameClassification::NonType(Ivar);
1017 }
1018
1019 goto Corrected;
1020 }
1021 }
1022
1023 // We failed to correct; just fall through and let the parser deal with it.
1024 Result.suppressDiagnostics();
1025 return NameClassification::Unknown();
1026
1027 case LookupResult::NotFoundInCurrentInstantiation: {
1028 // We performed name lookup into the current instantiation, and there were
1029 // dependent bases, so we treat this result the same way as any other
1030 // dependent nested-name-specifier.
1031
1032 // C++ [temp.res]p2:
1033 // A name used in a template declaration or definition and that is
1034 // dependent on a template-parameter is assumed not to name a type
1035 // unless the applicable name lookup finds a type name or the name is
1036 // qualified by the keyword typename.
1037 //
1038 // FIXME: If the next token is '<', we might want to ask the parser to
1039 // perform some heroics to see if we actually have a
1040 // template-argument-list, which would indicate a missing 'template'
1041 // keyword here.
1042 return NameClassification::DependentNonType();
1043 }
1044
1045 case LookupResult::Found:
1046 case LookupResult::FoundOverloaded:
1047 case LookupResult::FoundUnresolvedValue:
1048 break;
1049
1050 case LookupResult::Ambiguous:
1051 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1052 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053 /*AllowDependent=*/false)) {
1054 // C++ [temp.local]p3:
1055 // A lookup that finds an injected-class-name (10.2) can result in an
1056 // ambiguity in certain cases (for example, if it is found in more than
1057 // one base class). If all of the injected-class-names that are found
1058 // refer to specializations of the same class template, and if the name
1059 // is followed by a template-argument-list, the reference refers to the
1060 // class template itself and not a specialization thereof, and is not
1061 // ambiguous.
1062 //
1063 // This filtering can make an ambiguous result into an unambiguous one,
1064 // so try again after filtering out template names.
1065 FilterAcceptableTemplateNames(Result);
1066 if (!Result.isAmbiguous()) {
1067 IsFilteredTemplateName = true;
1068 break;
1069 }
1070 }
1071
1072 // Diagnose the ambiguity and return an error.
1073 return NameClassification::Error();
1074 }
1075
1076 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077 (IsFilteredTemplateName ||
1078 hasAnyAcceptableTemplateNames(
1079 Result, /*AllowFunctionTemplates=*/true,
1080 /*AllowDependent=*/false,
1081 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082 getLangOpts().CPlusPlus20))) {
1083 // C++ [temp.names]p3:
1084 // After name lookup (3.4) finds that a name is a template-name or that
1085 // an operator-function-id or a literal- operator-id refers to a set of
1086 // overloaded functions any member of which is a function template if
1087 // this is followed by a <, the < is always taken as the delimiter of a
1088 // template-argument-list and never as the less-than operator.
1089 // C++2a [temp.names]p2:
1090 // A name is also considered to refer to a template if it is an
1091 // unqualified-id followed by a < and name lookup finds either one
1092 // or more functions or finds nothing.
1093 if (!IsFilteredTemplateName)
1094 FilterAcceptableTemplateNames(Result);
1095
1096 bool IsFunctionTemplate;
1097 bool IsVarTemplate;
1098 TemplateName Template;
1099 if (Result.end() - Result.begin() > 1) {
1100 IsFunctionTemplate = true;
1101 Template = Context.getOverloadedTemplateName(Result.begin(),
1102 Result.end());
1103 } else if (!Result.empty()) {
1104 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105 *Result.begin(), /*AllowFunctionTemplates=*/true,
1106 /*AllowDependent=*/false));
1107 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108 IsVarTemplate = isa<VarTemplateDecl>(TD);
1109
1110 if (SS.isNotEmpty())
1111 Template =
1112 Context.getQualifiedTemplateName(SS.getScopeRep(),
1113 /*TemplateKeyword=*/false, TD);
1114 else
1115 Template = TemplateName(TD);
1116 } else {
1117 // All results were non-template functions. This is a function template
1118 // name.
1119 IsFunctionTemplate = true;
1120 Template = Context.getAssumedTemplateName(NameInfo.getName());
1121 }
1122
1123 if (IsFunctionTemplate) {
1124 // Function templates always go through overload resolution, at which
1125 // point we'll perform the various checks (e.g., accessibility) we need
1126 // to based on which function we selected.
1127 Result.suppressDiagnostics();
1128
1129 return NameClassification::FunctionTemplate(Template);
1130 }
1131
1132 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133 : NameClassification::TypeTemplate(Template);
1134 }
1135
1136 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138 DiagnoseUseOfDecl(Type, NameLoc);
1139 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140 QualType T = Context.getTypeDeclType(Type);
1141 if (SS.isNotEmpty())
1142 return buildNestedType(*this, SS, T, NameLoc);
1143 return ParsedType::make(T);
1144 }
1145
1146 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147 if (!Class) {
1148 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149 if (ObjCCompatibleAliasDecl *Alias =
1150 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151 Class = Alias->getClassInterface();
1152 }
1153
1154 if (Class) {
1155 DiagnoseUseOfDecl(Class, NameLoc);
1156
1157 if (NextToken.is(tok::period)) {
1158 // Interface. <something> is parsed as a property reference expression.
1159 // Just return "unknown" as a fall-through for now.
1160 Result.suppressDiagnostics();
1161 return NameClassification::Unknown();
1162 }
1163
1164 QualType T = Context.getObjCInterfaceType(Class);
1165 return ParsedType::make(T);
1166 }
1167
1168 if (isa<ConceptDecl>(FirstDecl))
1169 return NameClassification::Concept(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174 return NameClassification::Error();
1175 }
1176
1177 // We can have a type template here if we're classifying a template argument.
1178 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1179 !isa<VarTemplateDecl>(FirstDecl))
1180 return NameClassification::TypeTemplate(
1181 TemplateName(cast<TemplateDecl>(FirstDecl)));
1182
1183 // Check for a tag type hidden by a non-type decl in a few cases where it
1184 // seems likely a type is wanted instead of the non-type that was found.
1185 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186 if ((NextToken.is(tok::identifier) ||
1187 (NextIsOp &&
1188 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1189 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1190 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191 DiagnoseUseOfDecl(Type, NameLoc);
1192 QualType T = Context.getTypeDeclType(Type);
1193 if (SS.isNotEmpty())
1194 return buildNestedType(*this, SS, T, NameLoc);
1195 return ParsedType::make(T);
1196 }
1197
1198 // If we already know which single declaration is referenced, just annotate
1199 // that declaration directly. Defer resolving even non-overloaded class
1200 // member accesses, as we need to defer certain access checks until we know
1201 // the context.
1202 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1204 return NameClassification::NonType(Result.getRepresentativeDecl());
1205
1206 // Otherwise, this is an overload set that we will need to resolve later.
1207 Result.suppressDiagnostics();
1208 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211 Result.begin(), Result.end()));
1212}
1213
1214ExprResult
1215Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216 SourceLocation NameLoc) {
1217 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1217, __extension__ __PRETTY_FUNCTION__))
;
1218 CXXScopeSpec SS;
1219 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221}
1222
1223ExprResult
1224Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225 IdentifierInfo *Name,
1226 SourceLocation NameLoc,
1227 bool IsAddressOfOperand) {
1228 DeclarationNameInfo NameInfo(Name, NameLoc);
1229 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230 NameInfo, IsAddressOfOperand,
1231 /*TemplateArgs=*/nullptr);
1232}
1233
1234ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235 NamedDecl *Found,
1236 SourceLocation NameLoc,
1237 const Token &NextToken) {
1238 if (getCurMethodDecl() && SS.isEmpty())
1239 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240 return BuildIvarRefExpr(S, NameLoc, Ivar);
1241
1242 // Reconstruct the lookup result.
1243 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244 Result.addDecl(Found);
1245 Result.resolveKind();
1246
1247 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248 return BuildDeclarationNameExpr(SS, Result, ADL);
1249}
1250
1251ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252 // For an implicit class member access, transform the result into a member
1253 // access expression if necessary.
1254 auto *ULE = cast<UnresolvedLookupExpr>(E);
1255 if ((*ULE->decls_begin())->isCXXClassMember()) {
1256 CXXScopeSpec SS;
1257 SS.Adopt(ULE->getQualifierLoc());
1258
1259 // Reconstruct the lookup result.
1260 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261 LookupOrdinaryName);
1262 Result.setNamingClass(ULE->getNamingClass());
1263 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1264 Result.addDecl(*I, I.getAccess());
1265 Result.resolveKind();
1266 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267 nullptr, S);
1268 }
1269
1270 // Otherwise, this is already in the form we needed, and no further checks
1271 // are necessary.
1272 return ULE;
1273}
1274
1275Sema::TemplateNameKindForDiagnostics
1276Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277 auto *TD = Name.getAsTemplateDecl();
1278 if (!TD)
1279 return TemplateNameKindForDiagnostics::DependentTemplate;
1280 if (isa<ClassTemplateDecl>(TD))
1281 return TemplateNameKindForDiagnostics::ClassTemplate;
1282 if (isa<FunctionTemplateDecl>(TD))
1283 return TemplateNameKindForDiagnostics::FunctionTemplate;
1284 if (isa<VarTemplateDecl>(TD))
1285 return TemplateNameKindForDiagnostics::VarTemplate;
1286 if (isa<TypeAliasTemplateDecl>(TD))
1287 return TemplateNameKindForDiagnostics::AliasTemplate;
1288 if (isa<TemplateTemplateParmDecl>(TD))
1289 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290 if (isa<ConceptDecl>(TD))
1291 return TemplateNameKindForDiagnostics::Concept;
1292 return TemplateNameKindForDiagnostics::DependentTemplate;
1293}
1294
1295void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1297 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 CurContext = DC;
1299 S->setEntity(DC);
1300}
1301
1302void Sema::PopDeclContext() {
1303 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1303, __extension__ __PRETTY_FUNCTION__))
;
1304
1305 CurContext = CurContext->getLexicalParent();
1306 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1306, __extension__ __PRETTY_FUNCTION__))
;
1307}
1308
1309Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310 Decl *D) {
1311 // Unlike PushDeclContext, the context to which we return is not necessarily
1312 // the containing DC of TD, because the new context will be some pre-existing
1313 // TagDecl definition instead of a fresh one.
1314 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315 CurContext = cast<TagDecl>(D)->getDefinition();
1316 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1316, __extension__ __PRETTY_FUNCTION__))
;
1317 // Start lookups from the parent of the current context; we don't want to look
1318 // into the pre-existing complete definition.
1319 S->setEntity(CurContext->getLookupParent());
1320 return Result;
1321}
1322
1323void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324 CurContext = static_cast<decltype(CurContext)>(Context);
1325}
1326
1327/// EnterDeclaratorContext - Used when we must lookup names in the context
1328/// of a declarator's nested name specifier.
1329///
1330void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331 // C++0x [basic.lookup.unqual]p13:
1332 // A name used in the definition of a static data member of class
1333 // X (after the qualified-id of the static member) is looked up as
1334 // if the name was used in a member function of X.
1335 // C++0x [basic.lookup.unqual]p14:
1336 // If a variable member of a namespace is defined outside of the
1337 // scope of its namespace then any name used in the definition of
1338 // the variable member (after the declarator-id) is looked up as
1339 // if the definition of the variable member occurred in its
1340 // namespace.
1341 // Both of these imply that we should push a scope whose context
1342 // is the semantic context of the declaration. We can't use
1343 // PushDeclContext here because that context is not necessarily
1344 // lexically contained in the current context. Fortunately,
1345 // the containing scope should have the appropriate information.
1346
1347 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1347, __extension__ __PRETTY_FUNCTION__))
;
1348
1349#ifndef NDEBUG
1350 Scope *Ancestor = S->getParent();
1351 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1352 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1352, __extension__ __PRETTY_FUNCTION__))
;
1353#endif
1354
1355 CurContext = DC;
1356 S->setEntity(DC);
1357
1358 if (S->getParent()->isTemplateParamScope()) {
1359 // Also set the corresponding entities for all immediately-enclosing
1360 // template parameter scopes.
1361 EnterTemplatedContext(S->getParent(), DC);
1362 }
1363}
1364
1365void Sema::ExitDeclaratorContext(Scope *S) {
1366 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1366, __extension__ __PRETTY_FUNCTION__))
;
1367
1368 // Switch back to the lexical context. The safety of this is
1369 // enforced by an assert in EnterDeclaratorContext.
1370 Scope *Ancestor = S->getParent();
1371 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372 CurContext = Ancestor->getEntity();
1373
1374 // We don't need to do anything with the scope, which is going to
1375 // disappear.
1376}
1377
1378void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1380, __extension__ __PRETTY_FUNCTION__))
1380 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1380, __extension__ __PRETTY_FUNCTION__))
;
1381
1382 // C++20 [temp.local]p7:
1383 // In the definition of a member of a class template that appears outside
1384 // of the class template definition, the name of a member of the class
1385 // template hides the name of a template-parameter of any enclosing class
1386 // templates (but not a template-parameter of the member if the member is a
1387 // class or function template).
1388 // C++20 [temp.local]p9:
1389 // In the definition of a class template or in the definition of a member
1390 // of such a template that appears outside of the template definition, for
1391 // each non-dependent base class (13.8.2.1), if the name of the base class
1392 // or the name of a member of the base class is the same as the name of a
1393 // template-parameter, the base class name or member name hides the
1394 // template-parameter name (6.4.10).
1395 //
1396 // This means that a template parameter scope should be searched immediately
1397 // after searching the DeclContext for which it is a template parameter
1398 // scope. For example, for
1399 // template<typename T> template<typename U> template<typename V>
1400 // void N::A<T>::B<U>::f(...)
1401 // we search V then B<U> (and base classes) then U then A<T> (and base
1402 // classes) then T then N then ::.
1403 unsigned ScopeDepth = getTemplateDepth(S);
1404 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1405 DeclContext *SearchDCAfterScope = DC;
1406 for (; DC; DC = DC->getLookupParent()) {
1407 if (const TemplateParameterList *TPL =
1408 cast<Decl>(DC)->getDescribedTemplateParams()) {
1409 unsigned DCDepth = TPL->getDepth() + 1;
1410 if (DCDepth > ScopeDepth)
1411 continue;
1412 if (ScopeDepth == DCDepth)
1413 SearchDCAfterScope = DC = DC->getLookupParent();
1414 break;
1415 }
1416 }
1417 S->setLookupEntity(SearchDCAfterScope);
1418 }
1419}
1420
1421void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422 // We assume that the caller has already called
1423 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424 FunctionDecl *FD = D->getAsFunction();
1425 if (!FD)
1426 return;
1427
1428 // Same implementation as PushDeclContext, but enters the context
1429 // from the lexical parent, rather than the top-level class.
1430 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
1431 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
;
1432 CurContext = FD;
1433 S->setEntity(CurContext);
1434
1435 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1436 ParmVarDecl *Param = FD->getParamDecl(P);
1437 // If the parameter has an identifier, then add it to the scope
1438 if (Param->getIdentifier()) {
1439 S->AddDecl(Param);
1440 IdResolver.AddDecl(Param);
1441 }
1442 }
1443}
1444
1445void Sema::ActOnExitFunctionContext() {
1446 // Same implementation as PopDeclContext, but returns to the lexical parent,
1447 // rather than the top-level class.
1448 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1448, __extension__ __PRETTY_FUNCTION__))
;
1449 CurContext = CurContext->getLexicalParent();
1450 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1450, __extension__ __PRETTY_FUNCTION__))
;
1451}
1452
1453/// Determine whether we allow overloading of the function
1454/// PrevDecl with another declaration.
1455///
1456/// This routine determines whether overloading is possible, not
1457/// whether some new function is actually an overload. It will return
1458/// true in C++ (where we can always provide overloads) or, as an
1459/// extension, in C when the previous function is already an
1460/// overloaded function declaration or has the "overloadable"
1461/// attribute.
1462static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463 ASTContext &Context,
1464 const FunctionDecl *New) {
1465 if (Context.getLangOpts().CPlusPlus)
1466 return true;
1467
1468 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469 return true;
1470
1471 return Previous.getResultKind() == LookupResult::Found &&
1472 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1473 New->hasAttr<OverloadableAttr>());
1474}
1475
1476/// Add this decl to the scope shadowed decl chains.
1477void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478 // Move up the scope chain until we find the nearest enclosing
1479 // non-transparent context. The declaration will be introduced into this
1480 // scope.
1481 while (S->getEntity() && S->getEntity()->isTransparentContext())
1482 S = S->getParent();
1483
1484 // Add scoped declarations into their context, so that they can be
1485 // found later. Declarations without a context won't be inserted
1486 // into any context.
1487 if (AddToContext)
1488 CurContext->addDecl(D);
1489
1490 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491 // are function-local declarations.
1492 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1493 return;
1494
1495 // Template instantiations should also not be pushed into scope.
1496 if (isa<FunctionDecl>(D) &&
1497 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1498 return;
1499
1500 // If this replaces anything in the current scope,
1501 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502 IEnd = IdResolver.end();
1503 for (; I != IEnd; ++I) {
1504 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1505 S->RemoveDecl(*I);
1506 IdResolver.RemoveDecl(*I);
1507
1508 // Should only need to replace one decl.
1509 break;
1510 }
1511 }
1512
1513 S->AddDecl(D);
1514
1515 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1516 // Implicitly-generated labels may end up getting generated in an order that
1517 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518 // the label at the appropriate place in the identifier chain.
1519 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1520 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521 if (IDC == CurContext) {
1522 if (!S->isDeclScope(*I))
1523 continue;
1524 } else if (IDC->Encloses(CurContext))
1525 break;
1526 }
1527
1528 IdResolver.InsertDeclAfter(I, D);
1529 } else {
1530 IdResolver.AddDecl(D);
1531 }
1532 warnOnReservedIdentifier(D);
1533}
1534
1535bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536 bool AllowInlineNamespace) {
1537 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538}
1539
1540Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541 DeclContext *TargetDC = DC->getPrimaryContext();
1542 do {
1543 if (DeclContext *ScopeDC = S->getEntity())
1544 if (ScopeDC->getPrimaryContext() == TargetDC)
1545 return S;
1546 } while ((S = S->getParent()));
1547
1548 return nullptr;
1549}
1550
1551static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552 DeclContext*,
1553 ASTContext&);
1554
1555/// Filters out lookup results that don't fall within the given scope
1556/// as determined by isDeclInScope.
1557void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558 bool ConsiderLinkage,
1559 bool AllowInlineNamespace) {
1560 LookupResult::Filter F = R.makeFilter();
1561 while (F.hasNext()) {
1562 NamedDecl *D = F.next();
1563
1564 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565 continue;
1566
1567 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1568 continue;
1569
1570 F.erase();
1571 }
1572
1573 F.done();
1574}
1575
1576/// We've determined that \p New is a redeclaration of \p Old. Check that they
1577/// have compatible owning modules.
1578bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579 // FIXME: The Modules TS is not clear about how friend declarations are
1580 // to be treated. It's not meaningful to have different owning modules for
1581 // linkage in redeclarations of the same entity, so for now allow the
1582 // redeclaration and change the owning modules to match.
1583 if (New->getFriendObjectKind() &&
1584 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1585 New->setLocalOwningModule(Old->getOwningModule());
1586 makeMergedDefinitionVisible(New);
1587 return false;
1588 }
1589
1590 Module *NewM = New->getOwningModule();
1591 Module *OldM = Old->getOwningModule();
1592
1593 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1594 NewM = NewM->Parent;
1595 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1596 OldM = OldM->Parent;
1597
1598 if (NewM == OldM)
1599 return false;
1600
1601 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1602 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1603 if (NewIsModuleInterface || OldIsModuleInterface) {
1604 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605 // if a declaration of D [...] appears in the purview of a module, all
1606 // other such declarations shall appear in the purview of the same module
1607 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608 << New
1609 << NewIsModuleInterface
1610 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1611 << OldIsModuleInterface
1612 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1613 Diag(Old->getLocation(), diag::note_previous_declaration);
1614 New->setInvalidDecl();
1615 return true;
1616 }
1617
1618 return false;
1619}
1620
1621static bool isUsingDecl(NamedDecl *D) {
1622 return isa<UsingShadowDecl>(D) ||
1623 isa<UnresolvedUsingTypenameDecl>(D) ||
1624 isa<UnresolvedUsingValueDecl>(D);
1625}
1626
1627/// Removes using shadow declarations from the lookup results.
1628static void RemoveUsingDecls(LookupResult &R) {
1629 LookupResult::Filter F = R.makeFilter();
1630 while (F.hasNext())
1631 if (isUsingDecl(F.next()))
1632 F.erase();
1633
1634 F.done();
1635}
1636
1637/// Check for this common pattern:
1638/// @code
1639/// class S {
1640/// S(const S&); // DO NOT IMPLEMENT
1641/// void operator=(const S&); // DO NOT IMPLEMENT
1642/// };
1643/// @endcode
1644static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645 // FIXME: Should check for private access too but access is set after we get
1646 // the decl here.
1647 if (D->doesThisDeclarationHaveABody())
1648 return false;
1649
1650 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651 return CD->isCopyConstructor();
1652 return D->isCopyAssignmentOperator();
1653}
1654
1655// We need this to handle
1656//
1657// typedef struct {
1658// void *foo() { return 0; }
1659// } A;
1660//
1661// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662// for example. If 'A', foo will have external linkage. If we have '*A',
1663// foo will have no linkage. Since we can't know until we get to the end
1664// of the typedef, this function finds out if D might have non-external linkage.
1665// Callers should verify at the end of the TU if it D has external linkage or
1666// not.
1667bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668 const DeclContext *DC = D->getDeclContext();
1669 while (!DC->isTranslationUnit()) {
1670 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671 if (!RD->hasNameForLinkage())
1672 return true;
1673 }
1674 DC = DC->getParent();
1675 }
1676
1677 return !D->isExternallyVisible();
1678}
1679
1680// FIXME: This needs to be refactored; some other isInMainFile users want
1681// these semantics.
1682static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683 if (S.TUKind != TU_Complete)
1684 return false;
1685 return S.SourceMgr.isInMainFile(Loc);
1686}
1687
1688bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1689, __extension__ __PRETTY_FUNCTION__))
;
1690
1691 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1692 return false;
1693
1694 // Ignore all entities declared within templates, and out-of-line definitions
1695 // of members of class templates.
1696 if (D->getDeclContext()->isDependentContext() ||
1697 D->getLexicalDeclContext()->isDependentContext())
1698 return false;
1699
1700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702 return false;
1703 // A non-out-of-line declaration of a member specialization was implicitly
1704 // instantiated; it's the out-of-line declaration that we're interested in.
1705 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1707 return false;
1708
1709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1711 return false;
1712 } else {
1713 // 'static inline' functions are defined in headers; don't warn.
1714 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1715 return false;
1716 }
1717
1718 if (FD->doesThisDeclarationHaveABody() &&
1719 Context.DeclMustBeEmitted(FD))
1720 return false;
1721 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1722 // Constants and utility variables are defined in headers with internal
1723 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1724 // like "inline".)
1725 if (!isMainFileLoc(*this, VD->getLocation()))
1726 return false;
1727
1728 if (Context.DeclMustBeEmitted(VD))
1729 return false;
1730
1731 if (VD->isStaticDataMember() &&
1732 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1733 return false;
1734 if (VD->isStaticDataMember() &&
1735 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1736 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1737 return false;
1738
1739 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1740 return false;
1741 } else {
1742 return false;
1743 }
1744
1745 // Only warn for unused decls internal to the translation unit.
1746 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747 // for inline functions defined in the main source file, for instance.
1748 return mightHaveNonExternalLinkage(D);
1749}
1750
1751void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752 if (!D)
1753 return;
1754
1755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756 const FunctionDecl *First = FD->getFirstDecl();
1757 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1758 return; // First should already be in the vector.
1759 }
1760
1761 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762 const VarDecl *First = VD->getFirstDecl();
1763 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1764 return; // First should already be in the vector.
1765 }
1766
1767 if (ShouldWarnIfUnusedFileScopedDecl(D))
1768 UnusedFileScopedDecls.push_back(D);
1769}
1770
1771static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772 if (D->isInvalidDecl())
1773 return false;
1774
1775 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776 // For a decomposition declaration, warn if none of the bindings are
1777 // referenced, instead of if the variable itself is referenced (which
1778 // it is, by the bindings' expressions).
1779 for (auto *BD : DD->bindings())
1780 if (BD->isReferenced())
1781 return false;
1782 } else if (!D->getDeclName()) {
1783 return false;
1784 } else if (D->isReferenced() || D->isUsed()) {
1785 return false;
1786 }
1787
1788 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1789 return false;
1790
1791 if (isa<LabelDecl>(D))
1792 return true;
1793
1794 // Except for labels, we only care about unused decls that are local to
1795 // functions.
1796 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798 // For dependent types, the diagnostic is deferred.
1799 WithinFunction =
1800 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1801 if (!WithinFunction)
1802 return false;
1803
1804 if (isa<TypedefNameDecl>(D))
1805 return true;
1806
1807 // White-list anything that isn't a local variable.
1808 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1809 return false;
1810
1811 // Types of valid local variables should be complete, so this should succeed.
1812 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813
1814 // White-list anything with an __attribute__((unused)) type.
1815 const auto *Ty = VD->getType().getTypePtr();
1816
1817 // Only look at the outermost level of typedef.
1818 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819 if (TT->getDecl()->hasAttr<UnusedAttr>())
1820 return false;
1821 }
1822
1823 // If we failed to complete the type for some reason, or if the type is
1824 // dependent, don't diagnose the variable.
1825 if (Ty->isIncompleteType() || Ty->isDependentType())
1826 return false;
1827
1828 // Look at the element type to ensure that the warning behaviour is
1829 // consistent for both scalars and arrays.
1830 Ty = Ty->getBaseElementTypeUnsafe();
1831
1832 if (const TagType *TT = Ty->getAs<TagType>()) {
1833 const TagDecl *Tag = TT->getDecl();
1834 if (Tag->hasAttr<UnusedAttr>())
1835 return false;
1836
1837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1839 return false;
1840
1841 if (const Expr *Init = VD->getInit()) {
1842 if (const ExprWithCleanups *Cleanups =
1843 dyn_cast<ExprWithCleanups>(Init))
1844 Init = Cleanups->getSubExpr();
1845 const CXXConstructExpr *Construct =
1846 dyn_cast<CXXConstructExpr>(Init);
1847 if (Construct && !Construct->isElidable()) {
1848 CXXConstructorDecl *CD = Construct->getConstructor();
1849 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1850 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1851 return false;
1852 }
1853
1854 // Suppress the warning if we don't know how this is constructed, and
1855 // it could possibly be non-trivial constructor.
1856 if (Init->isTypeDependent())
1857 for (const CXXConstructorDecl *Ctor : RD->ctors())
1858 if (!Ctor->isTrivial())
1859 return false;
1860 }
1861 }
1862 }
1863
1864 // TODO: __attribute__((unused)) templates?
1865 }
1866
1867 return true;
1868}
1869
1870static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871 FixItHint &Hint) {
1872 if (isa<LabelDecl>(D)) {
1873 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875 true);
1876 if (AfterColon.isInvalid())
1877 return;
1878 Hint = FixItHint::CreateRemoval(
1879 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880 }
1881}
1882
1883void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884 if (D->getTypeForDecl()->isDependentType())
1885 return;
1886
1887 for (auto *TmpD : D->decls()) {
1888 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889 DiagnoseUnusedDecl(T);
1890 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891 DiagnoseUnusedNestedTypedefs(R);
1892 }
1893}
1894
1895/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896/// unless they are marked attr(unused).
1897void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898 if (!ShouldDiagnoseUnusedDecl(D))
1899 return;
1900
1901 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902 // typedefs can be referenced later on, so the diagnostics are emitted
1903 // at end-of-translation-unit.
1904 UnusedLocalTypedefNameCandidates.insert(TD);
1905 return;
1906 }
1907
1908 FixItHint Hint;
1909 GenerateFixForUnusedDecl(D, Context, Hint);
1910
1911 unsigned DiagID;
1912 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1913 DiagID = diag::warn_unused_exception_param;
1914 else if (isa<LabelDecl>(D))
1915 DiagID = diag::warn_unused_label;
1916 else
1917 DiagID = diag::warn_unused_variable;
1918
1919 Diag(D->getLocation(), DiagID) << D << Hint;
1920}
1921
1922void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923 // If it's not referenced, it can't be set.
1924 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
1925 return;
1926
1927 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928
1929 if (Ty->isReferenceType() || Ty->isDependentType())
1930 return;
1931
1932 if (const TagType *TT = Ty->getAs<TagType>()) {
1933 const TagDecl *Tag = TT->getDecl();
1934 if (Tag->hasAttr<UnusedAttr>())
1935 return;
1936 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937 // mimic gcc's behavior.
1938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939 if (!RD->hasAttr<WarnUnusedAttr>())
1940 return;
1941 }
1942 }
1943
1944 auto iter = RefsMinusAssignments.find(VD);
1945 if (iter == RefsMinusAssignments.end())
1946 return;
1947
1948 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
1949 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
;
1950 if (iter->getSecond() != 0)
1951 return;
1952 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1953 : diag::warn_unused_but_set_variable;
1954 Diag(VD->getLocation(), DiagID) << VD;
1955}
1956
1957static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958 // Verify that we have no forward references left. If so, there was a goto
1959 // or address of a label taken, but no definition of it. Label fwd
1960 // definitions are indicated with a null substmt which is also not a resolved
1961 // MS inline assembly label name.
1962 bool Diagnose = false;
1963 if (L->isMSAsmLabel())
1964 Diagnose = !L->isResolvedMSAsmLabel();
1965 else
1966 Diagnose = L->getStmt() == nullptr;
1967 if (Diagnose)
1968 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969}
1970
1971void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972 S->mergeNRVOIntoParent();
1973
1974 if (S->decl_empty()) return;
1975 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1976, __extension__ __PRETTY_FUNCTION__))
1976 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1976, __extension__ __PRETTY_FUNCTION__))
;
1977
1978 for (auto *TmpD : S->decls()) {
1979 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
;
1980
1981 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1981, __extension__ __PRETTY_FUNCTION__))
;
1982 NamedDecl *D = cast<NamedDecl>(TmpD);
1983
1984 // Diagnose unused variables in this scope.
1985 if (!S->hasUnrecoverableErrorOccurred()) {
1986 DiagnoseUnusedDecl(D);
1987 if (const auto *RD = dyn_cast<RecordDecl>(D))
1988 DiagnoseUnusedNestedTypedefs(RD);
1989 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990 DiagnoseUnusedButSetDecl(VD);
1991 RefsMinusAssignments.erase(VD);
1992 }
1993 }
1994
1995 if (!D->getDeclName()) continue;
1996
1997 // If this was a forward reference to a label, verify it was defined.
1998 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999 CheckPoppedLabel(LD, *this);
2000
2001 // Remove this name from our lexical scope, and warn on it if we haven't
2002 // already.
2003 IdResolver.RemoveDecl(D);
2004 auto ShadowI = ShadowingDecls.find(D);
2005 if (ShadowI != ShadowingDecls.end()) {
2006 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008 << D << FD << FD->getParent();
2009 Diag(FD->getLocation(), diag::note_previous_declaration);
2010 }
2011 ShadowingDecls.erase(ShadowI);
2012 }
2013 }
2014}
2015
2016/// Look for an Objective-C class in the translation unit.
2017///
2018/// \param Id The name of the Objective-C class we're looking for. If
2019/// typo-correction fixes this name, the Id will be updated
2020/// to the fixed name.
2021///
2022/// \param IdLoc The location of the name in the translation unit.
2023///
2024/// \param DoTypoCorrection If true, this routine will attempt typo correction
2025/// if there is no class with the given name.
2026///
2027/// \returns The declaration of the named Objective-C class, or NULL if the
2028/// class could not be found.
2029ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030 SourceLocation IdLoc,
2031 bool DoTypoCorrection) {
2032 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033 // creation from this context.
2034 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035
2036 if (!IDecl && DoTypoCorrection) {
2037 // Perform typo correction at the given location, but only if we
2038 // find an Objective-C class name.
2039 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040 if (TypoCorrection C =
2041 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045 Id = IDecl->getIdentifier();
2046 }
2047 }
2048 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049 // This routine must always return a class definition, if any.
2050 if (Def && Def->getDefinition())
2051 Def = Def->getDefinition();
2052 return Def;
2053}
2054
2055/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056/// from S, where a non-field would be declared. This routine copes
2057/// with the difference between C and C++ scoping rules in structs and
2058/// unions. For example, the following code is well-formed in C but
2059/// ill-formed in C++:
2060/// @code
2061/// struct S6 {
2062/// enum { BAR } e;
2063/// };
2064///
2065/// void test_S6() {
2066/// struct S6 a;
2067/// a.e = BAR;
2068/// }
2069/// @endcode
2070/// For the declaration of BAR, this routine will return a different
2071/// scope. The scope S will be the scope of the unnamed enumeration
2072/// within S6. In C++, this routine will return the scope associated
2073/// with S6, because the enumeration's scope is a transparent
2074/// context but structures can contain non-field names. In C, this
2075/// routine will return the translation unit scope, since the
2076/// enumeration's scope is a transparent context and structures cannot
2077/// contain non-field names.
2078Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2081 (S->isClassScope() && !getLangOpts().CPlusPlus))
2082 S = S->getParent();
2083 return S;
2084}
2085
2086static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087 ASTContext::GetBuiltinTypeError Error) {
2088 switch (Error) {
2089 case ASTContext::GE_None:
2090 return "";
2091 case ASTContext::GE_Missing_type:
2092 return BuiltinInfo.getHeaderName(ID);
2093 case ASTContext::GE_Missing_stdio:
2094 return "stdio.h";
2095 case ASTContext::GE_Missing_setjmp:
2096 return "setjmp.h";
2097 case ASTContext::GE_Missing_ucontext:
2098 return "ucontext.h";
2099 }
2100 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 2100)
;
2101}
2102
2103FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104 unsigned ID, SourceLocation Loc) {
2105 DeclContext *Parent = Context.getTranslationUnitDecl();
2106
2107 if (getLangOpts().CPlusPlus) {
2108 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110 CLinkageDecl->setImplicit();
2111 Parent->addDecl(CLinkageDecl);
2112 Parent = CLinkageDecl;
2113 }
2114
2115 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116 /*TInfo=*/nullptr, SC_Extern,
2117 getCurFPFeatures().isFPConstrained(),
2118 false, Type->isFunctionProtoType());
2119 New->setImplicit();
2120 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2121
2122 // Create Decl objects for each parameter, adding them to the
2123 // FunctionDecl.
2124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2125 SmallVector<ParmVarDecl *, 16> Params;
2126 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2127 ParmVarDecl *parm = ParmVarDecl::Create(
2128 Context, New, SourceLocation(), SourceLocation(), nullptr,
2129 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2130 parm->setScopeInfo(0, i);
2131 Params.push_back(parm);
2132 }
2133 New->setParams(Params);
2134 }
2135
2136 AddKnownFunctionAttributes(New);
2137 return New;
2138}
2139
2140/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2141/// file scope. lazily create a decl for it. ForRedeclaration is true
2142/// if we're creating this built-in in anticipation of redeclaring the
2143/// built-in.
2144NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2145 Scope *S, bool ForRedeclaration,
2146 SourceLocation Loc) {
2147 LookupNecessaryTypesForBuiltin(S, ID);
2148
2149 ASTContext::GetBuiltinTypeError Error;
2150 QualType R = Context.GetBuiltinType(ID, Error);
2151 if (Error) {
2152 if (!ForRedeclaration)
2153 return nullptr;
2154
2155 // If we have a builtin without an associated type we should not emit a
2156 // warning when we were not able to find a type for it.
2157 if (Error == ASTContext::GE_Missing_type ||
2158 Context.BuiltinInfo.allowTypeMismatch(ID))
2159 return nullptr;
2160
2161 // If we could not find a type for setjmp it is because the jmp_buf type was
2162 // not defined prior to the setjmp declaration.
2163 if (Error == ASTContext::GE_Missing_setjmp) {
2164 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2165 << Context.BuiltinInfo.getName(ID);
2166 return nullptr;
2167 }
2168
2169 // Generally, we emit a warning that the declaration requires the
2170 // appropriate header.
2171 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2172 << getHeaderName(Context.BuiltinInfo, ID, Error)
2173 << Context.BuiltinInfo.getName(ID);
2174 return nullptr;
2175 }
2176
2177 if (!ForRedeclaration &&
2178 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2179 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2180 Diag(Loc, diag::ext_implicit_lib_function_decl)
2181 << Context.BuiltinInfo.getName(ID) << R;
2182 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2183 Diag(Loc, diag::note_include_header_or_declare)
2184 << Header << Context.BuiltinInfo.getName(ID);
2185 }
2186
2187 if (R.isNull())
2188 return nullptr;
2189
2190 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2191 RegisterLocallyScopedExternCDecl(New, S);
2192
2193 // TUScope is the translation-unit scope to insert this function into.
2194 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2195 // relate Scopes to DeclContexts, and probably eliminate CurContext
2196 // entirely, but we're not there yet.
2197 DeclContext *SavedContext = CurContext;
2198 CurContext = New->getDeclContext();
2199 PushOnScopeChains(New, TUScope);
2200 CurContext = SavedContext;
2201 return New;
2202}
2203
2204/// Typedef declarations don't have linkage, but they still denote the same
2205/// entity if their types are the same.
2206/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2207/// isSameEntity.
2208static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2209 TypedefNameDecl *Decl,
2210 LookupResult &Previous) {
2211 // This is only interesting when modules are enabled.
2212 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2213 return;
2214
2215 // Empty sets are uninteresting.
2216 if (Previous.empty())
2217 return;
2218
2219 LookupResult::Filter Filter = Previous.makeFilter();
2220 while (Filter.hasNext()) {
2221 NamedDecl *Old = Filter.next();
2222
2223 // Non-hidden declarations are never ignored.
2224 if (S.isVisible(Old))
2225 continue;
2226
2227 // Declarations of the same entity are not ignored, even if they have
2228 // different linkages.
2229 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2230 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2231 Decl->getUnderlyingType()))
2232 continue;
2233
2234 // If both declarations give a tag declaration a typedef name for linkage
2235 // purposes, then they declare the same entity.
2236 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2237 Decl->getAnonDeclWithTypedefName())
2238 continue;
2239 }
2240
2241 Filter.erase();
2242 }
2243
2244 Filter.done();
2245}
2246
2247bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2248 QualType OldType;
2249 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2250 OldType = OldTypedef->getUnderlyingType();
2251 else
2252 OldType = Context.getTypeDeclType(Old);
2253 QualType NewType = New->getUnderlyingType();
2254
2255 if (NewType->isVariablyModifiedType()) {
2256 // Must not redefine a typedef with a variably-modified type.
2257 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2258 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2259 << Kind << NewType;
2260 if (Old->getLocation().isValid())
2261 notePreviousDefinition(Old, New->getLocation());
2262 New->setInvalidDecl();
2263 return true;
2264 }
2265
2266 if (OldType != NewType &&
2267 !OldType->isDependentType() &&
2268 !NewType->isDependentType() &&
2269 !Context.hasSameType(OldType, NewType)) {
2270 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2271 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2272 << Kind << NewType << OldType;
2273 if (Old->getLocation().isValid())
2274 notePreviousDefinition(Old, New->getLocation());
2275 New->setInvalidDecl();
2276 return true;
2277 }
2278 return false;
2279}
2280
2281/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2282/// same name and scope as a previous declaration 'Old'. Figure out
2283/// how to resolve this situation, merging decls or emitting
2284/// diagnostics as appropriate. If there was an error, set New to be invalid.
2285///
2286void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2287 LookupResult &OldDecls) {
2288 // If the new decl is known invalid already, don't bother doing any
2289 // merging checks.
2290 if (New->isInvalidDecl()) return;
2291
2292 // Allow multiple definitions for ObjC built-in typedefs.
2293 // FIXME: Verify the underlying types are equivalent!
2294 if (getLangOpts().ObjC) {
2295 const IdentifierInfo *TypeID = New->getIdentifier();
2296 switch (TypeID->getLength()) {
2297 default: break;
2298 case 2:
2299 {
2300 if (!TypeID->isStr("id"))
2301 break;
2302 QualType T = New->getUnderlyingType();
2303 if (!T->isPointerType())
2304 break;
2305 if (!T->isVoidPointerType()) {
2306 QualType PT = T->castAs<PointerType>()->getPointeeType();
2307 if (!PT->isStructureType())
2308 break;
2309 }
2310 Context.setObjCIdRedefinitionType(T);
2311 // Install the built-in type for 'id', ignoring the current definition.
2312 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2313 return;
2314 }
2315 case 5:
2316 if (!TypeID->isStr("Class"))
2317 break;
2318 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2319 // Install the built-in type for 'Class', ignoring the current definition.
2320 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2321 return;
2322 case 3:
2323 if (!TypeID->isStr("SEL"))
2324 break;
2325 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2326 // Install the built-in type for 'SEL', ignoring the current definition.
2327 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2328 return;
2329 }
2330 // Fall through - the typedef name was not a builtin type.
2331 }
2332
2333 // Verify the old decl was also a type.
2334 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2335 if (!Old) {
2336 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2337 << New->getDeclName();
2338
2339 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2340 if (OldD->getLocation().isValid())
2341 notePreviousDefinition(OldD, New->getLocation());
2342
2343 return New->setInvalidDecl();
2344 }
2345
2346 // If the old declaration is invalid, just give up here.
2347 if (Old->isInvalidDecl())
2348 return New->setInvalidDecl();
2349
2350 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2351 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2352 auto *NewTag = New->getAnonDeclWithTypedefName();
2353 NamedDecl *Hidden = nullptr;
2354 if (OldTag && NewTag &&
2355 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2356 !hasVisibleDefinition(OldTag, &Hidden)) {
2357 // There is a definition of this tag, but it is not visible. Use it
2358 // instead of our tag.
2359 New->setTypeForDecl(OldTD->getTypeForDecl());
2360 if (OldTD->isModed())
2361 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2362 OldTD->getUnderlyingType());
2363 else
2364 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2365
2366 // Make the old tag definition visible.
2367 makeMergedDefinitionVisible(Hidden);
2368
2369 // If this was an unscoped enumeration, yank all of its enumerators
2370 // out of the scope.
2371 if (isa<EnumDecl>(NewTag)) {
2372 Scope *EnumScope = getNonFieldDeclScope(S);
2373 for (auto *D : NewTag->decls()) {
2374 auto *ED = cast<EnumConstantDecl>(D);
2375 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 2375, __extension__ __PRETTY_FUNCTION__))
;
2376 EnumScope->RemoveDecl(ED);
2377 IdResolver.RemoveDecl(ED);
2378 ED->getLexicalDeclContext()->removeDecl(ED);
2379 }
2380 }
2381 }
2382 }
2383
2384 // If the typedef types are not identical, reject them in all languages and
2385 // with any extensions enabled.
2386 if (isIncompatibleTypedef(Old, New))
2387 return;
2388
2389 // The types match. Link up the redeclaration chain and merge attributes if
2390 // the old declaration was a typedef.
2391 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2392 New->setPreviousDecl(Typedef);
2393 mergeDeclAttributes(New, Old);
2394 }
2395
2396 if (getLangOpts().MicrosoftExt)
2397 return;
2398
2399 if (getLangOpts().CPlusPlus) {
2400 // C++ [dcl.typedef]p2:
2401 // In a given non-class scope, a typedef specifier can be used to
2402 // redefine the name of any type declared in that scope to refer
2403 // to the type to which it already refers.
2404 if (!isa<CXXRecordDecl>(CurContext))
2405 return;
2406
2407 // C++0x [dcl.typedef]p4:
2408 // In a given class scope, a typedef specifier can be used to redefine
2409 // any class-name declared in that scope that is not also a typedef-name
2410 // to refer to the type to which it already refers.
2411 //
2412 // This wording came in via DR424, which was a correction to the
2413 // wording in DR56, which accidentally banned code like:
2414 //
2415 // struct S {
2416 // typedef struct A { } A;
2417 // };
2418 //
2419 // in the C++03 standard. We implement the C++0x semantics, which
2420 // allow the above but disallow
2421 //
2422 // struct S {
2423 // typedef int I;
2424 // typedef int I;
2425 // };
2426 //
2427 // since that was the intent of DR56.
2428 if (!isa<TypedefNameDecl>(Old))
2429 return;
2430
2431 Diag(New->getLocation(), diag::err_redefinition)
2432 << New->getDeclName();
2433 notePreviousDefinition(Old, New->getLocation());
2434 return New->setInvalidDecl();
2435 }
2436
2437 // Modules always permit redefinition of typedefs, as does C11.
2438 if (getLangOpts().Modules || getLangOpts().C11)
2439 return;
2440
2441 // If we have a redefinition of a typedef in C, emit a warning. This warning
2442 // is normally mapped to an error, but can be controlled with
2443 // -Wtypedef-redefinition. If either the original or the redefinition is
2444 // in a system header, don't emit this for compatibility with GCC.
2445 if (getDiagnostics().getSuppressSystemWarnings() &&
2446 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2447 (Old->isImplicit() ||
2448 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2449 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2450 return;
2451
2452 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2453 << New->getDeclName();
2454 notePreviousDefinition(Old, New->getLocation());
2455}
2456
2457/// DeclhasAttr - returns true if decl Declaration already has the target
2458/// attribute.
2459static bool DeclHasAttr(const Decl *D, const Attr *A) {
2460 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2461 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2462 for (const auto *i : D->attrs())
2463 if (i->getKind() == A->getKind()) {
2464 if (Ann) {
2465 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2466 return true;
2467 continue;
2468 }
2469 // FIXME: Don't hardcode this check
2470 if (OA && isa<OwnershipAttr>(i))
2471 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2472 return true;
2473 }
2474
2475 return false;
2476}
2477
2478static bool isAttributeTargetADefinition(Decl *D) {
2479 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2480 return VD->isThisDeclarationADefinition();
2481 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2482 return TD->isCompleteDefinition() || TD->isBeingDefined();
2483 return true;
2484}
2485
2486/// Merge alignment attributes from \p Old to \p New, taking into account the
2487/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2488///
2489/// \return \c true if any attributes were added to \p New.
2490static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2491 // Look for alignas attributes on Old, and pick out whichever attribute
2492 // specifies the strictest alignment requirement.
2493 AlignedAttr *OldAlignasAttr = nullptr;
2494 AlignedAttr *OldStrictestAlignAttr = nullptr;
2495 unsigned OldAlign = 0;
2496 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2497 // FIXME: We have no way of representing inherited dependent alignments
2498 // in a case like:
2499 // template<int A, int B> struct alignas(A) X;
2500 // template<int A, int B> struct alignas(B) X {};
2501 // For now, we just ignore any alignas attributes which are not on the
2502 // definition in such a case.
2503 if (I->isAlignmentDependent())
2504 return false;
2505
2506 if (I->isAlignas())
2507 OldAlignasAttr = I;
2508
2509 unsigned Align = I->getAlignment(S.Context);
2510 if (Align > OldAlign) {
2511 OldAlign = Align;
2512 OldStrictestAlignAttr = I;
2513 }
2514 }
2515
2516 // Look for alignas attributes on New.
2517 AlignedAttr *NewAlignasAttr = nullptr;
2518 unsigned NewAlign = 0;
2519 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2520 if (I->isAlignmentDependent())
2521 return false;
2522
2523 if (I->isAlignas())
2524 NewAlignasAttr = I;
2525
2526 unsigned Align = I->getAlignment(S.Context);
2527 if (Align > NewAlign)
2528 NewAlign = Align;
2529 }
2530
2531 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2532 // Both declarations have 'alignas' attributes. We require them to match.
2533 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2534 // fall short. (If two declarations both have alignas, they must both match
2535 // every definition, and so must match each other if there is a definition.)
2536
2537 // If either declaration only contains 'alignas(0)' specifiers, then it
2538 // specifies the natural alignment for the type.
2539 if (OldAlign == 0 || NewAlign == 0) {
2540 QualType Ty;
2541 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2542 Ty = VD->getType();
2543 else
2544 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2545
2546 if (OldAlign == 0)
2547 OldAlign = S.Context.getTypeAlign(Ty);
2548 if (NewAlign == 0)
2549 NewAlign = S.Context.getTypeAlign(Ty);
2550 }
2551
2552 if (OldAlign != NewAlign) {
2553 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2554 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2555 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2556 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2557 }
2558 }
2559
2560 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2561 // C++11 [dcl.align]p6:
2562 // if any declaration of an entity has an alignment-specifier,
2563 // every defining declaration of that entity shall specify an
2564 // equivalent alignment.
2565 // C11 6.7.5/7:
2566 // If the definition of an object does not have an alignment
2567 // specifier, any other declaration of that object shall also
2568 // have no alignment specifier.
2569 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2570 << OldAlignasAttr;
2571 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2572 << OldAlignasAttr;
2573 }
2574
2575 bool AnyAdded = false;
2576
2577 // Ensure we have an attribute representing the strictest alignment.
2578 if (OldAlign > NewAlign) {
2579 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2580 Clone->setInherited(true);
2581 New->addAttr(Clone);
2582 AnyAdded = true;
2583 }
2584
2585 // Ensure we have an alignas attribute if the old declaration had one.
2586 if (OldAlignasAttr && !NewAlignasAttr &&
2587 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2588 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2589 Clone->setInherited(true);
2590 New->addAttr(Clone);
2591 AnyAdded = true;
2592 }
2593
2594 return AnyAdded;
2595}
2596
2597#define WANT_DECL_MERGE_LOGIC
2598#include "clang/Sema/AttrParsedAttrImpl.inc"
2599#undef WANT_DECL_MERGE_LOGIC
2600
2601static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2602 const InheritableAttr *Attr,
2603 Sema::AvailabilityMergeKind AMK) {
2604 // Diagnose any mutual exclusions between the attribute that we want to add
2605 // and attributes that already exist on the declaration.
2606 if (!DiagnoseMutualExclusions(S, D, Attr))
2607 return false;
2608
2609 // This function copies an attribute Attr from a previous declaration to the
2610 // new declaration D if the new declaration doesn't itself have that attribute
2611 // yet or if that attribute allows duplicates.
2612 // If you're adding a new attribute that requires logic different from
2613 // "use explicit attribute on decl if present, else use attribute from
2614 // previous decl", for example if the attribute needs to be consistent
2615 // between redeclarations, you need to call a custom merge function here.
2616 InheritableAttr *NewAttr = nullptr;
2617 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2618 NewAttr = S.mergeAvailabilityAttr(
2619 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2620 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2621 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2622 AA->getPriority());
2623 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2624 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2625 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2626 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2627 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2628 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2629 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2630 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2631 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2632 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2633 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2634 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2635 FA->getFirstArg());
2636 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2637 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2638 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2639 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2640 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2641 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2642 IA->getInheritanceModel());
2643 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2644 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2645 &S.Context.Idents.get(AA->getSpelling()));
2646 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2647 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2648 isa<CUDAGlobalAttr>(Attr))) {
2649 // CUDA target attributes are part of function signature for
2650 // overloading purposes and must not be merged.
2651 return false;
2652 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2653 NewAttr = S.mergeMinSizeAttr(D, *MA);
2654 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2655 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2656 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2657 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2658 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2659 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2660 else if (isa<AlignedAttr>(Attr))
2661 // AlignedAttrs are handled separately, because we need to handle all
2662 // such attributes on a declaration at the same time.
2663 NewAttr = nullptr;
2664 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2665 (AMK == Sema::AMK_Override ||
2666 AMK == Sema::AMK_ProtocolImplementation ||
2667 AMK == Sema::AMK_OptionalProtocolImplementation))
2668 NewAttr = nullptr;
2669 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2670 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2671 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2672 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2673 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2674 NewAttr = S.mergeImportNameAttr(D, *INA);
2675 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2676 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2677 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2678 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2679 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr))
2680 NewAttr = S.mergeBTFTagAttr(D, *BTFA);
2681 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2682 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2683
2684 if (NewAttr) {
2685 NewAttr->setInherited(true);
2686 D->addAttr(NewAttr);
2687 if (isa<MSInheritanceAttr>(NewAttr))
2688 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2689 return true;
2690 }
2691
2692 return false;
2693}
2694
2695static const NamedDecl *getDefinition(const Decl *D) {
2696 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2697 return TD->getDefinition();
2698 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2699 const VarDecl *Def = VD->getDefinition();
2700 if (Def)
2701 return Def;
2702 return VD->getActingDefinition();
2703 }
2704 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2705 const FunctionDecl *Def = nullptr;
2706 if (FD->isDefined(Def, true))
2707 return Def;
2708 }
2709 return nullptr;
2710}
2711
2712static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2713 for (const auto *Attribute : D->attrs())
2714 if (Attribute->getKind() == Kind)
2715 return true;
2716 return false;
2717}
2718
2719/// checkNewAttributesAfterDef - If we already have a definition, check that
2720/// there are no new attributes in this declaration.
2721static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2722 if (!New->hasAttrs())
2723 return;
2724
2725 const NamedDecl *Def = getDefinition(Old);
2726 if (!Def || Def == New)
2727 return;
2728
2729 AttrVec &NewAttributes = New->getAttrs();
2730 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2731 const Attr *NewAttribute = NewAttributes[I];
2732
2733 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2734 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2735 Sema::SkipBodyInfo SkipBody;
2736 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2737
2738 // If we're skipping this definition, drop the "alias" attribute.
2739 if (SkipBody.ShouldSkip) {
2740 NewAttributes.erase(NewAttributes.begin() + I);
2741 --E;
2742 continue;
2743 }
2744 } else {
2745 VarDecl *VD = cast<VarDecl>(New);
2746 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2747 VarDecl::TentativeDefinition
2748 ? diag::err_alias_after_tentative
2749 : diag::err_redefinition;
2750 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2751 if (Diag == diag::err_redefinition)
2752 S.notePreviousDefinition(Def, VD->getLocation());
2753 else
2754 S.Diag(Def->getLocation(), diag::note_previous_definition);
2755 VD->setInvalidDecl();
2756 }
2757 ++I;
2758 continue;
2759 }
2760
2761 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2762 // Tentative definitions are only interesting for the alias check above.
2763 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2764 ++I;
2765 continue;
2766 }
2767 }
2768
2769 if (hasAttribute(Def, NewAttribute->getKind())) {
2770 ++I;
2771 continue; // regular attr merging will take care of validating this.
2772 }
2773
2774 if (isa<C11NoReturnAttr>(NewAttribute)) {
2775 // C's _Noreturn is allowed to be added to a function after it is defined.
2776 ++I;
2777 continue;
2778 } else if (isa<UuidAttr>(NewAttribute)) {
2779 // msvc will allow a subsequent definition to add an uuid to a class
2780 ++I;
2781 continue;
2782 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2783 if (AA->isAlignas()) {
2784 // C++11 [dcl.align]p6:
2785 // if any declaration of an entity has an alignment-specifier,
2786 // every defining declaration of that entity shall specify an
2787 // equivalent alignment.
2788 // C11 6.7.5/7:
2789 // If the definition of an object does not have an alignment
2790 // specifier, any other declaration of that object shall also
2791 // have no alignment specifier.
2792 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2793 << AA;
2794 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2795 << AA;
2796 NewAttributes.erase(NewAttributes.begin() + I);
2797 --E;
2798 continue;
2799 }
2800 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2801 // If there is a C definition followed by a redeclaration with this
2802 // attribute then there are two different definitions. In C++, prefer the
2803 // standard diagnostics.
2804 if (!S.getLangOpts().CPlusPlus) {
2805 S.Diag(NewAttribute->getLocation(),
2806 diag::err_loader_uninitialized_redeclaration);
2807 S.Diag(Def->getLocation(), diag::note_previous_definition);
2808 NewAttributes.erase(NewAttributes.begin() + I);
2809 --E;
2810 continue;
2811 }
2812 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2813 cast<VarDecl>(New)->isInline() &&
2814 !cast<VarDecl>(New)->isInlineSpecified()) {
2815 // Don't warn about applying selectany to implicitly inline variables.
2816 // Older compilers and language modes would require the use of selectany
2817 // to make such variables inline, and it would have no effect if we
2818 // honored it.
2819 ++I;
2820 continue;
2821 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2822 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2823 // declarations after defintions.
2824 ++I;
2825 continue;
2826 }
2827
2828 S.Diag(NewAttribute->getLocation(),
2829 diag::warn_attribute_precede_definition);
2830 S.Diag(Def->getLocation(), diag::note_previous_definition);
2831 NewAttributes.erase(NewAttributes.begin() + I);
2832 --E;
2833 }
2834}
2835
2836static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2837 const ConstInitAttr *CIAttr,
2838 bool AttrBeforeInit) {
2839 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2840
2841 // Figure out a good way to write this specifier on the old declaration.
2842 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2843 // enough of the attribute list spelling information to extract that without
2844 // heroics.
2845 std::string SuitableSpelling;
2846 if (S.getLangOpts().CPlusPlus20)
2847 SuitableSpelling = std::string(
2848 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2849 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2850 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2851 InsertLoc, {tok::l_square, tok::l_square,
2852 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2853 S.PP.getIdentifierInfo("require_constant_initialization"),
2854 tok::r_square, tok::r_square}));
2855 if (SuitableSpelling.empty())
2856 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2857 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2858 S.PP.getIdentifierInfo("require_constant_initialization"),
2859 tok::r_paren, tok::r_paren}));
2860 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2861 SuitableSpelling = "constinit";
2862 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2863 SuitableSpelling = "[[clang::require_constant_initialization]]";
2864 if (SuitableSpelling.empty())
2865 SuitableSpelling = "__attribute__((require_constant_initialization))";
2866 SuitableSpelling += " ";
2867
2868 if (AttrBeforeInit) {
2869 // extern constinit int a;
2870 // int a = 0; // error (missing 'constinit'), accepted as extension
2871 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 2871, __extension__ __PRETTY_FUNCTION__))
;
2872 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2873 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2874 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2875 } else {
2876 // int a = 0;
2877 // constinit extern int a; // error (missing 'constinit')
2878 S.Diag(CIAttr->getLocation(),
2879 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2880 : diag::warn_require_const_init_added_too_late)
2881 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2882 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2883 << CIAttr->isConstinit()
2884 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2885 }
2886}
2887
2888/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2889void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2890 AvailabilityMergeKind AMK) {
2891 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2892 UsedAttr *NewAttr = OldAttr->clone(Context);
2893 NewAttr->setInherited(true);
2894 New->addAttr(NewAttr);
2895 }
2896 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2897 RetainAttr *NewAttr = OldAttr->clone(Context);
2898 NewAttr->setInherited(true);
2899 New->addAttr(NewAttr);
2900 }
2901
2902 if (!Old->hasAttrs() && !New->hasAttrs())
2903 return;
2904
2905 // [dcl.constinit]p1:
2906 // If the [constinit] specifier is applied to any declaration of a
2907 // variable, it shall be applied to the initializing declaration.
2908 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2909 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2910 if (bool(OldConstInit) != bool(NewConstInit)) {
2911 const auto *OldVD = cast<VarDecl>(Old);
2912 auto *NewVD = cast<VarDecl>(New);
2913
2914 // Find the initializing declaration. Note that we might not have linked
2915 // the new declaration into the redeclaration chain yet.
2916 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2917 if (!InitDecl &&
2918 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2919 InitDecl = NewVD;
2920
2921 if (InitDecl == NewVD) {
2922 // This is the initializing declaration. If it would inherit 'constinit',
2923 // that's ill-formed. (Note that we do not apply this to the attribute
2924 // form).
2925 if (OldConstInit && OldConstInit->isConstinit())
2926 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2927 /*AttrBeforeInit=*/true);
2928 } else if (NewConstInit) {
2929 // This is the first time we've been told that this declaration should
2930 // have a constant initializer. If we already saw the initializing
2931 // declaration, this is too late.
2932 if (InitDecl && InitDecl != NewVD) {
2933 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2934 /*AttrBeforeInit=*/false);
2935 NewVD->dropAttr<ConstInitAttr>();
2936 }
2937 }
2938 }
2939
2940 // Attributes declared post-definition are currently ignored.
2941 checkNewAttributesAfterDef(*this, New, Old);
2942
2943 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2944 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2945 if (!OldA->isEquivalent(NewA)) {
2946 // This redeclaration changes __asm__ label.
2947 Diag(New->getLocation(), diag::err_different_asm_label);
2948 Diag(OldA->getLocation(), diag::note_previous_declaration);
2949 }
2950 } else if (Old->isUsed()) {
2951 // This redeclaration adds an __asm__ label to a declaration that has
2952 // already been ODR-used.
2953 Diag(New->getLocation(), diag::err_late_asm_label_name)
2954 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2955 }
2956 }
2957
2958 // Re-declaration cannot add abi_tag's.
2959 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2960 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2961 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2962 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2963 NewTag) == OldAbiTagAttr->tags_end()) {
2964 Diag(NewAbiTagAttr->getLocation(),
2965 diag::err_new_abi_tag_on_redeclaration)
2966 << NewTag;
2967 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2968 }
2969 }
2970 } else {
2971 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2972 Diag(Old->getLocation(), diag::note_previous_declaration);
2973 }
2974 }
2975
2976 // This redeclaration adds a section attribute.
2977 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2978 if (auto *VD = dyn_cast<VarDecl>(New)) {
2979 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2980 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2981 Diag(Old->getLocation(), diag::note_previous_declaration);
2982 }
2983 }
2984 }
2985
2986 // Redeclaration adds code-seg attribute.
2987 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2988 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2989 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2990 Diag(New->getLocation(), diag::warn_mismatched_section)
2991 << 0 /*codeseg*/;
2992 Diag(Old->getLocation(), diag::note_previous_declaration);
2993 }
2994
2995 if (!Old->hasAttrs())
2996 return;
2997
2998 bool foundAny = New->hasAttrs();
2999
3000 // Ensure that any moving of objects within the allocated map is done before
3001 // we process them.
3002 if (!foundAny) New->setAttrs(AttrVec());
3003
3004 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3005 // Ignore deprecated/unavailable/availability attributes if requested.
3006 AvailabilityMergeKind LocalAMK = AMK_None;
3007 if (isa<DeprecatedAttr>(I) ||
3008 isa<UnavailableAttr>(I) ||
3009 isa<AvailabilityAttr>(I)) {
3010 switch (AMK) {
3011 case AMK_None:
3012 continue;
3013
3014 case AMK_Redeclaration:
3015 case AMK_Override:
3016 case AMK_ProtocolImplementation:
3017 case AMK_OptionalProtocolImplementation:
3018 LocalAMK = AMK;
3019 break;
3020 }
3021 }
3022
3023 // Already handled.
3024 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3025 continue;
3026
3027 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3028 foundAny = true;
3029 }
3030
3031 if (mergeAlignedAttrs(*this, New, Old))
3032 foundAny = true;
3033
3034 if (!foundAny) New->dropAttrs();
3035}
3036
3037/// mergeParamDeclAttributes - Copy attributes from the old parameter
3038/// to the new one.
3039static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3040 const ParmVarDecl *oldDecl,
3041 Sema &S) {
3042 // C++11 [dcl.attr.depend]p2:
3043 // The first declaration of a function shall specify the
3044 // carries_dependency attribute for its declarator-id if any declaration
3045 // of the function specifies the carries_dependency attribute.
3046 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3047 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3048 S.Diag(CDA->getLocation(),
3049 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3050 // Find the first declaration of the parameter.
3051 // FIXME: Should we build redeclaration chains for function parameters?
3052 const FunctionDecl *FirstFD =
3053 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3054 const ParmVarDecl *FirstVD =
3055 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3056 S.Diag(FirstVD->getLocation(),
3057 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3058 }
3059
3060 if (!oldDecl->hasAttrs())
3061 return;
3062
3063 bool foundAny = newDecl->hasAttrs();
3064
3065 // Ensure that any moving of objects within the allocated map is
3066 // done before we process them.
3067 if (!foundAny) newDecl->setAttrs(AttrVec());
3068
3069 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3070 if (!DeclHasAttr(newDecl, I)) {
3071 InheritableAttr *newAttr =
3072 cast<InheritableParamAttr>(I->clone(S.Context));
3073 newAttr->setInherited(true);
3074 newDecl->addAttr(newAttr);
3075 foundAny = true;
3076 }
3077 }
3078
3079 if (!foundAny) newDecl->dropAttrs();
3080}
3081
3082static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3083 const ParmVarDecl *OldParam,
3084 Sema &S) {
3085 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3086 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3087 if (*Oldnullability != *Newnullability) {
3088 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3089 << DiagNullabilityKind(
3090 *Newnullability,
3091 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3092 != 0))
3093 << DiagNullabilityKind(
3094 *Oldnullability,
3095 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3096 != 0));
3097 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3098 }
3099 } else {
3100 QualType NewT = NewParam->getType();
3101 NewT = S.Context.getAttributedType(
3102 AttributedType::getNullabilityAttrKind(*Oldnullability),
3103 NewT, NewT);
3104 NewParam->setType(NewT);
3105 }
3106 }
3107}
3108
3109namespace {
3110
3111/// Used in MergeFunctionDecl to keep track of function parameters in
3112/// C.
3113struct GNUCompatibleParamWarning {
3114 ParmVarDecl *OldParm;
3115 ParmVarDecl *NewParm;
3116 QualType PromotedType;
3117};
3118
3119} // end anonymous namespace
3120
3121// Determine whether the previous declaration was a definition, implicit
3122// declaration, or a declaration.
3123template <typename T>
3124static std::pair<diag::kind, SourceLocation>
3125getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3126 diag::kind PrevDiag;
3127 SourceLocation OldLocation = Old->getLocation();
3128 if (Old->isThisDeclarationADefinition())
3129 PrevDiag = diag::note_previous_definition;
3130 else if (Old->isImplicit()) {
3131 PrevDiag = diag::note_previous_implicit_declaration;
3132 if (OldLocation.isInvalid())
3133 OldLocation = New->getLocation();
3134 } else
3135 PrevDiag = diag::note_previous_declaration;
3136 return std::make_pair(PrevDiag, OldLocation);
3137}
3138
3139/// canRedefineFunction - checks if a function can be redefined. Currently,
3140/// only extern inline functions can be redefined, and even then only in
3141/// GNU89 mode.
3142static bool canRedefineFunction(const FunctionDecl *FD,
3143 const LangOptions& LangOpts) {
3144 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3145 !LangOpts.CPlusPlus &&
3146 FD->isInlineSpecified() &&
3147 FD->getStorageClass() == SC_Extern);
3148}
3149
3150const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3151 const AttributedType *AT = T->getAs<AttributedType>();
3152 while (AT && !AT->isCallingConv())
3153 AT = AT->getModifiedType()->getAs<AttributedType>();
3154 return AT;
3155}
3156
3157template <typename T>
3158static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3159 const DeclContext *DC = Old->getDeclContext();
3160 if (DC->isRecord())
3161 return false;
3162
3163 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3164 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3165 return true;
3166 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3167 return true;
3168 return false;
3169}
3170
3171template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3172static bool isExternC(VarTemplateDecl *) { return false; }
3173static bool isExternC(FunctionTemplateDecl *) { return false; }
3174
3175/// Check whether a redeclaration of an entity introduced by a
3176/// using-declaration is valid, given that we know it's not an overload
3177/// (nor a hidden tag declaration).
3178template<typename ExpectedDecl>
3179static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3180 ExpectedDecl *New) {
3181 // C++11 [basic.scope.declarative]p4:
3182 // Given a set of declarations in a single declarative region, each of
3183 // which specifies the same unqualified name,
3184 // -- they shall all refer to the same entity, or all refer to functions
3185 // and function templates; or
3186 // -- exactly one declaration shall declare a class name or enumeration
3187 // name that is not a typedef name and the other declarations shall all
3188 // refer to the same variable or enumerator, or all refer to functions
3189 // and function templates; in this case the class name or enumeration
3190 // name is hidden (3.3.10).
3191
3192 // C++11 [namespace.udecl]p14:
3193 // If a function declaration in namespace scope or block scope has the
3194 // same name and the same parameter-type-list as a function introduced
3195 // by a using-declaration, and the declarations do not declare the same
3196 // function, the program is ill-formed.
3197
3198 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3199 if (Old &&
3200 !Old->getDeclContext()->getRedeclContext()->Equals(
3201 New->getDeclContext()->getRedeclContext()) &&
3202 !(isExternC(Old) && isExternC(New)))
3203 Old = nullptr;
3204
3205 if (!Old) {
3206 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3207 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3208 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3209 return true;
3210 }
3211 return false;
3212}
3213
3214static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3215 const FunctionDecl *B) {
3216 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3216, __extension__ __PRETTY_FUNCTION__))
;
3217
3218 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3219 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3220 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3221 if (AttrA == AttrB)
3222 return true;
3223 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3224 AttrA->isDynamic() == AttrB->isDynamic();
3225 };
3226
3227 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3228}
3229
3230/// If necessary, adjust the semantic declaration context for a qualified
3231/// declaration to name the correct inline namespace within the qualifier.
3232static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3233 DeclaratorDecl *OldD) {
3234 // The only case where we need to update the DeclContext is when
3235 // redeclaration lookup for a qualified name finds a declaration
3236 // in an inline namespace within the context named by the qualifier:
3237 //
3238 // inline namespace N { int f(); }
3239 // int ::f(); // Sema DC needs adjusting from :: to N::.
3240 //
3241 // For unqualified declarations, the semantic context *can* change
3242 // along the redeclaration chain (for local extern declarations,
3243 // extern "C" declarations, and friend declarations in particular).
3244 if (!NewD->getQualifier())
3245 return;
3246
3247 // NewD is probably already in the right context.
3248 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3249 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3250 if (NamedDC->Equals(SemaDC))
3251 return;
3252
3253 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
3254 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
3255 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
;
3256
3257 auto *LexDC = NewD->getLexicalDeclContext();
3258 auto FixSemaDC = [=](NamedDecl *D) {
3259 if (!D)
3260 return;
3261 D->setDeclContext(SemaDC);
3262 D->setLexicalDeclContext(LexDC);
3263 };
3264
3265 FixSemaDC(NewD);
3266 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3267 FixSemaDC(FD->getDescribedFunctionTemplate());
3268 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3269 FixSemaDC(VD->getDescribedVarTemplate());
3270}
3271
3272/// MergeFunctionDecl - We just parsed a function 'New' from
3273/// declarator D which has the same name and scope as a previous
3274/// declaration 'Old'. Figure out how to resolve this situation,
3275/// merging decls or emitting diagnostics as appropriate.
3276///
3277/// In C++, New and Old must be declarations that are not
3278/// overloaded. Use IsOverload to determine whether New and Old are
3279/// overloaded, and to select the Old declaration that New should be
3280/// merged with.
3281///
3282/// Returns true if there was an error, false otherwise.
3283bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3284 Scope *S, bool MergeTypeWithOld) {
3285 // Verify the old decl was also a function.
3286 FunctionDecl *Old = OldD->getAsFunction();
3287 if (!Old) {
3288 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3289 if (New->getFriendObjectKind()) {
3290 Diag(New->getLocation(), diag::err_using_decl_friend);
3291 Diag(Shadow->getTargetDecl()->getLocation(),
3292 diag::note_using_decl_target);
3293 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3294 << 0;
3295 return true;
3296 }
3297
3298 // Check whether the two declarations might declare the same function or
3299 // function template.
3300 if (FunctionTemplateDecl *NewTemplate =
3301 New->getDescribedFunctionTemplate()) {
3302 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3303 NewTemplate))
3304 return true;
3305 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3306 ->getAsFunction();
3307 } else {
3308 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3309 return true;
3310 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3311 }
3312 } else {
3313 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3314 << New->getDeclName();
3315 notePreviousDefinition(OldD, New->getLocation());
3316 return true;
3317 }
3318 }
3319
3320 // If the old declaration was found in an inline namespace and the new
3321 // declaration was qualified, update the DeclContext to match.
3322 adjustDeclContextForDeclaratorDecl(New, Old);
3323
3324 // If the old declaration is invalid, just give up here.
3325 if (Old->isInvalidDecl())
3326 return true;
3327
3328 // Disallow redeclaration of some builtins.
3329 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3330 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3331 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3332 << Old << Old->getType();
3333 return true;
3334 }
3335
3336 diag::kind PrevDiag;
3337 SourceLocation OldLocation;
3338 std::tie(PrevDiag, OldLocation) =
3339 getNoteDiagForInvalidRedeclaration(Old, New);
3340
3341 // Don't complain about this if we're in GNU89 mode and the old function
3342 // is an extern inline function.
3343 // Don't complain about specializations. They are not supposed to have
3344 // storage classes.
3345 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3346 New->getStorageClass() == SC_Static &&
3347 Old->hasExternalFormalLinkage() &&
3348 !New->getTemplateSpecializationInfo() &&
3349 !canRedefineFunction(Old, getLangOpts())) {
3350 if (getLangOpts().MicrosoftExt) {
3351 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3352 Diag(OldLocation, PrevDiag);
3353 } else {
3354 Diag(New->getLocation(), diag::err_static_non_static) << New;
3355 Diag(OldLocation, PrevDiag);
3356 return true;
3357 }
3358 }
3359
3360 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3361 if (!Old->hasAttr<InternalLinkageAttr>()) {
3362 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3363 << ILA;
3364 Diag(Old->getLocation(), diag::note_previous_declaration);
3365 New->dropAttr<InternalLinkageAttr>();
3366 }
3367
3368 if (auto *EA = New->getAttr<ErrorAttr>()) {
3369 if (!Old->hasAttr<ErrorAttr>()) {
3370 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3371 Diag(Old->getLocation(), diag::note_previous_declaration);
3372 New->dropAttr<ErrorAttr>();
3373 }
3374 }
3375
3376 if (CheckRedeclarationModuleOwnership(New, Old))
3377 return true;
3378
3379 if (!getLangOpts().CPlusPlus) {
3380 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3381 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3382 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3383 << New << OldOvl;
3384
3385 // Try our best to find a decl that actually has the overloadable
3386 // attribute for the note. In most cases (e.g. programs with only one
3387 // broken declaration/definition), this won't matter.
3388 //
3389 // FIXME: We could do this if we juggled some extra state in
3390 // OverloadableAttr, rather than just removing it.
3391 const Decl *DiagOld = Old;
3392 if (OldOvl) {
3393 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3394 const auto *A = D->getAttr<OverloadableAttr>();
3395 return A && !A->isImplicit();
3396 });
3397 // If we've implicitly added *all* of the overloadable attrs to this
3398 // chain, emitting a "previous redecl" note is pointless.
3399 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3400 }
3401
3402 if (DiagOld)
3403 Diag(DiagOld->getLocation(),
3404 diag::note_attribute_overloadable_prev_overload)
3405 << OldOvl;
3406
3407 if (OldOvl)
3408 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3409 else
3410 New->dropAttr<OverloadableAttr>();
3411 }
3412 }
3413
3414 // If a function is first declared with a calling convention, but is later
3415 // declared or defined without one, all following decls assume the calling
3416 // convention of the first.
3417 //
3418 // It's OK if a function is first declared without a calling convention,
3419 // but is later declared or defined with the default calling convention.
3420 //
3421 // To test if either decl has an explicit calling convention, we look for
3422 // AttributedType sugar nodes on the type as written. If they are missing or
3423 // were canonicalized away, we assume the calling convention was implicit.
3424 //
3425 // Note also that we DO NOT return at this point, because we still have
3426 // other tests to run.
3427 QualType OldQType = Context.getCanonicalType(Old->getType());
3428 QualType NewQType = Context.getCanonicalType(New->getType());
3429 const FunctionType *OldType = cast<FunctionType>(OldQType);
3430 const FunctionType *NewType = cast<FunctionType>(NewQType);
3431 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3432 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3433 bool RequiresAdjustment = false;
3434
3435 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3436 FunctionDecl *First = Old->getFirstDecl();
3437 const FunctionType *FT =
3438 First->getType().getCanonicalType()->castAs<FunctionType>();
3439 FunctionType::ExtInfo FI = FT->getExtInfo();
3440 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3441 if (!NewCCExplicit) {
3442 // Inherit the CC from the previous declaration if it was specified
3443 // there but not here.
3444 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3445 RequiresAdjustment = true;
3446 } else if (Old->getBuiltinID()) {
3447 // Builtin attribute isn't propagated to the new one yet at this point,
3448 // so we check if the old one is a builtin.
3449
3450 // Calling Conventions on a Builtin aren't really useful and setting a
3451 // default calling convention and cdecl'ing some builtin redeclarations is
3452 // common, so warn and ignore the calling convention on the redeclaration.
3453 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3454 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3455 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3456 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3457 RequiresAdjustment = true;
3458 } else {
3459 // Calling conventions aren't compatible, so complain.
3460 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3461 Diag(New->getLocation(), diag::err_cconv_change)
3462 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3463 << !FirstCCExplicit
3464 << (!FirstCCExplicit ? "" :
3465 FunctionType::getNameForCallConv(FI.getCC()));
3466
3467 // Put the note on the first decl, since it is the one that matters.
3468 Diag(First->getLocation(), diag::note_previous_declaration);
3469 return true;
3470 }
3471 }
3472
3473 // FIXME: diagnose the other way around?
3474 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3475 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3476 RequiresAdjustment = true;
3477 }
3478
3479 // Merge regparm attribute.
3480 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3481 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3482 if (NewTypeInfo.getHasRegParm()) {
3483 Diag(New->getLocation(), diag::err_regparm_mismatch)
3484 << NewType->getRegParmType()
3485 << OldType->getRegParmType();
3486 Diag(OldLocation, diag::note_previous_declaration);
3487 return true;
3488 }
3489
3490 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3491 RequiresAdjustment = true;
3492 }
3493
3494 // Merge ns_returns_retained attribute.
3495 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3496 if (NewTypeInfo.getProducesResult()) {
3497 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3498 << "'ns_returns_retained'";
3499 Diag(OldLocation, diag::note_previous_declaration);
3500 return true;
3501 }
3502
3503 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3504 RequiresAdjustment = true;
3505 }
3506
3507 if (OldTypeInfo.getNoCallerSavedRegs() !=
3508 NewTypeInfo.getNoCallerSavedRegs()) {
3509 if (NewTypeInfo.getNoCallerSavedRegs()) {
3510 AnyX86NoCallerSavedRegistersAttr *Attr =
3511 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3512 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3513 Diag(OldLocation, diag::note_previous_declaration);
3514 return true;
3515 }
3516
3517 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3518 RequiresAdjustment = true;
3519 }
3520
3521 if (RequiresAdjustment) {
3522 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3523 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3524 New->setType(QualType(AdjustedType, 0));
3525 NewQType = Context.getCanonicalType(New->getType());
3526 }
3527
3528 // If this redeclaration makes the function inline, we may need to add it to
3529 // UndefinedButUsed.
3530 if (!Old->isInlined() && New->isInlined() &&
3531 !New->hasAttr<GNUInlineAttr>() &&
3532 !getLangOpts().GNUInline &&
3533 Old->isUsed(false) &&
3534 !Old->isDefined() && !New->isThisDeclarationADefinition())
3535 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3536 SourceLocation()));
3537
3538 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3539 // about it.
3540 if (New->hasAttr<GNUInlineAttr>() &&
3541 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3542 UndefinedButUsed.erase(Old->getCanonicalDecl());
3543 }
3544
3545 // If pass_object_size params don't match up perfectly, this isn't a valid
3546 // redeclaration.
3547 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3548 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3549 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3550 << New->getDeclName();
3551 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3552 return true;
3553 }
3554
3555 if (getLangOpts().CPlusPlus) {
3556 // C++1z [over.load]p2
3557 // Certain function declarations cannot be overloaded:
3558 // -- Function declarations that differ only in the return type,
3559 // the exception specification, or both cannot be overloaded.
3560
3561 // Check the exception specifications match. This may recompute the type of
3562 // both Old and New if it resolved exception specifications, so grab the
3563 // types again after this. Because this updates the type, we do this before
3564 // any of the other checks below, which may update the "de facto" NewQType
3565 // but do not necessarily update the type of New.
3566 if (CheckEquivalentExceptionSpec(Old, New))
3567 return true;
3568 OldQType = Context.getCanonicalType(Old->getType());
3569 NewQType = Context.getCanonicalType(New->getType());
3570
3571 // Go back to the type source info to compare the declared return types,
3572 // per C++1y [dcl.type.auto]p13:
3573 // Redeclarations or specializations of a function or function template
3574 // with a declared return type that uses a placeholder type shall also
3575 // use that placeholder, not a deduced type.
3576 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3577 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3578 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3579 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3580 OldDeclaredReturnType)) {
3581 QualType ResQT;
3582 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3583 OldDeclaredReturnType->isObjCObjectPointerType())
3584 // FIXME: This does the wrong thing for a deduced return type.
3585 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3586 if (ResQT.isNull()) {
3587 if (New->isCXXClassMember() && New->isOutOfLine())
3588 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3589 << New << New->getReturnTypeSourceRange();
3590 else
3591 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3592 << New->getReturnTypeSourceRange();
3593 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3594 << Old->getReturnTypeSourceRange();
3595 return true;
3596 }
3597 else
3598 NewQType = ResQT;
3599 }
3600
3601 QualType OldReturnType = OldType->getReturnType();
3602 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3603 if (OldReturnType != NewReturnType) {
3604 // If this function has a deduced return type and has already been
3605 // defined, copy the deduced value from the old declaration.
3606 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3607 if (OldAT && OldAT->isDeduced()) {
3608 New->setType(
3609 SubstAutoType(New->getType(),
3610 OldAT->isDependentType() ? Context.DependentTy
3611 : OldAT->getDeducedType()));
3612 NewQType = Context.getCanonicalType(
3613 SubstAutoType(NewQType,
3614 OldAT->isDependentType() ? Context.DependentTy
3615 : OldAT->getDeducedType()));
3616 }
3617 }
3618
3619 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3620 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3621 if (OldMethod && NewMethod) {
3622 // Preserve triviality.
3623 NewMethod->setTrivial(OldMethod->isTrivial());
3624
3625 // MSVC allows explicit template specialization at class scope:
3626 // 2 CXXMethodDecls referring to the same function will be injected.
3627 // We don't want a redeclaration error.
3628 bool IsClassScopeExplicitSpecialization =
3629 OldMethod->isFunctionTemplateSpecialization() &&
3630 NewMethod->isFunctionTemplateSpecialization();
3631 bool isFriend = NewMethod->getFriendObjectKind();
3632
3633 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3634 !IsClassScopeExplicitSpecialization) {
3635 // -- Member function declarations with the same name and the
3636 // same parameter types cannot be overloaded if any of them
3637 // is a static member function declaration.
3638 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3639 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3640 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3641 return true;
3642 }
3643
3644 // C++ [class.mem]p1:
3645 // [...] A member shall not be declared twice in the
3646 // member-specification, except that a nested class or member
3647 // class template can be declared and then later defined.
3648 if (!inTemplateInstantiation()) {
3649 unsigned NewDiag;
3650 if (isa<CXXConstructorDecl>(OldMethod))
3651 NewDiag = diag::err_constructor_redeclared;
3652 else if (isa<CXXDestructorDecl>(NewMethod))
3653 NewDiag = diag::err_destructor_redeclared;
3654 else if (isa<CXXConversionDecl>(NewMethod))
3655 NewDiag = diag::err_conv_function_redeclared;
3656 else
3657 NewDiag = diag::err_member_redeclared;
3658
3659 Diag(New->getLocation(), NewDiag);
3660 } else {
3661 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3662 << New << New->getType();
3663 }
3664 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3665 return true;
3666
3667 // Complain if this is an explicit declaration of a special
3668 // member that was initially declared implicitly.
3669 //
3670 // As an exception, it's okay to befriend such methods in order
3671 // to permit the implicit constructor/destructor/operator calls.
3672 } else if (OldMethod->isImplicit()) {
3673 if (isFriend) {
3674 NewMethod->setImplicit();
3675 } else {
3676 Diag(NewMethod->getLocation(),
3677 diag::err_definition_of_implicitly_declared_member)
3678 << New << getSpecialMember(OldMethod);
3679 return true;
3680 }
3681 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3682 Diag(NewMethod->getLocation(),
3683 diag::err_definition_of_explicitly_defaulted_member)
3684 << getSpecialMember(OldMethod);
3685 return true;
3686 }
3687 }
3688
3689 // C++11 [dcl.attr.noreturn]p1:
3690 // The first declaration of a function shall specify the noreturn
3691 // attribute if any declaration of that function specifies the noreturn
3692 // attribute.
3693 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3694 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3695 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3696 << NRA;
3697 Diag(Old->getLocation(), diag::note_previous_declaration);
3698 }
3699
3700 // C++11 [dcl.attr.depend]p2:
3701 // The first declaration of a function shall specify the
3702 // carries_dependency attribute for its declarator-id if any declaration
3703 // of the function specifies the carries_dependency attribute.
3704 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3705 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3706 Diag(CDA->getLocation(),
3707 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3708 Diag(Old->getFirstDecl()->getLocation(),
3709 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3710 }
3711
3712 // (C++98 8.3.5p3):
3713 // All declarations for a function shall agree exactly in both the
3714 // return type and the parameter-type-list.
3715 // We also want to respect all the extended bits except noreturn.
3716
3717 // noreturn should now match unless the old type info didn't have it.
3718 QualType OldQTypeForComparison = OldQType;
3719 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3720 auto *OldType = OldQType->castAs<FunctionProtoType>();
3721 const FunctionType *OldTypeForComparison
3722 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3723 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3724 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3724, __extension__ __PRETTY_FUNCTION__))
;
3725 }
3726
3727 if (haveIncompatibleLanguageLinkages(Old, New)) {
3728 // As a special case, retain the language linkage from previous
3729 // declarations of a friend function as an extension.
3730 //
3731 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3732 // and is useful because there's otherwise no way to specify language
3733 // linkage within class scope.
3734 //
3735 // Check cautiously as the friend object kind isn't yet complete.
3736 if (New->getFriendObjectKind() != Decl::FOK_None) {
3737 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3738 Diag(OldLocation, PrevDiag);
3739 } else {
3740 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3741 Diag(OldLocation, PrevDiag);
3742 return true;
3743 }
3744 }
3745
3746 // If the function types are compatible, merge the declarations. Ignore the
3747 // exception specifier because it was already checked above in
3748 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3749 // about incompatible types under -fms-compatibility.
3750 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3751 NewQType))
3752 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3753
3754 // If the types are imprecise (due to dependent constructs in friends or
3755 // local extern declarations), it's OK if they differ. We'll check again
3756 // during instantiation.
3757 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3758 return false;
3759
3760 // Fall through for conflicting redeclarations and redefinitions.
3761 }
3762
3763 // C: Function types need to be compatible, not identical. This handles
3764 // duplicate function decls like "void f(int); void f(enum X);" properly.
3765 if (!getLangOpts().CPlusPlus &&
3766 Context.typesAreCompatible(OldQType, NewQType)) {
3767 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3768 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3769 const FunctionProtoType *OldProto = nullptr;
3770 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3771 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3772 // The old declaration provided a function prototype, but the
3773 // new declaration does not. Merge in the prototype.
3774 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3774, __extension__ __PRETTY_FUNCTION__))
;
3775 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3776 NewQType =
3777 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3778 OldProto->getExtProtoInfo());
3779 New->setType(NewQType);
3780 New->setHasInheritedPrototype();
3781
3782 // Synthesize parameters with the same types.
3783 SmallVector<ParmVarDecl*, 16> Params;
3784 for (const auto &ParamType : OldProto->param_types()) {
3785 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3786 SourceLocation(), nullptr,
3787 ParamType, /*TInfo=*/nullptr,
3788 SC_None, nullptr);
3789 Param->setScopeInfo(0, Params.size());
3790 Param->setImplicit();
3791 Params.push_back(Param);
3792 }
3793
3794 New->setParams(Params);
3795 }
3796
3797 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3798 }
3799
3800 // Check if the function types are compatible when pointer size address
3801 // spaces are ignored.
3802 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3803 return false;
3804
3805 // GNU C permits a K&R definition to follow a prototype declaration
3806 // if the declared types of the parameters in the K&R definition
3807 // match the types in the prototype declaration, even when the
3808 // promoted types of the parameters from the K&R definition differ
3809 // from the types in the prototype. GCC then keeps the types from
3810 // the prototype.
3811 //
3812 // If a variadic prototype is followed by a non-variadic K&R definition,
3813 // the K&R definition becomes variadic. This is sort of an edge case, but
3814 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3815 // C99 6.9.1p8.
3816 if (!getLangOpts().CPlusPlus &&
3817 Old->hasPrototype() && !New->hasPrototype() &&
3818 New->getType()->getAs<FunctionProtoType>() &&
3819 Old->getNumParams() == New->getNumParams()) {
3820 SmallVector<QualType, 16> ArgTypes;
3821 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3822 const FunctionProtoType *OldProto
3823 = Old->getType()->getAs<FunctionProtoType>();
3824 const FunctionProtoType *NewProto
3825 = New->getType()->getAs<FunctionProtoType>();
3826
3827 // Determine whether this is the GNU C extension.
3828 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3829 NewProto->getReturnType());
3830 bool LooseCompatible = !MergedReturn.isNull();
3831 for (unsigned Idx = 0, End = Old->getNumParams();
3832 LooseCompatible && Idx != End; ++Idx) {
3833 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3834 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3835 if (Context.typesAreCompatible(OldParm->getType(),
3836 NewProto->getParamType(Idx))) {
3837 ArgTypes.push_back(NewParm->getType());
3838 } else if (Context.typesAreCompatible(OldParm->getType(),
3839 NewParm->getType(),
3840 /*CompareUnqualified=*/true)) {
3841 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3842 NewProto->getParamType(Idx) };
3843 Warnings.push_back(Warn);
3844 ArgTypes.push_back(NewParm->getType());
3845 } else
3846 LooseCompatible = false;
3847 }
3848
3849 if (LooseCompatible) {
3850 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3851 Diag(Warnings[Warn].NewParm->getLocation(),
3852 diag::ext_param_promoted_not_compatible_with_prototype)
3853 << Warnings[Warn].PromotedType
3854 << Warnings[Warn].OldParm->getType();
3855 if (Warnings[Warn].OldParm->getLocation().isValid())
3856 Diag(Warnings[Warn].OldParm->getLocation(),
3857 diag::note_previous_declaration);
3858 }
3859
3860 if (MergeTypeWithOld)
3861 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3862 OldProto->getExtProtoInfo()));
3863 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3864 }
3865
3866 // Fall through to diagnose conflicting types.
3867 }
3868
3869 // A function that has already been declared has been redeclared or
3870 // defined with a different type; show an appropriate diagnostic.
3871
3872 // If the previous declaration was an implicitly-generated builtin
3873 // declaration, then at the very least we should use a specialized note.
3874 unsigned BuiltinID;
3875 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3876 // If it's actually a library-defined builtin function like 'malloc'
3877 // or 'printf', just warn about the incompatible redeclaration.
3878 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3879 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3880 Diag(OldLocation, diag::note_previous_builtin_declaration)
3881 << Old << Old->getType();
3882 return false;
3883 }
3884
3885 PrevDiag = diag::note_previous_builtin_declaration;
3886 }
3887
3888 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3889 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3890 return true;
3891}
3892
3893/// Completes the merge of two function declarations that are
3894/// known to be compatible.
3895///
3896/// This routine handles the merging of attributes and other
3897/// properties of function declarations from the old declaration to
3898/// the new declaration, once we know that New is in fact a
3899/// redeclaration of Old.
3900///
3901/// \returns false
3902bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3903 Scope *S, bool MergeTypeWithOld) {
3904 // Merge the attributes
3905 mergeDeclAttributes(New, Old);
3906
3907 // Merge "pure" flag.
3908 if (Old->isPure())
3909 New->setPure();
3910
3911 // Merge "used" flag.
3912 if (Old->getMostRecentDecl()->isUsed(false))
3913 New->setIsUsed();
3914
3915 // Merge attributes from the parameters. These can mismatch with K&R
3916 // declarations.
3917 if (New->getNumParams() == Old->getNumParams())
3918 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3919 ParmVarDecl *NewParam = New->getParamDecl(i);
3920 ParmVarDecl *OldParam = Old->getParamDecl(i);
3921 mergeParamDeclAttributes(NewParam, OldParam, *this);
3922 mergeParamDeclTypes(NewParam, OldParam, *this);
3923 }
3924
3925 if (getLangOpts().CPlusPlus)
3926 return MergeCXXFunctionDecl(New, Old, S);
3927
3928 // Merge the function types so the we get the composite types for the return
3929 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3930 // was visible.
3931 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3932 if (!Merged.isNull() && MergeTypeWithOld)
3933 New->setType(Merged);
3934
3935 return false;
3936}
3937
3938void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3939 ObjCMethodDecl *oldMethod) {
3940 // Merge the attributes, including deprecated/unavailable
3941 AvailabilityMergeKind MergeKind =
3942 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3943 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3944 : AMK_ProtocolImplementation)
3945 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3946 : AMK_Override;
3947
3948 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3949
3950 // Merge attributes from the parameters.
3951 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3952 oe = oldMethod->param_end();
3953 for (ObjCMethodDecl::param_iterator
3954 ni = newMethod->param_begin(), ne = newMethod->param_end();
3955 ni != ne && oi != oe; ++ni, ++oi)
3956 mergeParamDeclAttributes(*ni, *oi, *this);
3957
3958 CheckObjCMethodOverride(newMethod, oldMethod);
3959}
3960
3961static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3962 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3962, __extension__ __PRETTY_FUNCTION__))
;
3963
3964 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3965 ? diag::err_redefinition_different_type
3966 : diag::err_redeclaration_different_type)
3967 << New->getDeclName() << New->getType() << Old->getType();
3968
3969 diag::kind PrevDiag;
3970 SourceLocation OldLocation;
3971 std::tie(PrevDiag, OldLocation)
3972 = getNoteDiagForInvalidRedeclaration(Old, New);
3973 S.Diag(OldLocation, PrevDiag);
3974 New->setInvalidDecl();
3975}
3976
3977/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3978/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3979/// emitting diagnostics as appropriate.
3980///
3981/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3982/// to here in AddInitializerToDecl. We can't check them before the initializer
3983/// is attached.
3984void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3985 bool MergeTypeWithOld) {
3986 if (New->isInvalidDecl() || Old->isInvalidDecl())
3987 return;
3988
3989 QualType MergedT;
3990 if (getLangOpts().CPlusPlus) {
3991 if (New->getType()->isUndeducedType()) {
3992 // We don't know what the new type is until the initializer is attached.
3993 return;
3994 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3995 // These could still be something that needs exception specs checked.
3996 return MergeVarDeclExceptionSpecs(New, Old);
3997 }
3998 // C++ [basic.link]p10:
3999 // [...] the types specified by all declarations referring to a given
4000 // object or function shall be identical, except that declarations for an
4001 // array object can specify array types that differ by the presence or
4002 // absence of a major array bound (8.3.4).
4003 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4004 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4005 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4006
4007 // We are merging a variable declaration New into Old. If it has an array
4008 // bound, and that bound differs from Old's bound, we should diagnose the
4009 // mismatch.
4010 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4011 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4012 PrevVD = PrevVD->getPreviousDecl()) {
4013 QualType PrevVDTy = PrevVD->getType();
4014 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4015 continue;
4016
4017 if (!Context.hasSameType(New->getType(), PrevVDTy))
4018 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4019 }
4020 }
4021
4022 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4023 if (Context.hasSameType(OldArray->getElementType(),
4024 NewArray->getElementType()))
4025 MergedT = New->getType();
4026 }
4027 // FIXME: Check visibility. New is hidden but has a complete type. If New
4028 // has no array bound, it should not inherit one from Old, if Old is not
4029 // visible.
4030 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4031 if (Context.hasSameType(OldArray->getElementType(),
4032 NewArray->getElementType()))
4033 MergedT = Old->getType();
4034 }
4035 }
4036 else if (New->getType()->isObjCObjectPointerType() &&
4037 Old->getType()->isObjCObjectPointerType()) {
4038 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4039 Old->getType());
4040 }
4041 } else {
4042 // C 6.2.7p2:
4043 // All declarations that refer to the same object or function shall have
4044 // compatible type.
4045 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4046 }
4047 if (MergedT.isNull()) {
4048 // It's OK if we couldn't merge types if either type is dependent, for a
4049 // block-scope variable. In other cases (static data members of class
4050 // templates, variable templates, ...), we require the types to be
4051 // equivalent.
4052 // FIXME: The C++ standard doesn't say anything about this.
4053 if ((New->getType()->isDependentType() ||
4054 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4055 // If the old type was dependent, we can't merge with it, so the new type
4056 // becomes dependent for now. We'll reproduce the original type when we
4057 // instantiate the TypeSourceInfo for the variable.
4058 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4059 New->setType(Context.DependentTy);
4060 return;
4061 }
4062 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4063 }
4064
4065 // Don't actually update the type on the new declaration if the old
4066 // declaration was an extern declaration in a different scope.
4067 if (MergeTypeWithOld)
4068 New->setType(MergedT);
4069}
4070
4071static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4072 LookupResult &Previous) {
4073 // C11 6.2.7p4:
4074 // For an identifier with internal or external linkage declared
4075 // in a scope in which a prior declaration of that identifier is
4076 // visible, if the prior declaration specifies internal or
4077 // external linkage, the type of the identifier at the later
4078 // declaration becomes the composite type.
4079 //
4080 // If the variable isn't visible, we do not merge with its type.
4081 if (Previous.isShadowed())
4082 return false;
4083
4084 if (S.getLangOpts().CPlusPlus) {
4085 // C++11 [dcl.array]p3:
4086 // If there is a preceding declaration of the entity in the same
4087 // scope in which the bound was specified, an omitted array bound
4088 // is taken to be the same as in that earlier declaration.
4089 return NewVD->isPreviousDeclInSameBlockScope() ||
4090 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4091 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4092 } else {
4093 // If the old declaration was function-local, don't merge with its
4094 // type unless we're in the same function.
4095 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4096 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4097 }
4098}
4099
4100/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4101/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4102/// situation, merging decls or emitting diagnostics as appropriate.
4103///
4104/// Tentative definition rules (C99 6.9.2p2) are checked by
4105/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4106/// definitions here, since the initializer hasn't been attached.
4107///
4108void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4109 // If the new decl is already invalid, don't do any other checking.
4110 if (New->isInvalidDecl())
4111 return;
4112
4113 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4114 return;
4115
4116 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4117
4118 // Verify the old decl was also a variable or variable template.
4119 VarDecl *Old = nullptr;
4120 VarTemplateDecl *OldTemplate = nullptr;
4121 if (Previous.isSingleResult()) {
4122 if (NewTemplate) {
4123 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4124 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4125
4126 if (auto *Shadow =
4127 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4128 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4129 return New->setInvalidDecl();
4130 } else {
4131 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4132
4133 if (auto *Shadow =
4134 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4135 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4136 return New->setInvalidDecl();
4137 }
4138 }
4139 if (!Old) {
4140 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4141 << New->getDeclName();
4142 notePreviousDefinition(Previous.getRepresentativeDecl(),
4143 New->getLocation());
4144 return New->setInvalidDecl();
4145 }
4146
4147 // If the old declaration was found in an inline namespace and the new
4148 // declaration was qualified, update the DeclContext to match.
4149 adjustDeclContextForDeclaratorDecl(New, Old);
4150
4151 // Ensure the template parameters are compatible.
4152 if (NewTemplate &&
4153 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4154 OldTemplate->getTemplateParameters(),
4155 /*Complain=*/true, TPL_TemplateMatch))
4156 return New->setInvalidDecl();
4157
4158 // C++ [class.mem]p1:
4159 // A member shall not be declared twice in the member-specification [...]
4160 //
4161 // Here, we need only consider static data members.
4162 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4163 Diag(New->getLocation(), diag::err_duplicate_member)
4164 << New->getIdentifier();
4165 Diag(Old->getLocation(), diag::note_previous_declaration);
4166 New->setInvalidDecl();
4167 }
4168
4169 mergeDeclAttributes(New, Old);
4170 // Warn if an already-declared variable is made a weak_import in a subsequent
4171 // declaration
4172 if (New->hasAttr<WeakImportAttr>() &&
4173 Old->getStorageClass() == SC_None &&
4174 !Old->hasAttr<WeakImportAttr>()) {
4175 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4176 Diag(Old->getLocation(), diag::note_previous_declaration);
4177 // Remove weak_import attribute on new declaration.
4178 New->dropAttr<WeakImportAttr>();
4179 }
4180
4181 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4182 if (!Old->hasAttr<InternalLinkageAttr>()) {
4183 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4184 << ILA;
4185 Diag(Old->getLocation(), diag::note_previous_declaration);
4186 New->dropAttr<InternalLinkageAttr>();
4187 }
4188
4189 // Merge the types.
4190 VarDecl *MostRecent = Old->getMostRecentDecl();
4191 if (MostRecent != Old) {
4192 MergeVarDeclTypes(New, MostRecent,
4193 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4194 if (New->isInvalidDecl())
4195 return;
4196 }
4197
4198 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4199 if (New->isInvalidDecl())
4200 return;
4201
4202 diag::kind PrevDiag;
4203 SourceLocation OldLocation;
4204 std::tie(PrevDiag, OldLocation) =
4205 getNoteDiagForInvalidRedeclaration(Old, New);
4206
4207 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4208 if (New->getStorageClass() == SC_Static &&
4209 !New->isStaticDataMember() &&
4210 Old->hasExternalFormalLinkage()) {
4211 if (getLangOpts().MicrosoftExt) {
4212 Diag(New->getLocation(), diag::ext_static_non_static)
4213 << New->getDeclName();
4214 Diag(OldLocation, PrevDiag);
4215 } else {
4216 Diag(New->getLocation(), diag::err_static_non_static)
4217 << New->getDeclName();
4218 Diag(OldLocation, PrevDiag);
4219 return New->setInvalidDecl();
4220 }
4221 }
4222 // C99 6.2.2p4:
4223 // For an identifier declared with the storage-class specifier
4224 // extern in a scope in which a prior declaration of that
4225 // identifier is visible,23) if the prior declaration specifies
4226 // internal or external linkage, the linkage of the identifier at
4227 // the later declaration is the same as the linkage specified at
4228 // the prior declaration. If no prior declaration is visible, or
4229 // if the prior declaration specifies no linkage, then the
4230 // identifier has external linkage.
4231 if (New->hasExternalStorage() && Old->hasLinkage())
4232 /* Okay */;
4233 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4234 !New->isStaticDataMember() &&
4235 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4236 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4237 Diag(OldLocation, PrevDiag);
4238 return New->setInvalidDecl();
4239 }
4240
4241 // Check if extern is followed by non-extern and vice-versa.
4242 if (New->hasExternalStorage() &&
4243 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4244 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4245 Diag(OldLocation, PrevDiag);
4246 return New->setInvalidDecl();
4247 }
4248 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4249 !New->hasExternalStorage()) {
4250 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4251 Diag(OldLocation, PrevDiag);
4252 return New->setInvalidDecl();
4253 }
4254
4255 if (CheckRedeclarationModuleOwnership(New, Old))
4256 return;
4257
4258 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4259
4260 // FIXME: The test for external storage here seems wrong? We still
4261 // need to check for mismatches.
4262 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4263 // Don't complain about out-of-line definitions of static members.
4264 !(Old->getLexicalDeclContext()->isRecord() &&
4265 !New->getLexicalDeclContext()->isRecord())) {
4266 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4267 Diag(OldLocation, PrevDiag);
4268 return New->setInvalidDecl();
4269 }
4270
4271 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4272 if (VarDecl *Def = Old->getDefinition()) {
4273 // C++1z [dcl.fcn.spec]p4:
4274 // If the definition of a variable appears in a translation unit before
4275 // its first declaration as inline, the program is ill-formed.
4276 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4277 Diag(Def->getLocation(), diag::note_previous_definition);
4278 }
4279 }
4280
4281 // If this redeclaration makes the variable inline, we may need to add it to
4282 // UndefinedButUsed.
4283 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4284 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4285 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4286 SourceLocation()));
4287
4288 if (New->getTLSKind() != Old->getTLSKind()) {
4289 if (!Old->getTLSKind()) {
4290 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4291 Diag(OldLocation, PrevDiag);
4292 } else if (!New->getTLSKind()) {
4293 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4294 Diag(OldLocation, PrevDiag);
4295 } else {
4296 // Do not allow redeclaration to change the variable between requiring
4297 // static and dynamic initialization.
4298 // FIXME: GCC allows this, but uses the TLS keyword on the first
4299 // declaration to determine the kind. Do we need to be compatible here?
4300 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4301 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4302 Diag(OldLocation, PrevDiag);
4303 }
4304 }
4305
4306 // C++ doesn't have tentative definitions, so go right ahead and check here.
4307 if (getLangOpts().CPlusPlus &&
4308 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4309 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4310 Old->getCanonicalDecl()->isConstexpr()) {
4311 // This definition won't be a definition any more once it's been merged.
4312 Diag(New->getLocation(),
4313 diag::warn_deprecated_redundant_constexpr_static_def);
4314 } else if (VarDecl *Def = Old->getDefinition()) {
4315 if (checkVarDeclRedefinition(Def, New))
4316 return;
4317 }
4318 }
4319
4320 if (haveIncompatibleLanguageLinkages(Old, New)) {
4321 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4322 Diag(OldLocation, PrevDiag);
4323 New->setInvalidDecl();
4324 return;
4325 }
4326
4327 // Merge "used" flag.
4328 if (Old->getMostRecentDecl()->isUsed(false))
4329 New->setIsUsed();
4330
4331 // Keep a chain of previous declarations.
4332 New->setPreviousDecl(Old);
4333 if (NewTemplate)
4334 NewTemplate->setPreviousDecl(OldTemplate);
4335
4336 // Inherit access appropriately.
4337 New->setAccess(Old->getAccess());
4338 if (NewTemplate)
4339 NewTemplate->setAccess(New->getAccess());
4340
4341 if (Old->isInline())
4342 New->setImplicitlyInline();
4343}
4344
4345void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4346 SourceManager &SrcMgr = getSourceManager();
4347 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4348 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4349 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4350 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4351 auto &HSI = PP.getHeaderSearchInfo();
4352 StringRef HdrFilename =
4353 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4354
4355 auto noteFromModuleOrInclude = [&](Module *Mod,
4356 SourceLocation IncLoc) -> bool {
4357 // Redefinition errors with modules are common with non modular mapped
4358 // headers, example: a non-modular header H in module A that also gets
4359 // included directly in a TU. Pointing twice to the same header/definition
4360 // is confusing, try to get better diagnostics when modules is on.
4361 if (IncLoc.isValid()) {
4362 if (Mod) {
4363 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4364 << HdrFilename.str() << Mod->getFullModuleName();
4365 if (!Mod->DefinitionLoc.isInvalid())
4366 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4367 << Mod->getFullModuleName();
4368 } else {
4369 Diag(IncLoc, diag::note_redefinition_include_same_file)
4370 << HdrFilename.str();
4371 }
4372 return true;
4373 }
4374
4375 return false;
4376 };
4377
4378 // Is it the same file and same offset? Provide more information on why
4379 // this leads to a redefinition error.
4380 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4381 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4382 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4383 bool EmittedDiag =
4384 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4385 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4386
4387 // If the header has no guards, emit a note suggesting one.
4388 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4389 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4390
4391 if (EmittedDiag)
4392 return;
4393 }
4394
4395 // Redefinition coming from different files or couldn't do better above.
4396 if (Old->getLocation().isValid())
4397 Diag(Old->getLocation(), diag::note_previous_definition);
4398}
4399
4400/// We've just determined that \p Old and \p New both appear to be definitions
4401/// of the same variable. Either diagnose or fix the problem.
4402bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4403 if (!hasVisibleDefinition(Old) &&
4404 (New->getFormalLinkage() == InternalLinkage ||
4405 New->isInline() ||
4406 New->getDescribedVarTemplate() ||
4407 New->getNumTemplateParameterLists() ||
4408 New->getDeclContext()->isDependentContext())) {
4409 // The previous definition is hidden, and multiple definitions are
4410 // permitted (in separate TUs). Demote this to a declaration.
4411 New->demoteThisDefinitionToDeclaration();
4412
4413 // Make the canonical definition visible.
4414 if (auto *OldTD = Old->getDescribedVarTemplate())
4415 makeMergedDefinitionVisible(OldTD);
4416 makeMergedDefinitionVisible(Old);
4417 return false;
4418 } else {
4419 Diag(New->getLocation(), diag::err_redefinition) << New;
4420 notePreviousDefinition(Old, New->getLocation());
4421 New->setInvalidDecl();
4422 return true;
4423 }
4424}
4425
4426/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4427/// no declarator (e.g. "struct foo;") is parsed.
4428Decl *
4429Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4430 RecordDecl *&AnonRecord) {
4431 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4432 AnonRecord);
4433}
4434
4435// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4436// disambiguate entities defined in different scopes.
4437// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4438// compatibility.
4439// We will pick our mangling number depending on which version of MSVC is being
4440// targeted.
4441static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4442 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4443 ? S->getMSCurManglingNumber()
4444 : S->getMSLastManglingNumber();
4445}
4446
4447void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4448 if (!Context.getLangOpts().CPlusPlus)
4449 return;
4450
4451 if (isa<CXXRecordDecl>(Tag->getParent())) {
4452 // If this tag is the direct child of a class, number it if
4453 // it is anonymous.
4454 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4455 return;
4456 MangleNumberingContext &MCtx =
4457 Context.getManglingNumberContext(Tag->getParent());
4458 Context.setManglingNumber(
4459 Tag, MCtx.getManglingNumber(
4460 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4461 return;
4462 }
4463
4464 // If this tag isn't a direct child of a class, number it if it is local.
4465 MangleNumberingContext *MCtx;
4466 Decl *ManglingContextDecl;
4467 std::tie(MCtx, ManglingContextDecl) =
4468 getCurrentMangleNumberContext(Tag->getDeclContext());
4469 if (MCtx) {
4470 Context.setManglingNumber(
4471 Tag, MCtx->getManglingNumber(
4472 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4473 }
4474}
4475
4476namespace {
4477struct NonCLikeKind {
4478 enum {
4479 None,
4480 BaseClass,
4481 DefaultMemberInit,
4482 Lambda,
4483 Friend,
4484 OtherMember,
4485 Invalid,
4486 } Kind = None;
4487 SourceRange Range;
4488
4489 explicit operator bool() { return Kind != None; }
4490};
4491}
4492
4493/// Determine whether a class is C-like, according to the rules of C++
4494/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4495static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4496 if (RD->isInvalidDecl())
4497 return {NonCLikeKind::Invalid, {}};
4498
4499 // C++ [dcl.typedef]p9: [P1766R1]
4500 // An unnamed class with a typedef name for linkage purposes shall not
4501 //
4502 // -- have any base classes
4503 if (RD->getNumBases())
4504 return {NonCLikeKind::BaseClass,
4505 SourceRange(RD->bases_begin()->getBeginLoc(),
4506 RD->bases_end()[-1].getEndLoc())};
4507 bool Invalid = false;
4508 for (Decl *D : RD->decls()) {
4509 // Don't complain about things we already diagnosed.
4510 if (D->isInvalidDecl()) {
4511 Invalid = true;
4512 continue;
4513 }
4514
4515 // -- have any [...] default member initializers
4516 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4517 if (FD->hasInClassInitializer()) {
4518 auto *Init = FD->getInClassInitializer();
4519 return {NonCLikeKind::DefaultMemberInit,
4520 Init ? Init->getSourceRange() : D->getSourceRange()};
4521 }
4522 continue;
4523 }
4524
4525 // FIXME: We don't allow friend declarations. This violates the wording of
4526 // P1766, but not the intent.
4527 if (isa<FriendDecl>(D))
4528 return {NonCLikeKind::Friend, D->getSourceRange()};
4529
4530 // -- declare any members other than non-static data members, member
4531 // enumerations, or member classes,
4532 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4533 isa<EnumDecl>(D))
4534 continue;
4535 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4536 if (!MemberRD) {
4537 if (D->isImplicit())
4538 continue;
4539 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4540 }
4541
4542 // -- contain a lambda-expression,
4543 if (MemberRD->isLambda())
4544 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4545
4546 // and all member classes shall also satisfy these requirements
4547 // (recursively).
4548 if (MemberRD->isThisDeclarationADefinition()) {
4549 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4550 return Kind;
4551 }
4552 }
4553
4554 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4555}
4556
4557void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4558 TypedefNameDecl *NewTD) {
4559 if (TagFromDeclSpec->isInvalidDecl())
4560 return;
4561
4562 // Do nothing if the tag already has a name for linkage purposes.
4563 if (TagFromDeclSpec->hasNameForLinkage())
4564 return;
4565
4566 // A well-formed anonymous tag must always be a TUK_Definition.
4567 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4567, __extension__ __PRETTY_FUNCTION__))
;
4568
4569 // The type must match the tag exactly; no qualifiers allowed.
4570 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4571 Context.getTagDeclType(TagFromDeclSpec))) {
4572 if (getLangOpts().CPlusPlus)
4573 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4574 return;
4575 }
4576
4577 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4578 // An unnamed class with a typedef name for linkage purposes shall [be
4579 // C-like].
4580 //
4581 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4582 // shouldn't happen, but there are constructs that the language rule doesn't
4583 // disallow for which we can't reasonably avoid computing linkage early.
4584 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4585 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4586 : NonCLikeKind();
4587 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4588 if (NonCLike || ChangesLinkage) {
4589 if (NonCLike.Kind == NonCLikeKind::Invalid)
4590 return;
4591
4592 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4593 if (ChangesLinkage) {
4594 // If the linkage changes, we can't accept this as an extension.
4595 if (NonCLike.Kind == NonCLikeKind::None)
4596 DiagID = diag::err_typedef_changes_linkage;
4597 else
4598 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4599 }
4600
4601 SourceLocation FixitLoc =
4602 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4603 llvm::SmallString<40> TextToInsert;
4604 TextToInsert += ' ';
4605 TextToInsert += NewTD->getIdentifier()->getName();
4606
4607 Diag(FixitLoc, DiagID)
4608 << isa<TypeAliasDecl>(NewTD)
4609 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4610 if (NonCLike.Kind != NonCLikeKind::None) {
4611 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4612 << NonCLike.Kind - 1 << NonCLike.Range;
4613 }
4614 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4615 << NewTD << isa<TypeAliasDecl>(NewTD);
4616
4617 if (ChangesLinkage)
4618 return;
4619 }
4620
4621 // Otherwise, set this as the anon-decl typedef for the tag.
4622 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4623}
4624
4625static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4626 switch (T) {
4627 case DeclSpec::TST_class:
4628 return 0;
4629 case DeclSpec::TST_struct:
4630 return 1;
4631 case DeclSpec::TST_interface:
4632 return 2;
4633 case DeclSpec::TST_union:
4634 return 3;
4635 case DeclSpec::TST_enum:
4636 return 4;
4637 default:
4638 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4638)
;
4639 }
4640}
4641
4642/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4643/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4644/// parameters to cope with template friend declarations.
4645Decl *
4646Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4647 MultiTemplateParamsArg TemplateParams,
4648 bool IsExplicitInstantiation,
4649 RecordDecl *&AnonRecord) {
4650 Decl *TagD = nullptr;
4651 TagDecl *Tag = nullptr;
4652 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4653 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4654 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4655 DS.getTypeSpecType() == DeclSpec::TST_union ||
4656 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4657 TagD = DS.getRepAsDecl();
4658
4659 if (!TagD) // We probably had an error
4660 return nullptr;
4661
4662 // Note that the above type specs guarantee that the
4663 // type rep is a Decl, whereas in many of the others
4664 // it's a Type.
4665 if (isa<TagDecl>(TagD))
4666 Tag = cast<TagDecl>(TagD);
4667 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4668 Tag = CTD->getTemplatedDecl();
4669 }
4670
4671 if (Tag) {
4672 handleTagNumbering(Tag, S);
4673 Tag->setFreeStanding();
4674 if (Tag->isInvalidDecl())
4675 return Tag;
4676 }
4677
4678 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4679 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4680 // or incomplete types shall not be restrict-qualified."
4681 if (TypeQuals & DeclSpec::TQ_restrict)
4682 Diag(DS.getRestrictSpecLoc(),
4683 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4684 << DS.getSourceRange();
4685 }
4686
4687 if (DS.isInlineSpecified())
4688 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4689 << getLangOpts().CPlusPlus17;
4690
4691 if (DS.hasConstexprSpecifier()) {
4692 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4693 // and definitions of functions and variables.
4694 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4695 // the declaration of a function or function template
4696 if (Tag)
4697 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4698 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4699 << static_cast<int>(DS.getConstexprSpecifier());
4700 else
4701 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4702 << static_cast<int>(DS.getConstexprSpecifier());
4703 // Don't emit warnings after this error.
4704 return TagD;
4705 }
4706
4707 DiagnoseFunctionSpecifiers(DS);
4708
4709 if (DS.isFriendSpecified()) {
4710 // If we're dealing with a decl but not a TagDecl, assume that
4711 // whatever routines created it handled the friendship aspect.
4712 if (TagD && !Tag)
4713 return nullptr;
4714 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4715 }
4716
4717 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4718 bool IsExplicitSpecialization =
4719 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4720 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4721 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4722 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4723 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4724 // nested-name-specifier unless it is an explicit instantiation
4725 // or an explicit specialization.
4726 //
4727 // FIXME: We allow class template partial specializations here too, per the
4728 // obvious intent of DR1819.
4729 //
4730 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4731 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4732 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4733 return nullptr;
4734 }
4735
4736 // Track whether this decl-specifier declares anything.
4737 bool DeclaresAnything = true;
4738
4739 // Handle anonymous struct definitions.
4740 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4741 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4742 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4743 if (getLangOpts().CPlusPlus ||
4744 Record->getDeclContext()->isRecord()) {
4745 // If CurContext is a DeclContext that can contain statements,
4746 // RecursiveASTVisitor won't visit the decls that
4747 // BuildAnonymousStructOrUnion() will put into CurContext.
4748 // Also store them here so that they can be part of the
4749 // DeclStmt that gets created in this case.
4750 // FIXME: Also return the IndirectFieldDecls created by
4751 // BuildAnonymousStructOr union, for the same reason?
4752 if (CurContext->isFunctionOrMethod())
4753 AnonRecord = Record;
4754 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4755 Context.getPrintingPolicy());
4756 }
4757
4758 DeclaresAnything = false;
4759 }
4760 }
4761
4762 // C11 6.7.2.1p2:
4763 // A struct-declaration that does not declare an anonymous structure or
4764 // anonymous union shall contain a struct-declarator-list.
4765 //
4766 // This rule also existed in C89 and C99; the grammar for struct-declaration
4767 // did not permit a struct-declaration without a struct-declarator-list.
4768 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4769 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4770 // Check for Microsoft C extension: anonymous struct/union member.
4771 // Handle 2 kinds of anonymous struct/union:
4772 // struct STRUCT;
4773 // union UNION;
4774 // and
4775 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4776 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4777 if ((Tag && Tag->getDeclName()) ||
4778 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4779 RecordDecl *Record = nullptr;
4780 if (Tag)
4781 Record = dyn_cast<RecordDecl>(Tag);
4782 else if (const RecordType *RT =
4783 DS.getRepAsType().get()->getAsStructureType())
4784 Record = RT->getDecl();
4785 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4786 Record = UT->getDecl();
4787
4788 if (Record && getLangOpts().MicrosoftExt) {
4789 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4790 << Record->isUnion() << DS.getSourceRange();
4791 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4792 }
4793
4794 DeclaresAnything = false;
4795 }
4796 }
4797
4798 // Skip all the checks below if we have a type error.
4799 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4800 (TagD && TagD->isInvalidDecl()))
4801 return TagD;
4802
4803 if (getLangOpts().CPlusPlus &&
4804 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4805 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4806 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4807 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4808 DeclaresAnything = false;
4809
4810 if (!DS.isMissingDeclaratorOk()) {
4811 // Customize diagnostic for a typedef missing a name.
4812 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4813 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4814 << DS.getSourceRange();
4815 else
4816 DeclaresAnything = false;
4817 }
4818
4819 if (DS.isModulePrivateSpecified() &&
4820 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4821 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4822 << Tag->getTagKind()
4823 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4824
4825 ActOnDocumentableDecl(TagD);
4826
4827 // C 6.7/2:
4828 // A declaration [...] shall declare at least a declarator [...], a tag,
4829 // or the members of an enumeration.
4830 // C++ [dcl.dcl]p3:
4831 // [If there are no declarators], and except for the declaration of an
4832 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4833 // names into the program, or shall redeclare a name introduced by a
4834 // previous declaration.
4835 if (!DeclaresAnything) {
4836 // In C, we allow this as a (popular) extension / bug. Don't bother
4837 // producing further diagnostics for redundant qualifiers after this.
4838 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4839 ? diag::err_no_declarators
4840 : diag::ext_no_declarators)
4841 << DS.getSourceRange();
4842 return TagD;
4843 }
4844
4845 // C++ [dcl.stc]p1:
4846 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4847 // init-declarator-list of the declaration shall not be empty.
4848 // C++ [dcl.fct.spec]p1:
4849 // If a cv-qualifier appears in a decl-specifier-seq, the
4850 // init-declarator-list of the declaration shall not be empty.
4851 //
4852 // Spurious qualifiers here appear to be valid in C.
4853 unsigned DiagID = diag::warn_standalone_specifier;
4854 if (getLangOpts().CPlusPlus)
4855 DiagID = diag::ext_standalone_specifier;
4856
4857 // Note that a linkage-specification sets a storage class, but
4858 // 'extern "C" struct foo;' is actually valid and not theoretically
4859 // useless.
4860 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4861 if (SCS == DeclSpec::SCS_mutable)
4862 // Since mutable is not a viable storage class specifier in C, there is
4863 // no reason to treat it as an extension. Instead, diagnose as an error.
4864 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4865 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4866 Diag(DS.getStorageClassSpecLoc(), DiagID)
4867 << DeclSpec::getSpecifierName(SCS);
4868 }
4869
4870 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4871 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4872 << DeclSpec::getSpecifierName(TSCS);
4873 if (DS.getTypeQualifiers()) {
4874 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4875 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4876 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4877 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4878 // Restrict is covered above.
4879 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4880 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4881 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4882 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4883 }
4884
4885 // Warn about ignored type attributes, for example:
4886 // __attribute__((aligned)) struct A;
4887 // Attributes should be placed after tag to apply to type declaration.
4888 if (!DS.getAttributes().empty()) {
4889 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4890 if (TypeSpecType == DeclSpec::TST_class ||
4891 TypeSpecType == DeclSpec::TST_struct ||
4892 TypeSpecType == DeclSpec::TST_interface ||
4893 TypeSpecType == DeclSpec::TST_union ||
4894 TypeSpecType == DeclSpec::TST_enum) {
4895 for (const ParsedAttr &AL : DS.getAttributes())
4896 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4897 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4898 }
4899 }
4900
4901 return TagD;
4902}
4903
4904/// We are trying to inject an anonymous member into the given scope;
4905/// check if there's an existing declaration that can't be overloaded.
4906///
4907/// \return true if this is a forbidden redeclaration
4908static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4909 Scope *S,
4910 DeclContext *Owner,
4911 DeclarationName Name,
4912 SourceLocation NameLoc,
4913 bool IsUnion) {
4914 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4915 Sema::ForVisibleRedeclaration);
4916 if (!SemaRef.LookupName(R, S)) return false;
4917
4918 // Pick a representative declaration.
4919 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4920 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4920, __extension__ __PRETTY_FUNCTION__))
;
4921
4922 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4923 return false;
4924
4925 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4926 << IsUnion << Name;
4927 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4928
4929 return true;
4930}
4931
4932/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4933/// anonymous struct or union AnonRecord into the owning context Owner
4934/// and scope S. This routine will be invoked just after we realize
4935/// that an unnamed union or struct is actually an anonymous union or
4936/// struct, e.g.,
4937///
4938/// @code
4939/// union {
4940/// int i;
4941/// float f;
4942/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4943/// // f into the surrounding scope.x
4944/// @endcode
4945///
4946/// This routine is recursive, injecting the names of nested anonymous
4947/// structs/unions into the owning context and scope as well.
4948static bool
4949InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4950 RecordDecl *AnonRecord, AccessSpecifier AS,
4951 SmallVectorImpl<NamedDecl *> &Chaining) {
4952 bool Invalid = false;
4953
4954 // Look every FieldDecl and IndirectFieldDecl with a name.
4955 for (auto *D : AnonRecord->decls()) {
4956 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4957 cast<NamedDecl>(D)->getDeclName()) {
4958 ValueDecl *VD = cast<ValueDecl>(D);
4959 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4960 VD->getLocation(),
4961 AnonRecord->isUnion())) {
4962 // C++ [class.union]p2:
4963 // The names of the members of an anonymous union shall be
4964 // distinct from the names of any other entity in the
4965 // scope in which the anonymous union is declared.
4966 Invalid = true;
4967 } else {
4968 // C++ [class.union]p2:
4969 // For the purpose of name lookup, after the anonymous union
4970 // definition, the members of the anonymous union are
4971 // considered to have been defined in the scope in which the
4972 // anonymous union is declared.
4973 unsigned OldChainingSize = Chaining.size();
4974 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4975 Chaining.append(IF->chain_begin(), IF->chain_end());
4976 else
4977 Chaining.push_back(VD);
4978
4979 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4979, __extension__ __PRETTY_FUNCTION__))
;
4980 NamedDecl **NamedChain =
4981 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4982 for (unsigned i = 0; i < Chaining.size(); i++)
4983 NamedChain[i] = Chaining[i];
4984
4985 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4986 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4987 VD->getType(), {NamedChain, Chaining.size()});
4988
4989 for (const auto *Attr : VD->attrs())
4990 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4991
4992 IndirectField->setAccess(AS);
4993 IndirectField->setImplicit();
4994 SemaRef.PushOnScopeChains(IndirectField, S);
4995
4996 // That includes picking up the appropriate access specifier.
4997 if (AS != AS_none) IndirectField->setAccess(AS);
4998
4999 Chaining.resize(OldChainingSize);
5000 }
5001 }
5002 }
5003
5004 return Invalid;
5005}
5006
5007/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5008/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5009/// illegal input values are mapped to SC_None.
5010static StorageClass
5011StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5012 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5013 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5014, __extension__ __PRETTY_FUNCTION__))
5014 "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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5014, __extension__ __PRETTY_FUNCTION__))
;
5015 switch (StorageClassSpec) {
5016 case DeclSpec::SCS_unspecified: return SC_None;
5017 case DeclSpec::SCS_extern:
5018 if (DS.isExternInLinkageSpec())
5019 return SC_None;
5020 return SC_Extern;
5021 case DeclSpec::SCS_static: return SC_Static;
5022 case DeclSpec::SCS_auto: return SC_Auto;
5023 case DeclSpec::SCS_register: return SC_Register;
5024 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5025 // Illegal SCSs map to None: error reporting is up to the caller.
5026 case DeclSpec::SCS_mutable: // Fall through.
5027 case DeclSpec::SCS_typedef: return SC_None;
5028 }
5029 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5029)
;
5030}
5031
5032static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5033 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5033, __extension__ __PRETTY_FUNCTION__))
;
5034
5035 for (const auto *I : Record->decls()) {
5036 const auto *FD = dyn_cast<FieldDecl>(I);
5037 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5038 FD = IFD->getAnonField();
5039 if (FD && FD->hasInClassInitializer())
5040 return FD->getLocation();
5041 }
5042
5043 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5043)
;
5044}
5045
5046static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5047 SourceLocation DefaultInitLoc) {
5048 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5049 return;
5050
5051 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5052 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5053}
5054
5055static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5056 CXXRecordDecl *AnonUnion) {
5057 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5058 return;
5059
5060 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5061}
5062
5063/// BuildAnonymousStructOrUnion - Handle the declaration of an
5064/// anonymous structure or union. Anonymous unions are a C++ feature
5065/// (C++ [class.union]) and a C11 feature; anonymous structures
5066/// are a C11 feature and GNU C++ extension.
5067Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5068 AccessSpecifier AS,
5069 RecordDecl *Record,
5070 const PrintingPolicy &Policy) {
5071 DeclContext *Owner = Record->getDeclContext();
5072
5073 // Diagnose whether this anonymous struct/union is an extension.
5074 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5075 Diag(Record->getLocation(), diag::ext_anonymous_union);
5076 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5077 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5078 else if (!Record->isUnion() && !getLangOpts().C11)
5079 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5080
5081 // C and C++ require different kinds of checks for anonymous
5082 // structs/unions.
5083 bool Invalid = false;
5084 if (getLangOpts().CPlusPlus) {
5085 const char *PrevSpec = nullptr;
5086 if (Record->isUnion()) {
5087 // C++ [class.union]p6:
5088 // C++17 [class.union.anon]p2:
5089 // Anonymous unions declared in a named namespace or in the
5090 // global namespace shall be declared static.
5091 unsigned DiagID;
5092 DeclContext *OwnerScope = Owner->getRedeclContext();
5093 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5094 (OwnerScope->isTranslationUnit() ||
5095 (OwnerScope->isNamespace() &&
5096 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5097 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5098 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5099
5100 // Recover by adding 'static'.
5101 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5102 PrevSpec, DiagID, Policy);
5103 }
5104 // C++ [class.union]p6:
5105 // A storage class is not allowed in a declaration of an
5106 // anonymous union in a class scope.
5107 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5108 isa<RecordDecl>(Owner)) {
5109 Diag(DS.getStorageClassSpecLoc(),
5110 diag::err_anonymous_union_with_storage_spec)
5111 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5112
5113 // Recover by removing the storage specifier.
5114 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5115 SourceLocation(),
5116 PrevSpec, DiagID, Context.getPrintingPolicy());
5117 }
5118 }
5119
5120 // Ignore const/volatile/restrict qualifiers.
5121 if (DS.getTypeQualifiers()) {
5122 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5123 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5124 << Record->isUnion() << "const"
5125 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5126 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5127 Diag(DS.getVolatileSpecLoc(),
5128 diag::ext_anonymous_struct_union_qualified)
5129 << Record->isUnion() << "volatile"
5130 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5131 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5132 Diag(DS.getRestrictSpecLoc(),
5133 diag::ext_anonymous_struct_union_qualified)
5134 << Record->isUnion() << "restrict"
5135 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5136 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5137 Diag(DS.getAtomicSpecLoc(),
5138 diag::ext_anonymous_struct_union_qualified)
5139 << Record->isUnion() << "_Atomic"
5140 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5141 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5142 Diag(DS.getUnalignedSpecLoc(),
5143 diag::ext_anonymous_struct_union_qualified)
5144 << Record->isUnion() << "__unaligned"
5145 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5146
5147 DS.ClearTypeQualifiers();
5148 }
5149
5150 // C++ [class.union]p2:
5151 // The member-specification of an anonymous union shall only
5152 // define non-static data members. [Note: nested types and
5153 // functions cannot be declared within an anonymous union. ]
5154 for (auto *Mem : Record->decls()) {
5155 // Ignore invalid declarations; we already diagnosed them.
5156 if (Mem->isInvalidDecl())
5157 continue;
5158
5159 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5160 // C++ [class.union]p3:
5161 // An anonymous union shall not have private or protected
5162 // members (clause 11).
5163 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5163, __extension__ __PRETTY_FUNCTION__))
;
5164 if (FD->getAccess() != AS_public) {
5165 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5166 << Record->isUnion() << (FD->getAccess() == AS_protected);
5167 Invalid = true;
5168 }
5169
5170 // C++ [class.union]p1
5171 // An object of a class with a non-trivial constructor, a non-trivial
5172 // copy constructor, a non-trivial destructor, or a non-trivial copy
5173 // assignment operator cannot be a member of a union, nor can an
5174 // array of such objects.
5175 if (CheckNontrivialField(FD))
5176 Invalid = true;
5177 } else if (Mem->isImplicit()) {
5178 // Any implicit members are fine.
5179 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5180 // This is a type that showed up in an
5181 // elaborated-type-specifier inside the anonymous struct or
5182 // union, but which actually declares a type outside of the
5183 // anonymous struct or union. It's okay.
5184 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5185 if (!MemRecord->isAnonymousStructOrUnion() &&
5186 MemRecord->getDeclName()) {
5187 // Visual C++ allows type definition in anonymous struct or union.
5188 if (getLangOpts().MicrosoftExt)
5189 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5190 << Record->isUnion();
5191 else {
5192 // This is a nested type declaration.
5193 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5194 << Record->isUnion();
5195 Invalid = true;
5196 }
5197 } else {
5198 // This is an anonymous type definition within another anonymous type.
5199 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5200 // not part of standard C++.
5201 Diag(MemRecord->getLocation(),
5202 diag::ext_anonymous_record_with_anonymous_type)
5203 << Record->isUnion();
5204 }
5205 } else if (isa<AccessSpecDecl>(Mem)) {
5206 // Any access specifier is fine.
5207 } else if (isa<StaticAssertDecl>(Mem)) {
5208 // In C++1z, static_assert declarations are also fine.
5209 } else {
5210 // We have something that isn't a non-static data
5211 // member. Complain about it.
5212 unsigned DK = diag::err_anonymous_record_bad_member;
5213 if (isa<TypeDecl>(Mem))
5214 DK = diag::err_anonymous_record_with_type;
5215 else if (isa<FunctionDecl>(Mem))
5216 DK = diag::err_anonymous_record_with_function;
5217 else if (isa<VarDecl>(Mem))
5218 DK = diag::err_anonymous_record_with_static;
5219
5220 // Visual C++ allows type definition in anonymous struct or union.
5221 if (getLangOpts().MicrosoftExt &&
5222 DK == diag::err_anonymous_record_with_type)
5223 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5224 << Record->isUnion();
5225 else {
5226 Diag(Mem->getLocation(), DK) << Record->isUnion();
5227 Invalid = true;
5228 }
5229 }
5230 }
5231
5232 // C++11 [class.union]p8 (DR1460):
5233 // At most one variant member of a union may have a
5234 // brace-or-equal-initializer.
5235 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5236 Owner->isRecord())
5237 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5238 cast<CXXRecordDecl>(Record));
5239 }
5240
5241 if (!Record->isUnion() && !Owner->isRecord()) {
5242 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5243 << getLangOpts().CPlusPlus;
5244 Invalid = true;
5245 }
5246
5247 // C++ [dcl.dcl]p3:
5248 // [If there are no declarators], and except for the declaration of an
5249 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5250 // names into the program
5251 // C++ [class.mem]p2:
5252 // each such member-declaration shall either declare at least one member
5253 // name of the class or declare at least one unnamed bit-field
5254 //
5255 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5256 if (getLangOpts().CPlusPlus && Record->field_empty())
5257 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5258
5259 // Mock up a declarator.
5260 Declarator Dc(DS, DeclaratorContext::Member);
5261 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5262 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5262, __extension__ __PRETTY_FUNCTION__))
;
5263
5264 // Create a declaration for this anonymous struct/union.
5265 NamedDecl *Anon = nullptr;
5266 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5267 Anon = FieldDecl::Create(
5268 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5269 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5270 /*BitWidth=*/nullptr, /*Mutable=*/false,
5271 /*InitStyle=*/ICIS_NoInit);
5272 Anon->setAccess(AS);
5273 ProcessDeclAttributes(S, Anon, Dc);
5274
5275 if (getLangOpts().CPlusPlus)
5276 FieldCollector->Add(cast<FieldDecl>(Anon));
5277 } else {
5278 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5279 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5280 if (SCSpec == DeclSpec::SCS_mutable) {
5281 // mutable can only appear on non-static class members, so it's always
5282 // an error here
5283 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5284 Invalid = true;
5285 SC = SC_None;
5286 }
5287
5288 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5288, __extension__ __PRETTY_FUNCTION__))
;
5289 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5290 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5291 Context.getTypeDeclType(Record), TInfo, SC);
5292
5293 // Default-initialize the implicit variable. This initialization will be
5294 // trivial in almost all cases, except if a union member has an in-class
5295 // initializer:
5296 // union { int n = 0; };
5297 if (!Invalid)
5298 ActOnUninitializedDecl(Anon);
5299 }
5300 Anon->setImplicit();
5301
5302 // Mark this as an anonymous struct/union type.
5303 Record->setAnonymousStructOrUnion(true);
5304
5305 // Add the anonymous struct/union object to the current
5306 // context. We'll be referencing this object when we refer to one of
5307 // its members.
5308 Owner->addDecl(Anon);
5309
5310 // Inject the members of the anonymous struct/union into the owning
5311 // context and into the identifier resolver chain for name lookup
5312 // purposes.
5313 SmallVector<NamedDecl*, 2> Chain;
5314 Chain.push_back(Anon);
5315
5316 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5317 Invalid = true;
5318
5319 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5320 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5321 MangleNumberingContext *MCtx;
5322 Decl *ManglingContextDecl;
5323 std::tie(MCtx, ManglingContextDecl) =
5324 getCurrentMangleNumberContext(NewVD->getDeclContext());
5325 if (MCtx) {
5326 Context.setManglingNumber(
5327 NewVD, MCtx->getManglingNumber(
5328 NewVD, getMSManglingNumber(getLangOpts(), S)));
5329 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5330 }
5331 }
5332 }
5333
5334 if (Invalid)
5335 Anon->setInvalidDecl();
5336
5337 return Anon;
5338}
5339
5340/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5341/// Microsoft C anonymous structure.
5342/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5343/// Example:
5344///
5345/// struct A { int a; };
5346/// struct B { struct A; int b; };
5347///
5348/// void foo() {
5349/// B var;
5350/// var.a = 3;
5351/// }
5352///
5353Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5354 RecordDecl *Record) {
5355 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5355, __extension__ __PRETTY_FUNCTION__))
;
5356
5357 // Mock up a declarator.
5358 Declarator Dc(DS, DeclaratorContext::TypeName);
5359 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5360 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~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5360, __extension__ __PRETTY_FUNCTION__))
;
5361
5362 auto *ParentDecl = cast<RecordDecl>(CurContext);
5363 QualType RecTy = Context.getTypeDeclType(Record);
5364
5365 // Create a declaration for this anonymous struct.
5366 NamedDecl *Anon =
5367 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5368 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5369 /*BitWidth=*/nullptr, /*Mutable=*/false,
5370 /*InitStyle=*/ICIS_NoInit);
5371 Anon->setImplicit();
5372
5373 // Add the anonymous struct object to the current context.
5374 CurContext->addDecl(Anon);
5375
5376 // Inject the members of the anonymous struct into the current
5377 // context and into the identifier resolver chain for name lookup
5378 // purposes.
5379 SmallVector<NamedDecl*, 2> Chain;
5380 Chain.push_back(Anon);
5381
5382 RecordDecl *RecordDef = Record->getDefinition();
5383 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5384 diag::err_field_incomplete_or_sizeless) ||
5385 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5386 AS_none, Chain)) {
5387 Anon->setInvalidDecl();
5388 ParentDecl->setInvalidDecl();
5389 }
5390
5391 return Anon;
5392}
5393
5394/// GetNameForDeclarator - Determine the full declaration name for the
5395/// given Declarator.
5396DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5397 return GetNameFromUnqualifiedId(D.getName());
9
Returning without writing to 'D.Redeclaration', which participates in a condition later
20
Returning without writing to 'D.Redeclaration', which participates in a condition later
5398}
5399
5400/// Retrieves the declaration name from a parsed unqualified-id.
5401DeclarationNameInfo
5402Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5403 DeclarationNameInfo NameInfo;
5404 NameInfo.setLoc(Name.StartLocation);
5405
5406 switch (Name.getKind()) {
5407
5408 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5409 case UnqualifiedIdKind::IK_Identifier:
5410 NameInfo.setName(Name.Identifier);
5411 return NameInfo;
5412
5413 case UnqualifiedIdKind::IK_DeductionGuideName: {
5414 // C++ [temp.deduct.guide]p3:
5415 // The simple-template-id shall name a class template specialization.
5416 // The template-name shall be the same identifier as the template-name
5417 // of the simple-template-id.
5418 // These together intend to imply that the template-name shall name a
5419 // class template.
5420 // FIXME: template<typename T> struct X {};
5421 // template<typename T> using Y = X<T>;
5422 // Y(int) -> Y<int>;
5423 // satisfies these rules but does not name a class template.
5424 TemplateName TN = Name.TemplateName.get().get();
5425 auto *Template = TN.getAsTemplateDecl();
5426 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5427 Diag(Name.StartLocation,
5428 diag::err_deduction_guide_name_not_class_template)
5429 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5430 if (Template)
5431 Diag(Template->getLocation(), diag::note_template_decl_here);
5432 return DeclarationNameInfo();
5433 }
5434
5435 NameInfo.setName(
5436 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5437 return NameInfo;
5438 }
5439
5440 case UnqualifiedIdKind::IK_OperatorFunctionId:
5441 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5442 Name.OperatorFunctionId.Operator));
5443 NameInfo.setCXXOperatorNameRange(SourceRange(
5444 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5445 return NameInfo;
5446
5447 case UnqualifiedIdKind::IK_LiteralOperatorId:
5448 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5449 Name.Identifier));
5450 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5451 return NameInfo;
5452
5453 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5454 TypeSourceInfo *TInfo;
5455 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5456 if (Ty.isNull())
5457 return DeclarationNameInfo();
5458 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5459 Context.getCanonicalType(Ty)));
5460 NameInfo.setNamedTypeInfo(TInfo);
5461 return NameInfo;
5462 }
5463
5464 case UnqualifiedIdKind::IK_ConstructorName: {
5465 TypeSourceInfo *TInfo;
5466 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5467 if (Ty.isNull())
5468 return DeclarationNameInfo();
5469 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5470 Context.getCanonicalType(Ty)));
5471 NameInfo.setNamedTypeInfo(TInfo);
5472 return NameInfo;
5473 }
5474
5475 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5476 // In well-formed code, we can only have a constructor
5477 // template-id that refers to the current context, so go there
5478 // to find the actual type being constructed.
5479 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5480 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5481 return DeclarationNameInfo();
5482
5483 // Determine the type of the class being constructed.
5484 QualType CurClassType = Context.getTypeDeclType(CurClass);
5485
5486 // FIXME: Check two things: that the template-id names the same type as
5487 // CurClassType, and that the template-id does not occur when the name
5488 // was qualified.
5489
5490 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5491 Context.getCanonicalType(CurClassType)));
5492 // FIXME: should we retrieve TypeSourceInfo?
5493 NameInfo.setNamedTypeInfo(nullptr);
5494 return NameInfo;
5495 }
5496
5497 case UnqualifiedIdKind::IK_DestructorName: {
5498 TypeSourceInfo *TInfo;
5499 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5500 if (Ty.isNull())
5501 return DeclarationNameInfo();
5502 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5503 Context.getCanonicalType(Ty)));
5504 NameInfo.setNamedTypeInfo(TInfo);
5505 return NameInfo;
5506 }
5507
5508 case UnqualifiedIdKind::IK_TemplateId: {
5509 TemplateName TName = Name.TemplateId->Template.get();
5510 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5511 return Context.getNameForTemplate(TName, TNameLoc);
5512 }
5513
5514 } // switch (Name.getKind())
5515
5516 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5516)
;
5517}
5518
5519static QualType getCoreType(QualType Ty) {
5520 do {
5521 if (Ty->isPointerType() || Ty->isReferenceType())
5522 Ty = Ty->getPointeeType();
5523 else if (Ty->isArrayType())
5524 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5525 else
5526 return Ty.withoutLocalFastQualifiers();
5527 } while (true);
5528}
5529
5530/// hasSimilarParameters - Determine whether the C++ functions Declaration
5531/// and Definition have "nearly" matching parameters. This heuristic is
5532/// used to improve diagnostics in the case where an out-of-line function
5533/// definition doesn't match any declaration within the class or namespace.
5534/// Also sets Params to the list of indices to the parameters that differ
5535/// between the declaration and the definition. If hasSimilarParameters
5536/// returns true and Params is empty, then all of the parameters match.
5537static bool hasSimilarParameters(ASTContext &Context,
5538 FunctionDecl *Declaration,
5539 FunctionDecl *Definition,
5540 SmallVectorImpl<unsigned> &Params) {
5541 Params.clear();
5542 if (Declaration->param_size() != Definition->param_size())
5543 return false;
5544 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5545 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5546 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5547
5548 // The parameter types are identical
5549 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5550 continue;
5551
5552 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5553 QualType DefParamBaseTy = getCoreType(DefParamTy);
5554 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5555 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5556
5557 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5558 (DeclTyName && DeclTyName == DefTyName))
5559 Params.push_back(Idx);
5560 else // The two parameters aren't even close
5561 return false;
5562 }
5563
5564 return true;
5565}
5566
5567/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5568/// declarator needs to be rebuilt in the current instantiation.
5569/// Any bits of declarator which appear before the name are valid for
5570/// consideration here. That's specifically the type in the decl spec
5571/// and the base type in any member-pointer chunks.
5572static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5573 DeclarationName Name) {
5574 // The types we specifically need to rebuild are:
5575 // - typenames, typeofs, and decltypes
5576 // - types which will become injected class names
5577 // Of course, we also need to rebuild any type referencing such a
5578 // type. It's safest to just say "dependent", but we call out a
5579 // few cases here.
5580
5581 DeclSpec &DS = D.getMutableDeclSpec();
5582 switch (DS.getTypeSpecType()) {
5583 case DeclSpec::TST_typename:
5584 case DeclSpec::TST_typeofType:
5585 case DeclSpec::TST_underlyingType:
5586 case DeclSpec::TST_atomic: {
5587 // Grab the type from the parser.
5588 TypeSourceInfo *TSI = nullptr;
5589 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5590 if (T.isNull() || !T->isInstantiationDependentType()) break;
5591
5592 // Make sure there's a type source info. This isn't really much
5593 // of a waste; most dependent types should have type source info
5594 // attached already.
5595 if (!TSI)
5596 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5597
5598 // Rebuild the type in the current instantiation.
5599 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5600 if (!TSI) return true;
5601
5602 // Store the new type back in the decl spec.
5603 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5604 DS.UpdateTypeRep(LocType);
5605 break;
5606 }
5607
5608 case DeclSpec::TST_decltype:
5609 case DeclSpec::TST_typeofExpr: {
5610 Expr *E = DS.getRepAsExpr();
5611 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5612 if (Result.isInvalid()) return true;
5613 DS.UpdateExprRep(Result.get());
5614 break;
5615 }
5616
5617 default:
5618 // Nothing to do for these decl specs.
5619 break;
5620 }
5621
5622 // It doesn't matter what order we do this in.
5623 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5624 DeclaratorChunk &Chunk = D.getTypeObject(I);
5625
5626 // The only type information in the declarator which can come
5627 // before the declaration name is the base type of a member
5628 // pointer.
5629 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5630 continue;
5631
5632 // Rebuild the scope specifier in-place.
5633 CXXScopeSpec &SS = Chunk.Mem.Scope();
5634 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5635 return true;
5636 }
5637
5638 return false;
5639}
5640
5641void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5642 // Avoid warning twice on the same identifier, and don't warn on redeclaration
5643 // of system decl.
5644 if (D->getPreviousDecl() || D->isImplicit())
5645 return;
5646 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5647 if (Status != ReservedIdentifierStatus::NotReserved &&
5648 !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5649 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5650 << D << static_cast<int>(Status);
5651}
5652
5653Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5654 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5655 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5656
5657 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5658 Dcl && Dcl->getDeclContext()->isFileContext())
5659 Dcl->setTopLevelDeclInObjCContainer();
5660
5661 return Dcl;
5662}
5663
5664/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5665/// If T is the name of a class, then each of the following shall have a
5666/// name different from T:
5667/// - every static data member of class T;
5668/// - every member function of class T
5669/// - every member of class T that is itself a type;
5670/// \returns true if the declaration name violates these rules.
5671bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5672 DeclarationNameInfo NameInfo) {
5673 DeclarationName Name = NameInfo.getName();
5674
5675 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5676 while (Record && Record->isAnonymousStructOrUnion())
5677 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5678 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5679 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5680 return true;
5681 }
5682
5683 return false;
5684}
5685
5686/// Diagnose a declaration whose declarator-id has the given
5687/// nested-name-specifier.
5688///
5689/// \param SS The nested-name-specifier of the declarator-id.
5690///
5691/// \param DC The declaration context to which the nested-name-specifier
5692/// resolves.
5693///
5694/// \param Name The name of the entity being declared.
5695///
5696/// \param Loc The location of the name of the entity being declared.
5697///
5698/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5699/// we're declaring an explicit / partial specialization / instantiation.
5700///
5701/// \returns true if we cannot safely recover from this error, false otherwise.
5702bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5703 DeclarationName Name,
5704 SourceLocation Loc, bool IsTemplateId) {
5705 DeclContext *Cur = CurContext;
5706 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5707 Cur = Cur->getParent();
5708
5709 // If the user provided a superfluous scope specifier that refers back to the
5710 // class in which the entity is already declared, diagnose and ignore it.
5711 //
5712 // class X {
5713 // void X::f();
5714 // };
5715 //
5716 // Note, it was once ill-formed to give redundant qualification in all
5717 // contexts, but that rule was removed by DR482.
5718 if (Cur->Equals(DC)) {
5719 if (Cur->isRecord()) {
5720 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5721 : diag::err_member_extra_qualification)
5722 << Name << FixItHint::CreateRemoval(SS.getRange());
5723 SS.clear();
5724 } else {
5725 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5726 }
5727 return false;
5728 }
5729
5730 // Check whether the qualifying scope encloses the scope of the original
5731 // declaration. For a template-id, we perform the checks in
5732 // CheckTemplateSpecializationScope.
5733 if (!Cur->Encloses(DC) && !IsTemplateId) {
5734 if (Cur->isRecord())
5735 Diag(Loc, diag::err_member_qualification)
5736 << Name << SS.getRange();
5737 else if (isa<TranslationUnitDecl>(DC))
5738 Diag(Loc, diag::err_invalid_declarator_global_scope)
5739 << Name << SS.getRange();
5740 else if (isa<FunctionDecl>(Cur))
5741 Diag(Loc, diag::err_invalid_declarator_in_function)
5742 << Name << SS.getRange();
5743 else if (isa<BlockDecl>(Cur))
5744 Diag(Loc, diag::err_invalid_declarator_in_block)
5745 << Name << SS.getRange();
5746 else
5747 Diag(Loc, diag::err_invalid_declarator_scope)
5748 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5749
5750 return true;
5751 }
5752
5753 if (Cur->isRecord()) {
5754 // Cannot qualify members within a class.
5755 Diag(Loc, diag::err_member_qualification)
5756 << Name << SS.getRange();
5757 SS.clear();
5758
5759 // C++ constructors and destructors with incorrect scopes can break
5760 // our AST invariants by having the wrong underlying types. If
5761 // that's the case, then drop this declaration entirely.
5762 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5763 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5764 !Context.hasSameType(Name.getCXXNameType(),
5765 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5766 return true;
5767
5768 return false;
5769 }
5770
5771 // C++11 [dcl.meaning]p1:
5772 // [...] "The nested-name-specifier of the qualified declarator-id shall
5773 // not begin with a decltype-specifer"
5774 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5775 while (SpecLoc.getPrefix())
5776 SpecLoc = SpecLoc.getPrefix();
5777 if (dyn_cast_or_null<DecltypeType>(
5778 SpecLoc.getNestedNameSpecifier()->getAsType()))
5779 Diag(Loc, diag::err_decltype_in_declarator)
5780 << SpecLoc.getTypeLoc().getSourceRange();
5781
5782 return false;
5783}
5784
5785NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5786 MultiTemplateParamsArg TemplateParamLists) {
5787 // TODO: consider using NameInfo for diagnostic.
5788 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5789 DeclarationName Name = NameInfo.getName();
5790
5791 // All of these full declarators require an identifier. If it doesn't have
5792 // one, the ParsedFreeStandingDeclSpec action should be used.
5793 if (D.isDecompositionDeclarator()) {
5794 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5795 } else if (!Name) {
5796 if (!D.isInvalidType()) // Reject this if we think it is valid.
5797 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5798 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5799 return nullptr;
5800 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5801 return nullptr;
5802
5803 // The scope passed in may not be a decl scope. Zip up the scope tree until
5804 // we find one that is.
5805 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5806 (S->getFlags() & Scope::TemplateParamScope) != 0)
5807 S = S->getParent();
5808
5809 DeclContext *DC = CurContext;
5810 if (D.getCXXScopeSpec().isInvalid())
5811 D.setInvalidType();
5812 else if (D.getCXXScopeSpec().isSet()) {
5813 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5814 UPPC_DeclarationQualifier))
5815 return nullptr;
5816
5817 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5818 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5819 if (!DC || isa<EnumDecl>(DC)) {
5820 // If we could not compute the declaration context, it's because the
5821 // declaration context is dependent but does not refer to a class,
5822 // class template, or class template partial specialization. Complain
5823 // and return early, to avoid the coming semantic disaster.
5824 Diag(D.getIdentifierLoc(),
5825 diag::err_template_qualified_declarator_no_match)
5826 << D.getCXXScopeSpec().getScopeRep()
5827 << D.getCXXScopeSpec().getRange();
5828 return nullptr;
5829 }
5830 bool IsDependentContext = DC->isDependentContext();
5831
5832 if (!IsDependentContext &&
5833 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5834 return nullptr;
5835
5836 // If a class is incomplete, do not parse entities inside it.
5837 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5838 Diag(D.getIdentifierLoc(),
5839 diag::err_member_def_undefined_record)
5840 << Name << DC << D.getCXXScopeSpec().getRange();
5841 return nullptr;
5842 }
5843 if (!D.getDeclSpec().isFriendSpecified()) {
5844 if (diagnoseQualifiedDeclaration(
5845 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5846 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5847 if (DC->isRecord())
5848 return nullptr;
5849
5850 D.setInvalidType();
5851 }
5852 }
5853
5854 // Check whether we need to rebuild the type of the given
5855 // declaration in the current instantiation.
5856 if (EnteringContext && IsDependentContext &&
5857 TemplateParamLists.size() != 0) {
5858 ContextRAII SavedContext(*this, DC);
5859 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5860 D.setInvalidType();
5861 }
5862 }
5863
5864 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5865 QualType R = TInfo->getType();
5866
5867 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5868 UPPC_DeclarationType))
5869 D.setInvalidType();
5870
5871 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5872 forRedeclarationInCurContext());
5873
5874 // See if this is a redefinition of a variable in the same scope.
5875 if (!D.getCXXScopeSpec().isSet()) {
5876 bool IsLinkageLookup = false;
5877 bool CreateBuiltins = false;
5878
5879 // If the declaration we're planning to build will be a function
5880 // or object with linkage, then look for another declaration with
5881 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5882 //
5883 // If the declaration we're planning to build will be declared with
5884 // external linkage in the translation unit, create any builtin with
5885 // the same name.
5886 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5887 /* Do nothing*/;
5888 else if (CurContext->isFunctionOrMethod() &&
5889 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5890 R->isFunctionType())) {
5891 IsLinkageLookup = true;
5892 CreateBuiltins =
5893 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5894 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5895 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5896 CreateBuiltins = true;
5897
5898 if (IsLinkageLookup) {
5899 Previous.clear(LookupRedeclarationWithLinkage);
5900 Previous.setRedeclarationKind(ForExternalRedeclaration);
5901 }
5902
5903 LookupName(Previous, S, CreateBuiltins);
5904 } else { // Something like "int foo::x;"
5905 LookupQualifiedName(Previous, DC);
5906
5907 // C++ [dcl.meaning]p1:
5908 // When the declarator-id is qualified, the declaration shall refer to a
5909 // previously declared member of the class or namespace to which the
5910 // qualifier refers (or, in the case of a namespace, of an element of the
5911 // inline namespace set of that namespace (7.3.1)) or to a specialization
5912 // thereof; [...]
5913 //
5914 // Note that we already checked the context above, and that we do not have
5915 // enough information to make sure that Previous contains the declaration
5916 // we want to match. For example, given:
5917 //
5918 // class X {
5919 // void f();
5920 // void f(float);
5921 // };
5922 //
5923 // void X::f(int) { } // ill-formed
5924 //
5925 // In this case, Previous will point to the overload set
5926 // containing the two f's declared in X, but neither of them
5927 // matches.
5928
5929 // C++ [dcl.meaning]p1:
5930 // [...] the member shall not merely have been introduced by a
5931 // using-declaration in the scope of the class or namespace nominated by
5932 // the nested-name-specifier of the declarator-id.
5933 RemoveUsingDecls(Previous);
5934 }
5935
5936 if (Previous.isSingleResult() &&
5937 Previous.getFoundDecl()->isTemplateParameter()) {
5938 // Maybe we will complain about the shadowed template parameter.
5939 if (!D.isInvalidType())
5940 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5941 Previous.getFoundDecl());
5942
5943 // Just pretend that we didn't see the previous declaration.
5944 Previous.clear();
5945 }
5946
5947 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5948 // Forget that the previous declaration is the injected-class-name.
5949 Previous.clear();
5950
5951 // In C++, the previous declaration we find might be a tag type
5952 // (class or enum). In this case, the new declaration will hide the
5953 // tag type. Note that this applies to functions, function templates, and
5954 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5955 if (Previous.isSingleTagDecl() &&
5956 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5957 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5958 Previous.clear();
5959
5960 // Check that there are no default arguments other than in the parameters
5961 // of a function declaration (C++ only).
5962 if (getLangOpts().CPlusPlus)
5963 CheckExtraCXXDefaultArguments(D);
5964
5965 NamedDecl *New;
5966
5967 bool AddToScope = true;
5968 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5969 if (TemplateParamLists.size()) {
5970 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5971 return nullptr;
5972 }
5973
5974 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5975 } else if (R->isFunctionType()) {
5976 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5977 TemplateParamLists,
5978 AddToScope);
5979 } else {
5980 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5981 AddToScope);
5982 }
5983
5984 if (!New)
5985 return nullptr;
5986
5987 // If this has an identifier and is not a function template specialization,
5988 // add it to the scope stack.
5989 if (New->getDeclName() && AddToScope)
5990 PushOnScopeChains(New, S);
5991
5992 if (isInOpenMPDeclareTargetContext())
5993 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5994
5995 return New;
5996}
5997
5998/// Helper method to turn variable array types into constant array
5999/// types in certain situations which would otherwise be errors (for
6000/// GCC compatibility).
6001static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6002 ASTContext &Context,
6003 bool &SizeIsNegative,
6004 llvm::APSInt &Oversized) {
6005 // This method tries to turn a variable array into a constant
6006 // array even when the size isn't an ICE. This is necessary
6007 // for compatibility with code that depends on gcc's buggy
6008 // constant expression folding, like struct {char x[(int)(char*)2];}
6009 SizeIsNegative = false;
6010 Oversized = 0;
6011
6012 if (T->isDependentType())
6013 return QualType();
6014
6015 QualifierCollector Qs;
6016 const Type *Ty = Qs.strip(T);
6017
6018 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6019 QualType Pointee = PTy->getPointeeType();
6020 QualType FixedType =
6021 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6022 Oversized);
6023 if (FixedType.isNull()) return FixedType;
6024 FixedType = Context.getPointerType(FixedType);
6025 return Qs.apply(Context, FixedType);
6026 }
6027 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6028 QualType Inner = PTy->getInnerType();
6029 QualType FixedType =
6030 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6031 Oversized);
6032 if (FixedType.isNull()) return FixedType;
6033 FixedType = Context.getParenType(FixedType);
6034 return Qs.apply(Context, FixedType);
6035 }
6036
6037 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6038 if (!VLATy)
6039 return QualType();
6040
6041 QualType ElemTy = VLATy->getElementType();
6042 if (ElemTy->isVariablyModifiedType()) {
6043 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6044 SizeIsNegative, Oversized);
6045 if (ElemTy.isNull())
6046 return QualType();
6047 }
6048
6049 Expr::EvalResult Result;
6050 if (!VLATy->getSizeExpr() ||
6051 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6052 return QualType();
6053
6054 llvm::APSInt Res = Result.Val.getInt();
6055
6056 // Check whether the array size is negative.
6057 if (Res.isSigned() && Res.isNegative()) {
6058 SizeIsNegative = true;
6059 return QualType();
6060 }
6061
6062 // Check whether the array is too large to be addressed.
6063 unsigned ActiveSizeBits =
6064 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6065 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6066 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6067 : Res.getActiveBits();
6068 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6069 Oversized = Res;
6070 return QualType();
6071 }
6072
6073 QualType FoldedArrayType = Context.getConstantArrayType(
6074 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6075 return Qs.apply(Context, FoldedArrayType);
6076}
6077
6078static void
6079FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6080 SrcTL = SrcTL.getUnqualifiedLoc();
6081 DstTL = DstTL.getUnqualifiedLoc();
6082 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6083 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6084 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6085 DstPTL.getPointeeLoc());
6086 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6087 return;
6088 }
6089 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6090 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6091 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6092 DstPTL.getInnerLoc());
6093 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6094 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6095 return;
6096 }
6097 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6098 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6099 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6100 TypeLoc DstElemTL = DstATL.getElementLoc();
6101 if (VariableArrayTypeLoc SrcElemATL =
6102 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6103 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6104 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6105 } else {
6106 DstElemTL.initializeFullCopy(SrcElemTL);
6107 }
6108 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6109 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6110 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6111}
6112
6113/// Helper method to turn variable array types into constant array
6114/// types in certain situations which would otherwise be errors (for
6115/// GCC compatibility).
6116static TypeSourceInfo*
6117TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6118 ASTContext &Context,
6119 bool &SizeIsNegative,
6120 llvm::APSInt &Oversized) {
6121 QualType FixedTy
6122 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6123 SizeIsNegative, Oversized);
6124 if (FixedTy.isNull())
6125 return nullptr;
6126 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6127 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6128 FixedTInfo->getTypeLoc());
6129 return FixedTInfo;
6130}
6131
6132/// Attempt to fold a variable-sized type to a constant-sized type, returning
6133/// true if we were successful.
6134bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6135 QualType &T, SourceLocation Loc,
6136 unsigned FailedFoldDiagID) {
6137 bool SizeIsNegative;
6138 llvm::APSInt Oversized;
6139 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6140 TInfo, Context, SizeIsNegative, Oversized);
6141 if (FixedTInfo) {
6142 Diag(Loc, diag::ext_vla_folded_to_constant);
6143 TInfo = FixedTInfo;
6144 T = FixedTInfo->getType();
6145 return true;
6146 }
6147
6148 if (SizeIsNegative)
6149 Diag(Loc, diag::err_typecheck_negative_array_size);
6150 else if (Oversized.getBoolValue())
6151 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6152 else if (FailedFoldDiagID)
6153 Diag(Loc, FailedFoldDiagID);
6154 return false;
6155}
6156
6157/// Register the given locally-scoped extern "C" declaration so
6158/// that it can be found later for redeclarations. We include any extern "C"
6159/// declaration that is not visible in the translation unit here, not just
6160/// function-scope declarations.
6161void
6162Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6163 if (!getLangOpts().CPlusPlus &&
6164 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6165 // Don't need to track declarations in the TU in C.
6166 return;
6167
6168 // Note that we have a locally-scoped external with this name.
6169 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6170}
6171
6172NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6173 // FIXME: We can have multiple results via __attribute__((overloadable)).
6174 auto Result = Context.getExternCContextDecl()->lookup(Name);
6175 return Result.empty() ? nullptr : *Result.begin();
6176}
6177
6178/// Diagnose function specifiers on a declaration of an identifier that
6179/// does not identify a function.
6180void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6181 // FIXME: We should probably indicate the identifier in question to avoid
6182 // confusion for constructs like "virtual int a(), b;"
6183 if (DS.isVirtualSpecified())
6184 Diag(DS.getVirtualSpecLoc(),
6185 diag::err_virtual_non_function);
6186
6187 if (DS.hasExplicitSpecifier())
6188 Diag(DS.getExplicitSpecLoc(),
6189 diag::err_explicit_non_function);
6190
6191 if (DS.isNoreturnSpecified())
6192 Diag(DS.getNoreturnSpecLoc(),
6193 diag::err_noreturn_non_function);
6194}
6195
6196NamedDecl*
6197Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6198 TypeSourceInfo *TInfo, LookupResult &Previous) {
6199 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6200 if (D.getCXXScopeSpec().isSet()) {
6201 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6202 << D.getCXXScopeSpec().getRange();
6203 D.setInvalidType();
6204 // Pretend we didn't see the scope specifier.
6205 DC = CurContext;
6206 Previous.clear();
6207 }
6208
6209 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6210
6211 if (D.getDeclSpec().isInlineSpecified())
6212 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6213 << getLangOpts().CPlusPlus17;
6214 if (D.getDeclSpec().hasConstexprSpecifier())
6215 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6216 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6217
6218 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6219 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6220 Diag(D.getName().StartLocation,
6221 diag::err_deduction_guide_invalid_specifier)
6222 << "typedef";
6223 else
6224 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6225 << D.getName().getSourceRange();
6226 return nullptr;
6227 }
6228
6229 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6230 if (!NewTD) return nullptr;
6231
6232 // Handle attributes prior to checking for duplicates in MergeVarDecl
6233 ProcessDeclAttributes(S, NewTD, D);
6234
6235 CheckTypedefForVariablyModifiedType(S, NewTD);
6236
6237 bool Redeclaration = D.isRedeclaration();
6238 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6239 D.setRedeclaration(Redeclaration);
6240 return ND;
6241}
6242
6243void
6244Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6245 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6246 // then it shall have block scope.
6247 // Note that variably modified types must be fixed before merging the decl so
6248 // that redeclarations will match.
6249 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6250 QualType T = TInfo->getType();
6251 if (T->isVariablyModifiedType()) {
6252 setFunctionHasBranchProtectedScope();
6253
6254 if (S->getFnParent() == nullptr) {
6255 bool SizeIsNegative;
6256 llvm::APSInt Oversized;
6257 TypeSourceInfo *FixedTInfo =
6258 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6259 SizeIsNegative,
6260 Oversized);
6261 if (FixedTInfo) {
6262 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6263 NewTD->setTypeSourceInfo(FixedTInfo);
6264 } else {
6265 if (SizeIsNegative)
6266 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6267 else if (T->isVariableArrayType())
6268 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6269 else if (Oversized.getBoolValue())
6270 Diag(NewTD->getLocation(), diag::err_array_too_large)
6271 << toString(Oversized, 10);
6272 else
6273 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6274 NewTD->setInvalidDecl();
6275 }
6276 }
6277 }
6278}
6279
6280/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6281/// declares a typedef-name, either using the 'typedef' type specifier or via
6282/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6283NamedDecl*
6284Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6285 LookupResult &Previous, bool &Redeclaration) {
6286
6287 // Find the shadowed declaration before filtering for scope.
6288 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6289
6290 // Merge the decl with the existing one if appropriate. If the decl is
6291 // in an outer scope, it isn't the same thing.
6292 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6293 /*AllowInlineNamespace*/false);
6294 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6295 if (!Previous.empty()) {
6296 Redeclaration = true;
6297 MergeTypedefNameDecl(S, NewTD, Previous);
6298 } else {
6299 inferGslPointerAttribute(NewTD);
6300 }
6301
6302 if (ShadowedDecl && !Redeclaration)
6303 CheckShadow(NewTD, ShadowedDecl, Previous);
6304
6305 // If this is the C FILE type, notify the AST context.
6306 if (IdentifierInfo *II = NewTD->getIdentifier())
6307 if (!NewTD->isInvalidDecl() &&
6308 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6309 if (II->isStr("FILE"))
6310 Context.setFILEDecl(NewTD);
6311 else if (II->isStr("jmp_buf"))
6312 Context.setjmp_bufDecl(NewTD);
6313 else if (II->isStr("sigjmp_buf"))
6314 Context.setsigjmp_bufDecl(NewTD);
6315 else if (II->isStr("ucontext_t"))
6316 Context.setucontext_tDecl(NewTD);
6317 }
6318
6319 return NewTD;
6320}
6321
6322/// Determines whether the given declaration is an out-of-scope
6323/// previous declaration.
6324///
6325/// This routine should be invoked when name lookup has found a
6326/// previous declaration (PrevDecl) that is not in the scope where a
6327/// new declaration by the same name is being introduced. If the new
6328/// declaration occurs in a local scope, previous declarations with
6329/// linkage may still be considered previous declarations (C99
6330/// 6.2.2p4-5, C++ [basic.link]p6).
6331///
6332/// \param PrevDecl the previous declaration found by name
6333/// lookup
6334///
6335/// \param DC the context in which the new declaration is being
6336/// declared.
6337///
6338/// \returns true if PrevDecl is an out-of-scope previous declaration
6339/// for a new delcaration with the same name.
6340static bool
6341isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6342 ASTContext &Context) {
6343 if (!PrevDecl)
6344 return false;
6345
6346 if (!PrevDecl->hasLinkage())
6347 return false;
6348
6349 if (Context.getLangOpts().CPlusPlus) {
6350 // C++ [basic.link]p6:
6351 // If there is a visible declaration of an entity with linkage
6352 // having the same name and type, ignoring entities declared
6353 // outside the innermost enclosing namespace scope, the block
6354 // scope declaration declares that same entity and receives the
6355 // linkage of the previous declaration.
6356 DeclContext *OuterContext = DC->getRedeclContext();
6357 if (!OuterContext->isFunctionOrMethod())
6358 // This rule only applies to block-scope declarations.
6359 return false;
6360
6361 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6362 if (PrevOuterContext->isRecord())
6363 // We found a member function: ignore it.
6364 return false;
6365
6366 // Find the innermost enclosing namespace for the new and
6367 // previous declarations.
6368 OuterContext = OuterContext->getEnclosingNamespaceContext();
6369 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6370
6371 // The previous declaration is in a different namespace, so it
6372 // isn't the same function.
6373 if (!OuterContext->Equals(PrevOuterContext))
6374 return false;
6375 }
6376
6377 return true;
6378}
6379
6380static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6381 CXXScopeSpec &SS = D.getCXXScopeSpec();
6382 if (!SS.isSet()) return;
6383 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6384}
6385
6386bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6387 QualType type = decl->getType();
6388 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6389 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6390 // Various kinds of declaration aren't allowed to be __autoreleasing.
6391 unsigned kind = -1U;
6392 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6393 if (var->hasAttr<BlocksAttr>())
6394 kind = 0; // __block
6395 else if (!var->hasLocalStorage())
6396 kind = 1; // global
6397 } else if (isa<ObjCIvarDecl>(decl)) {
6398 kind = 3; // ivar
6399 } else if (isa<FieldDecl>(decl)) {
6400 kind = 2; // field
6401 }
6402
6403 if (kind != -1U) {
6404 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6405 << kind;
6406 }
6407 } else if (lifetime == Qualifiers::OCL_None) {
6408 // Try to infer lifetime.
6409 if (!type->isObjCLifetimeType())
6410 return false;
6411
6412 lifetime = type->getObjCARCImplicitLifetime();
6413 type = Context.getLifetimeQualifiedType(type, lifetime);
6414 decl->setType(type);
6415 }
6416
6417 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6418 // Thread-local variables cannot have lifetime.
6419 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6420 var->getTLSKind()) {
6421 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6422 << var->getType();
6423 return true;
6424 }
6425 }
6426
6427 return false;
6428}
6429
6430void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6431 if (Decl->getType().hasAddressSpace())
6432 return;
6433 if (Decl->getType()->isDependentType())
6434 return;
6435 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6436 QualType Type = Var->getType();
6437 if (Type->isSamplerT() || Type->isVoidType())
6438 return;
6439 LangAS ImplAS = LangAS::opencl_private;
6440 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6441 // __opencl_c_program_scope_global_variables feature, the address space
6442 // for a variable at program scope or a static or extern variable inside
6443 // a function are inferred to be __global.
6444 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6445 Var->hasGlobalStorage())
6446 ImplAS = LangAS::opencl_global;
6447 // If the original type from a decayed type is an array type and that array
6448 // type has no address space yet, deduce it now.
6449 if (auto DT = dyn_cast<DecayedType>(Type)) {
6450 auto OrigTy = DT->getOriginalType();
6451 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6452 // Add the address space to the original array type and then propagate
6453 // that to the element type through `getAsArrayType`.
6454 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6455 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6456 // Re-generate the decayed type.
6457 Type = Context.getDecayedType(OrigTy);
6458 }
6459 }
6460 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6461 // Apply any qualifiers (including address space) from the array type to
6462 // the element type. This implements C99 6.7.3p8: "If the specification of
6463 // an array type includes any type qualifiers, the element type is so
6464 // qualified, not the array type."
6465 if (Type->isArrayType())
6466 Type = QualType(Context.getAsArrayType(Type), 0);
6467 Decl->setType(Type);
6468 }
6469}
6470
6471static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6472 // Ensure that an auto decl is deduced otherwise the checks below might cache
6473 // the wrong linkage.
6474 assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(&
ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 6474, __extension__ __PRETTY_FUNCTION__))
;
6475
6476 // 'weak' only applies to declarations with external linkage.
6477 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6478 if (!ND.isExternallyVisible()) {
6479 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6480 ND.dropAttr<WeakAttr>();
6481 }
6482 }
6483 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6484 if (ND.isExternallyVisible()) {
6485 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6486 ND.dropAttr<WeakRefAttr>();
6487 ND.dropAttr<AliasAttr>();
6488 }
6489 }
6490
6491 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6492 if (VD->hasInit()) {
6493 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6494 assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
6495 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
;
6496 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6497 VD->dropAttr<AliasAttr>();
6498 }
6499 }
6500 }
6501
6502 // 'selectany' only applies to externally visible variable declarations.
6503 // It does not apply to functions.
6504 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6505 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6506 S.Diag(Attr->getLocation(),
6507 diag::err_attribute_selectany_non_extern_data);
6508 ND.dropAttr<SelectAnyAttr>();
6509 }
6510 }
6511
6512 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6513 auto *VD = dyn_cast<VarDecl>(&ND);
6514 bool IsAnonymousNS = false;
6515 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6516 if (VD) {
6517 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6518 while (NS && !IsAnonymousNS) {
6519 IsAnonymousNS = NS->isAnonymousNamespace();
6520 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6521 }
6522 }
6523 // dll attributes require external linkage. Static locals may have external
6524 // linkage but still cannot be explicitly imported or exported.
6525 // In Microsoft mode, a variable defined in anonymous namespace must have
6526 // external linkage in order to be exported.
6527 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6528 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6529 (!AnonNSInMicrosoftMode &&
6530 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6531 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6532 << &ND << Attr;
6533 ND.setInvalidDecl();
6534 }
6535 }
6536
6537 // Check the attributes on the function type, if any.
6538 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6539 // Don't declare this variable in the second operand of the for-statement;
6540 // GCC miscompiles that by ending its lifetime before evaluating the
6541 // third operand. See gcc.gnu.org/PR86769.
6542 AttributedTypeLoc ATL;
6543 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6544 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6545 TL = ATL.getModifiedLoc()) {
6546 // The [[lifetimebound]] attribute can be applied to the implicit object
6547 // parameter of a non-static member function (other than a ctor or dtor)
6548 // by applying it to the function type.
6549 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6550 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6551 if (!MD || MD->isStatic()) {
6552 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6553 << !MD << A->getRange();
6554 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6555 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6556 << isa<CXXDestructorDecl>(MD) << A->getRange();
6557 }
6558 }
6559 }
6560 }
6561}
6562
6563static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6564 NamedDecl *NewDecl,
6565 bool IsSpecialization,
6566 bool IsDefinition) {
6567 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6568 return;
6569
6570 bool IsTemplate = false;
6571 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6572 OldDecl = OldTD->getTemplatedDecl();
6573 IsTemplate = true;
6574 if (!IsSpecialization)
6575 IsDefinition = false;
6576 }
6577 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6578 NewDecl = NewTD->getTemplatedDecl();
6579 IsTemplate = true;
6580 }
6581
6582 if (!OldDecl || !NewDecl)
6583 return;
6584
6585 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6586 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6587 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6588 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6589
6590 // dllimport and dllexport are inheritable attributes so we have to exclude
6591 // inherited attribute instances.
6592 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6593 (NewExportAttr && !NewExportAttr->isInherited());
6594
6595 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6596 // the only exception being explicit specializations.
6597 // Implicitly generated declarations are also excluded for now because there
6598 // is no other way to switch these to use dllimport or dllexport.
6599 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6600
6601 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6602 // Allow with a warning for free functions and global variables.
6603 bool JustWarn = false;
6604 if (!OldDecl->isCXXClassMember()) {
6605 auto *VD = dyn_cast<VarDecl>(OldDecl);
6606 if (VD && !VD->getDescribedVarTemplate())
6607 JustWarn = true;
6608 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6609 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6610 JustWarn = true;
6611 }
6612
6613 // We cannot change a declaration that's been used because IR has already
6614 // been emitted. Dllimported functions will still work though (modulo
6615 // address equality) as they can use the thunk.
6616 if (OldDecl->isUsed())
6617 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6618 JustWarn = false;
6619
6620 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6621 : diag::err_attribute_dll_redeclaration;
6622 S.Diag(NewDecl->getLocation(), DiagID)
6623 << NewDecl
6624 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6625 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6626 if (!JustWarn) {
6627 NewDecl->setInvalidDecl();
6628 return;
6629 }
6630 }
6631
6632 // A redeclaration is not allowed to drop a dllimport attribute, the only
6633 // exceptions being inline function definitions (except for function
6634 // templates), local extern declarations, qualified friend declarations or
6635 // special MSVC extension: in the last case, the declaration is treated as if
6636 // it were marked dllexport.
6637 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6638 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6639 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6640 // Ignore static data because out-of-line definitions are diagnosed
6641 // separately.
6642 IsStaticDataMember = VD->isStaticDataMember();
6643 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6644 VarDecl::DeclarationOnly;
6645 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6646 IsInline = FD->isInlined();
6647 IsQualifiedFriend = FD->getQualifier() &&
6648 FD->getFriendObjectKind() == Decl::FOK_Declared;
6649 }
6650
6651 if (OldImportAttr && !HasNewAttr &&
6652 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6653 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6654 if (IsMicrosoftABI && IsDefinition) {
6655 S.Diag(NewDecl->getLocation(),
6656 diag::warn_redeclaration_without_import_attribute)
6657 << NewDecl;
6658 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6659 NewDecl->dropAttr<DLLImportAttr>();
6660 NewDecl->addAttr(
6661 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6662 } else {
6663 S.Diag(NewDecl->getLocation(),
6664 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6665 << NewDecl << OldImportAttr;
6666 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6667 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6668 OldDecl->dropAttr<DLLImportAttr>();
6669 NewDecl->dropAttr<DLLImportAttr>();
6670 }
6671 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6672 // In MinGW, seeing a function declared inline drops the dllimport
6673 // attribute.
6674 OldDecl->dropAttr<DLLImportAttr>();
6675 NewDecl->dropAttr<DLLImportAttr>();
6676 S.Diag(NewDecl->getLocation(),
6677 diag::warn_dllimport_dropped_from_inline_function)
6678 << NewDecl << OldImportAttr;
6679 }
6680
6681 // A specialization of a class template member function is processed here
6682 // since it's a redeclaration. If the parent class is dllexport, the
6683 // specialization inherits that attribute. This doesn't happen automatically
6684 // since the parent class isn't instantiated until later.
6685 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6686 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6687 !NewImportAttr && !NewExportAttr) {
6688 if (const DLLExportAttr *ParentExportAttr =
6689 MD->getParent()->getAttr<DLLExportAttr>()) {
6690 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6691 NewAttr->setInherited(true);
6692 NewDecl->addAttr(NewAttr);
6693 }
6694 }
6695 }
6696}
6697
6698/// Given that we are within the definition of the given function,
6699/// will that definition behave like C99's 'inline', where the
6700/// definition is discarded except for optimization purposes?
6701static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6702 // Try to avoid calling GetGVALinkageForFunction.
6703
6704 // All cases of this require the 'inline' keyword.
6705 if (!FD->isInlined()) return false;
6706
6707 // This is only possible in C++ with the gnu_inline attribute.
6708 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6709 return false;
6710
6711 // Okay, go ahead and call the relatively-more-expensive function.
6712 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6713}
6714
6715/// Determine whether a variable is extern "C" prior to attaching
6716/// an initializer. We can't just call isExternC() here, because that
6717/// will also compute and cache whether the declaration is externally
6718/// visible, which might change when we attach the initializer.
6719///
6720/// This can only be used if the declaration is known to not be a
6721/// redeclaration of an internal linkage declaration.
6722///
6723/// For instance:
6724///
6725/// auto x = []{};
6726///
6727/// Attaching the initializer here makes this declaration not externally
6728/// visible, because its type has internal linkage.
6729///
6730/// FIXME: This is a hack.
6731template<typename T>
6732static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6733 if (S.getLangOpts().CPlusPlus) {
6734 // In C++, the overloadable attribute negates the effects of extern "C".
6735 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6736 return false;
6737
6738 // So do CUDA's host/device attributes.
6739 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6740 D->template hasAttr<CUDAHostAttr>()))
6741 return false;
6742 }
6743 return D->isExternC();
6744}
6745
6746static bool shouldConsiderLinkage(const VarDecl *VD) {
6747 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6748 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6749 isa<OMPDeclareMapperDecl>(DC))
6750 return VD->hasExternalStorage();
6751 if (DC->isFileContext())
6752 return true;
6753 if (DC->isRecord())
6754 return false;
6755 if (isa<RequiresExprBodyDecl>(DC))
6756 return false;
6757 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 6757)
;
6758}
6759
6760static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6761 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6762 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6763 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6764 return true;
6765 if (DC->isRecord())
6766 return false;
6767 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 6767)
;
6768}
6769
6770static bool hasParsedAttr(Scope *S, const Declarator &PD,
6771 ParsedAttr::Kind Kind) {
6772 // Check decl attributes on the DeclSpec.
6773 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6774 return true;
6775
6776 // Walk the declarator structure, checking decl attributes that were in a type
6777 // position to the decl itself.
6778 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6779 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6780 return true;
6781 }
6782
6783 // Finally, check attributes on the decl itself.
6784 return PD.getAttributes().hasAttribute(Kind);
6785}
6786
6787/// Adjust the \c DeclContext for a function or variable that might be a
6788/// function-local external declaration.
6789bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6790 if (!DC->isFunctionOrMethod())
6791 return false;
6792
6793 // If this is a local extern function or variable declared within a function
6794 // template, don't add it into the enclosing namespace scope until it is
6795 // instantiated; it might have a dependent type right now.
6796 if (DC->isDependentContext())
6797 return true;
6798
6799 // C++11 [basic.link]p7:
6800 // When a block scope declaration of an entity with linkage is not found to
6801 // refer to some other declaration, then that entity is a member of the
6802 // innermost enclosing namespace.
6803 //
6804 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6805 // semantically-enclosing namespace, not a lexically-enclosing one.
6806 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6807 DC = DC->getParent();
6808 return true;
6809}
6810
6811/// Returns true if given declaration has external C language linkage.
6812static bool isDeclExternC(const Decl *D) {
6813 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6814 return FD->isExternC();
6815 if (const auto *VD = dyn_cast<VarDecl>(D))
6816 return VD->isExternC();
6817
6818 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 6818)
;
6819}
6820
6821/// Returns true if there hasn't been any invalid type diagnosed.
6822static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6823 DeclContext *DC = NewVD->getDeclContext();
6824 QualType R = NewVD->getType();
6825
6826 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6827 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6828 // argument.
6829 if (R->isImageType() || R->isPipeType()) {
6830 Se.Diag(NewVD->getLocation(),
6831 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6832 << R;
6833 NewVD->setInvalidDecl();
6834 return false;
6835 }
6836
6837 // OpenCL v1.2 s6.9.r:
6838 // The event type cannot be used to declare a program scope variable.
6839 // OpenCL v2.0 s6.9.q:
6840 // The clk_event_t and reserve_id_t types cannot be declared in program
6841 // scope.
6842 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6843 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6844 Se.Diag(NewVD->getLocation(),
6845 diag::err_invalid_type_for_program_scope_var)
6846 << R;
6847 NewVD->setInvalidDecl();
6848 return false;
6849 }
6850 }
6851
6852 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6853 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6854 Se.getLangOpts())) {
6855 QualType NR = R.getCanonicalType();
6856 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6857 NR->isReferenceType()) {
6858 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6859 NR->isFunctionReferenceType()) {
6860 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6861 << NR->isReferenceType();
6862 NewVD->setInvalidDecl();
6863 return false;
6864 }
6865 NR = NR->getPointeeType();
6866 }
6867 }
6868
6869 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6870 Se.getLangOpts())) {
6871 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6872 // half array type (unless the cl_khr_fp16 extension is enabled).
6873 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6874 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6875 NewVD->setInvalidDecl();
6876 return false;
6877 }
6878 }
6879
6880 // OpenCL v1.2 s6.9.r:
6881 // The event type cannot be used with the __local, __constant and __global
6882 // address space qualifiers.
6883 if (R->isEventT()) {
6884 if (R.getAddressSpace() != LangAS::opencl_private) {
6885 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6886 NewVD->setInvalidDecl();
6887 return false;
6888 }
6889 }
6890
6891 if (R->isSamplerT()) {
6892 // OpenCL v1.2 s6.9.b p4:
6893 // The sampler type cannot be used with the __local and __global address
6894 // space qualifiers.
6895 if (R.getAddressSpace() == LangAS::opencl_local ||
6896 R.getAddressSpace() == LangAS::opencl_global) {
6897 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6898 NewVD->setInvalidDecl();
6899 }
6900
6901 // OpenCL v1.2 s6.12.14.1:
6902 // A global sampler must be declared with either the constant address
6903 // space qualifier or with the const qualifier.
6904 if (DC->isTranslationUnit() &&
6905 !(R.getAddressSpace() == LangAS::opencl_constant ||
6906 R.isConstQualified())) {
6907 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6908 NewVD->setInvalidDecl();
6909 }
6910 if (NewVD->isInvalidDecl())
6911 return false;
6912 }
6913
6914 return true;
6915}
6916
6917template <typename AttrTy>
6918static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6919 const TypedefNameDecl *TND = TT->getDecl();
6920 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6921 AttrTy *Clone = Attribute->clone(S.Context);
6922 Clone->setInherited(true);
6923 D->addAttr(Clone);
6924 }
6925}
6926
6927NamedDecl *Sema::ActOnVariableDeclarator(
6928 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6929 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6930 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6931 QualType R = TInfo->getType();
6932 DeclarationName Name = GetNameForDeclarator(D).getName();
6933
6934 IdentifierInfo *II = Name.getAsIdentifierInfo();
6935
6936 if (D.isDecompositionDeclarator()) {
6937 // Take the name of the first declarator as our name for diagnostic
6938 // purposes.
6939 auto &Decomp = D.getDecompositionDeclarator();
6940 if (!Decomp.bindings().empty()) {
6941 II = Decomp.bindings()[0].Name;
6942 Name = II;
6943 }
6944 } else if (!II) {
6945 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6946 return nullptr;
6947 }
6948
6949
6950 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6951 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6952
6953 // dllimport globals without explicit storage class are treated as extern. We
6954 // have to change the storage class this early to get the right DeclContext.
6955 if (SC == SC_None && !DC->isRecord() &&
6956 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6957 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6958 SC = SC_Extern;
6959
6960 DeclContext *OriginalDC = DC;
6961 bool IsLocalExternDecl = SC == SC_Extern &&
6962 adjustContextForLocalExternDecl(DC);
6963
6964 if (SCSpec == DeclSpec::SCS_mutable) {
6965 // mutable can only appear on non-static class members, so it's always
6966 // an error here
6967 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6968 D.setInvalidType();
6969 SC = SC_None;
6970 }
6971
6972 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6973 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6974 D.getDeclSpec().getStorageClassSpecLoc())) {
6975 // In C++11, the 'register' storage class specifier is deprecated.
6976 // Suppress the warning in system macros, it's used in macros in some
6977 // popular C system headers, such as in glibc's htonl() macro.
6978 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6979 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6980 : diag::warn_deprecated_register)
6981 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6982 }
6983
6984 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6985
6986 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6987 // C99 6.9p2: The storage-class specifiers auto and register shall not
6988 // appear in the declaration specifiers in an external declaration.
6989 // Global Register+Asm is a GNU extension we support.
6990 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6991 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6992 D.setInvalidType();
6993 }
6994 }
6995
6996 // If this variable has a VLA type and an initializer, try to
6997 // fold to a constant-sized type. This is otherwise invalid.
6998 if (D.hasInitializer() && R->isVariableArrayType())
6999 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7000 /*DiagID=*/0);
7001
7002 bool IsMemberSpecialization = false;
7003 bool IsVariableTemplateSpecialization = false;
7004 bool IsPartialSpecialization = false;
7005 bool IsVariableTemplate = false;
7006 VarDecl *NewVD = nullptr;
7007 VarTemplateDecl *NewTemplate = nullptr;
7008 TemplateParameterList *TemplateParams = nullptr;
7009 if (!getLangOpts().CPlusPlus) {
7010 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7011 II, R, TInfo, SC);
7012
7013 if (R->getContainedDeducedType())
7014 ParsingInitForAutoVars.insert(NewVD);
7015
7016 if (D.isInvalidType())
7017 NewVD->setInvalidDecl();
7018
7019 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7020 NewVD->hasLocalStorage())
7021 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7022 NTCUC_AutoVar, NTCUK_Destruct);
7023 } else {
7024 bool Invalid = false;
7025
7026 if (DC->isRecord() && !CurContext->isRecord()) {
7027 // This is an out-of-line definition of a static data member.
7028 switch (SC) {
7029 case SC_None:
7030 break;
7031 case SC_Static:
7032 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7033 diag::err_static_out_of_line)
7034 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7035 break;
7036 case SC_Auto:
7037 case SC_Register:
7038 case SC_Extern:
7039 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7040 // to names of variables declared in a block or to function parameters.
7041 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7042 // of class members
7043
7044 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7045 diag::err_storage_class_for_static_member)
7046 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7047 break;
7048 case SC_PrivateExtern:
7049 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7049)
;
7050 }
7051 }
7052
7053 if (SC == SC_Static && CurContext->isRecord()) {
7054 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7055 // Walk up the enclosing DeclContexts to check for any that are
7056 // incompatible with static data members.
7057 const DeclContext *FunctionOrMethod = nullptr;
7058 const CXXRecordDecl *AnonStruct = nullptr;
7059 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7060 if (Ctxt->isFunctionOrMethod()) {
7061 FunctionOrMethod = Ctxt;
7062 break;
7063 }
7064 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7065 if (ParentDecl && !ParentDecl->getDeclName()) {
7066 AnonStruct = ParentDecl;
7067 break;
7068 }
7069 }
7070 if (FunctionOrMethod) {
7071 // C++ [class.static.data]p5: A local class shall not have static data
7072 // members.
7073 Diag(D.getIdentifierLoc(),
7074 diag::err_static_data_member_not_allowed_in_local_class)
7075 << Name << RD->getDeclName() << RD->getTagKind();
7076 } else if (AnonStruct) {
7077 // C++ [class.static.data]p4: Unnamed classes and classes contained
7078 // directly or indirectly within unnamed classes shall not contain
7079 // static data members.
7080 Diag(D.getIdentifierLoc(),
7081 diag::err_static_data_member_not_allowed_in_anon_struct)
7082 << Name << AnonStruct->getTagKind();
7083 Invalid = true;
7084 } else if (RD->isUnion()) {
7085 // C++98 [class.union]p1: If a union contains a static data member,
7086 // the program is ill-formed. C++11 drops this restriction.
7087 Diag(D.getIdentifierLoc(),
7088 getLangOpts().CPlusPlus11
7089 ? diag::warn_cxx98_compat_static_data_member_in_union
7090 : diag::ext_static_data_member_in_union) << Name;
7091 }
7092 }
7093 }
7094
7095 // Match up the template parameter lists with the scope specifier, then
7096 // determine whether we have a template or a template specialization.
7097 bool InvalidScope = false;
7098 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7099 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7100 D.getCXXScopeSpec(),
7101 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7102 ? D.getName().TemplateId
7103 : nullptr,
7104 TemplateParamLists,
7105 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7106 Invalid |= InvalidScope;
7107
7108 if (TemplateParams) {
7109 if (!TemplateParams->size() &&
7110 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7111 // There is an extraneous 'template<>' for this variable. Complain
7112 // about it, but allow the declaration of the variable.
7113 Diag(TemplateParams->getTemplateLoc(),
7114 diag::err_template_variable_noparams)
7115 << II
7116 << SourceRange(TemplateParams->getTemplateLoc(),
7117 TemplateParams->getRAngleLoc());
7118 TemplateParams = nullptr;
7119 } else {
7120 // Check that we can declare a template here.
7121 if (CheckTemplateDeclScope(S, TemplateParams))
7122 return nullptr;
7123
7124 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7125 // This is an explicit specialization or a partial specialization.
7126 IsVariableTemplateSpecialization = true;
7127 IsPartialSpecialization = TemplateParams->size() > 0;
7128 } else { // if (TemplateParams->size() > 0)
7129 // This is a template declaration.
7130 IsVariableTemplate = true;
7131
7132 // Only C++1y supports variable templates (N3651).
7133 Diag(D.getIdentifierLoc(),
7134 getLangOpts().CPlusPlus14
7135 ? diag::warn_cxx11_compat_variable_template
7136 : diag::ext_variable_template);
7137 }
7138 }
7139 } else {
7140 // Check that we can declare a member specialization here.
7141 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7142 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7143 return nullptr;
7144 assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7146, __extension__ __PRETTY_FUNCTION__))
7145 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7146, __extension__ __PRETTY_FUNCTION__))
7146 "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7146, __extension__ __PRETTY_FUNCTION__))
;
7147 }
7148
7149 if (IsVariableTemplateSpecialization) {
7150 SourceLocation TemplateKWLoc =
7151 TemplateParamLists.size() > 0
7152 ? TemplateParamLists[0]->getTemplateLoc()
7153 : SourceLocation();
7154 DeclResult Res = ActOnVarTemplateSpecialization(
7155 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7156 IsPartialSpecialization);
7157 if (Res.isInvalid())
7158 return nullptr;
7159 NewVD = cast<VarDecl>(Res.get());
7160 AddToScope = false;
7161 } else if (D.isDecompositionDeclarator()) {
7162 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7163 D.getIdentifierLoc(), R, TInfo, SC,
7164 Bindings);
7165 } else
7166 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7167 D.getIdentifierLoc(), II, R, TInfo, SC);
7168
7169 // If this is supposed to be a variable template, create it as such.
7170 if (IsVariableTemplate) {
7171 NewTemplate =
7172 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7173 TemplateParams, NewVD);
7174 NewVD->setDescribedVarTemplate(NewTemplate);
7175 }
7176
7177 // If this decl has an auto type in need of deduction, make a note of the
7178 // Decl so we can diagnose uses of it in its own initializer.
7179 if (R->getContainedDeducedType())
7180 ParsingInitForAutoVars.insert(NewVD);
7181
7182 if (D.isInvalidType() || Invalid) {
7183 NewVD->setInvalidDecl();
7184 if (NewTemplate)
7185 NewTemplate->setInvalidDecl();
7186 }
7187
7188 SetNestedNameSpecifier(*this, NewVD, D);
7189
7190 // If we have any template parameter lists that don't directly belong to
7191 // the variable (matching the scope specifier), store them.
7192 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7193 if (TemplateParamLists.size() > VDTemplateParamLists)
7194 NewVD->setTemplateParameterListsInfo(
7195 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7196 }
7197
7198 if (D.getDeclSpec().isInlineSpecified()) {
7199 if (!getLangOpts().CPlusPlus) {
7200 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7201 << 0;
7202 } else if (CurContext->isFunctionOrMethod()) {
7203 // 'inline' is not allowed on block scope variable declaration.
7204 Diag(D.getDeclSpec().getInlineSpecLoc(),
7205 diag::err_inline_declaration_block_scope) << Name
7206 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7207 } else {
7208 Diag(D.getDeclSpec().getInlineSpecLoc(),
7209 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7210 : diag::ext_inline_variable);
7211 NewVD->setInlineSpecified();
7212 }
7213 }
7214
7215 // Set the lexical context. If the declarator has a C++ scope specifier, the
7216 // lexical context will be different from the semantic context.
7217 NewVD->setLexicalDeclContext(CurContext);
7218 if (NewTemplate)
7219 NewTemplate->setLexicalDeclContext(CurContext);
7220
7221 if (IsLocalExternDecl) {
7222 if (D.isDecompositionDeclarator())
7223 for (auto *B : Bindings)
7224 B->setLocalExternDecl();
7225 else
7226 NewVD->setLocalExternDecl();
7227 }
7228
7229 bool EmitTLSUnsupportedError = false;
7230 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7231 // C++11 [dcl.stc]p4:
7232 // When thread_local is applied to a variable of block scope the
7233 // storage-class-specifier static is implied if it does not appear
7234 // explicitly.
7235 // Core issue: 'static' is not implied if the variable is declared
7236 // 'extern'.
7237 if (NewVD->hasLocalStorage() &&
7238 (SCSpec != DeclSpec::SCS_unspecified ||
7239 TSCS != DeclSpec::TSCS_thread_local ||
7240 !DC->isFunctionOrMethod()))
7241 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7242 diag::err_thread_non_global)
7243 << DeclSpec::getSpecifierName(TSCS);
7244 else if (!Context.getTargetInfo().isTLSSupported()) {
7245 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7246 getLangOpts().SYCLIsDevice) {
7247 // Postpone error emission until we've collected attributes required to
7248 // figure out whether it's a host or device variable and whether the
7249 // error should be ignored.
7250 EmitTLSUnsupportedError = true;
7251 // We still need to mark the variable as TLS so it shows up in AST with
7252 // proper storage class for other tools to use even if we're not going
7253 // to emit any code for it.
7254 NewVD->setTSCSpec(TSCS);
7255 } else
7256 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7257 diag::err_thread_unsupported);
7258 } else
7259 NewVD->setTSCSpec(TSCS);
7260 }
7261
7262 switch (D.getDeclSpec().getConstexprSpecifier()) {
7263 case ConstexprSpecKind::Unspecified:
7264 break;
7265
7266 case ConstexprSpecKind::Consteval:
7267 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7268 diag::err_constexpr_wrong_decl_kind)
7269 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7270 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7271
7272 case ConstexprSpecKind::Constexpr:
7273 NewVD->setConstexpr(true);
7274 // C++1z [dcl.spec.constexpr]p1:
7275 // A static data member declared with the constexpr specifier is
7276 // implicitly an inline variable.
7277 if (NewVD->isStaticDataMember() &&
7278 (getLangOpts().CPlusPlus17 ||
7279 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7280 NewVD->setImplicitlyInline();
7281 break;
7282
7283 case ConstexprSpecKind::Constinit:
7284 if (!NewVD->hasGlobalStorage())
7285 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7286 diag::err_constinit_local_variable);
7287 else
7288 NewVD->addAttr(ConstInitAttr::Create(
7289 Context, D.getDeclSpec().getConstexprSpecLoc(),
7290 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7291 break;
7292 }
7293
7294 // C99 6.7.4p3
7295 // An inline definition of a function with external linkage shall
7296 // not contain a definition of a modifiable object with static or
7297 // thread storage duration...
7298 // We only apply this when the function is required to be defined
7299 // elsewhere, i.e. when the function is not 'extern inline'. Note
7300 // that a local variable with thread storage duration still has to
7301 // be marked 'static'. Also note that it's possible to get these
7302 // semantics in C++ using __attribute__((gnu_inline)).
7303 if (SC == SC_Static && S->getFnParent() != nullptr &&
7304 !NewVD->getType().isConstQualified()) {
7305 FunctionDecl *CurFD = getCurFunctionDecl();
7306 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7307 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7308 diag::warn_static_local_in_extern_inline);
7309 MaybeSuggestAddingStaticToDecl(CurFD);
7310 }
7311 }
7312
7313 if (D.getDeclSpec().isModulePrivateSpecified()) {
7314 if (IsVariableTemplateSpecialization)
7315 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7316 << (IsPartialSpecialization ? 1 : 0)
7317 << FixItHint::CreateRemoval(
7318 D.getDeclSpec().getModulePrivateSpecLoc());
7319 else if (IsMemberSpecialization)
7320 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7321 << 2
7322 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7323 else if (NewVD->hasLocalStorage())
7324 Diag(NewVD->getLocation(), diag::err_module_private_local)
7325 << 0 << NewVD
7326 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7327 << FixItHint::CreateRemoval(
7328 D.getDeclSpec().getModulePrivateSpecLoc());
7329 else {
7330 NewVD->setModulePrivate();
7331 if (NewTemplate)
7332 NewTemplate->setModulePrivate();
7333 for (auto *B : Bindings)
7334 B->setModulePrivate();
7335 }
7336 }
7337
7338 if (getLangOpts().OpenCL) {
7339 deduceOpenCLAddressSpace(NewVD);
7340
7341 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7342 if (TSC != TSCS_unspecified) {
7343 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7344 diag::err_opencl_unknown_type_specifier)
7345 << getLangOpts().getOpenCLVersionString()
7346 << DeclSpec::getSpecifierName(TSC) << 1;
7347 NewVD->setInvalidDecl();
7348 }
7349 }
7350
7351 // Handle attributes prior to checking for duplicates in MergeVarDecl
7352 ProcessDeclAttributes(S, NewVD, D);
7353
7354 // FIXME: This is probably the wrong location to be doing this and we should
7355 // probably be doing this for more attributes (especially for function
7356 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7357 // the code to copy attributes would be generated by TableGen.
7358 if (R->isFunctionPointerType())
7359 if (const auto *TT = R->getAs<TypedefType>())
7360 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7361
7362 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7363 getLangOpts().SYCLIsDevice) {
7364 if (EmitTLSUnsupportedError &&
7365 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7366 (getLangOpts().OpenMPIsDevice &&
7367 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7368 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7369 diag::err_thread_unsupported);
7370
7371 if (EmitTLSUnsupportedError &&
7372 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7373 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7374 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7375 // storage [duration]."
7376 if (SC == SC_None && S->getFnParent() != nullptr &&
7377 (NewVD->hasAttr<CUDASharedAttr>() ||
7378 NewVD->hasAttr<CUDAConstantAttr>())) {
7379 NewVD->setStorageClass(SC_Static);
7380 }
7381 }
7382
7383 // Ensure that dllimport globals without explicit storage class are treated as
7384 // extern. The storage class is set above using parsed attributes. Now we can
7385 // check the VarDecl itself.
7386 assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7388, __extension__ __PRETTY_FUNCTION__))
7387 NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7388, __extension__ __PRETTY_FUNCTION__))
7388 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7388, __extension__ __PRETTY_FUNCTION__))
;
7389
7390 // In auto-retain/release, infer strong retension for variables of
7391 // retainable type.
7392 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7393 NewVD->setInvalidDecl();
7394
7395 // Handle GNU asm-label extension (encoded as an attribute).
7396 if (Expr *E = (Expr*)D.getAsmLabel()) {
7397 // The parser guarantees this is a string.
7398 StringLiteral *SE = cast<StringLiteral>(E);
7399 StringRef Label = SE->getString();
7400 if (S->getFnParent() != nullptr) {
7401 switch (SC) {
7402 case SC_None:
7403 case SC_Auto:
7404 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7405 break;
7406 case SC_Register:
7407 // Local Named register
7408 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7409 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7410 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7411 break;
7412 case SC_Static:
7413 case SC_Extern:
7414 case SC_PrivateExtern:
7415 break;
7416 }
7417 } else if (SC == SC_Register) {
7418 // Global Named register
7419 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7420 const auto &TI = Context.getTargetInfo();
7421 bool HasSizeMismatch;
7422
7423 if (!TI.isValidGCCRegisterName(Label))
7424 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7425 else if (!TI.validateGlobalRegisterVariable(Label,
7426 Context.getTypeSize(R),
7427 HasSizeMismatch))
7428 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7429 else if (HasSizeMismatch)
7430 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7431 }
7432
7433 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7434 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7435 NewVD->setInvalidDecl(true);
7436 }
7437 }
7438
7439 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7440 /*IsLiteralLabel=*/true,
7441 SE->getStrTokenLoc(0)));
7442 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7443 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7444 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7445 if (I != ExtnameUndeclaredIdentifiers.end()) {
7446 if (isDeclExternC(NewVD)) {
7447 NewVD->addAttr(I->second);
7448 ExtnameUndeclaredIdentifiers.erase(I);
7449 } else
7450 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7451 << /*Variable*/1 << NewVD;
7452 }
7453 }
7454
7455 // Find the shadowed declaration before filtering for scope.
7456 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7457 ? getShadowedDeclaration(NewVD, Previous)
7458 : nullptr;
7459
7460 // Don't consider existing declarations that are in a different
7461 // scope and are out-of-semantic-context declarations (if the new
7462 // declaration has linkage).
7463 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7464 D.getCXXScopeSpec().isNotEmpty() ||
7465 IsMemberSpecialization ||
7466 IsVariableTemplateSpecialization);
7467
7468 // Check whether the previous declaration is in the same block scope. This
7469 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7470 if (getLangOpts().CPlusPlus &&
7471 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7472 NewVD->setPreviousDeclInSameBlockScope(
7473 Previous.isSingleResult() && !Previous.isShadowed() &&
7474 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7475
7476 if (!getLangOpts().CPlusPlus) {
7477 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7478 } else {
7479 // If this is an explicit specialization of a static data member, check it.
7480 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7481 CheckMemberSpecialization(NewVD, Previous))
7482 NewVD->setInvalidDecl();
7483
7484 // Merge the decl with the existing one if appropriate.
7485 if (!Previous.empty()) {
7486 if (Previous.isSingleResult() &&
7487 isa<FieldDecl>(Previous.getFoundDecl()) &&
7488 D.getCXXScopeSpec().isSet()) {
7489 // The user tried to define a non-static data member
7490 // out-of-line (C++ [dcl.meaning]p1).
7491 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7492 << D.getCXXScopeSpec().getRange();
7493 Previous.clear();
7494 NewVD->setInvalidDecl();
7495 }
7496 } else if (D.getCXXScopeSpec().isSet()) {
7497 // No previous declaration in the qualifying scope.
7498 Diag(D.getIdentifierLoc(), diag::err_no_member)
7499 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7500 << D.getCXXScopeSpec().getRange();
7501 NewVD->setInvalidDecl();
7502 }
7503
7504 if (!IsVariableTemplateSpecialization)
7505 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7506
7507 if (NewTemplate) {
7508 VarTemplateDecl *PrevVarTemplate =
7509 NewVD->getPreviousDecl()
7510 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7511 : nullptr;
7512
7513 // Check the template parameter list of this declaration, possibly
7514 // merging in the template parameter list from the previous variable
7515 // template declaration.
7516 if (CheckTemplateParameterList(
7517 TemplateParams,
7518 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7519 : nullptr,
7520 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7521 DC->isDependentContext())
7522 ? TPC_ClassTemplateMember
7523 : TPC_VarTemplate))
7524 NewVD->setInvalidDecl();
7525
7526 // If we are providing an explicit specialization of a static variable
7527 // template, make a note of that.
7528 if (PrevVarTemplate &&
7529 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7530 PrevVarTemplate->setMemberSpecialization();
7531 }
7532 }
7533
7534 // Diagnose shadowed variables iff this isn't a redeclaration.
7535 if (ShadowedDecl && !D.isRedeclaration())
7536 CheckShadow(NewVD, ShadowedDecl, Previous);
7537
7538 ProcessPragmaWeak(S, NewVD);
7539
7540 // If this is the first declaration of an extern C variable, update
7541 // the map of such variables.
7542 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7543 isIncompleteDeclExternC(*this, NewVD))
7544 RegisterLocallyScopedExternCDecl(NewVD, S);
7545
7546 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7547 MangleNumberingContext *MCtx;
7548 Decl *ManglingContextDecl;
7549 std::tie(MCtx, ManglingContextDecl) =
7550 getCurrentMangleNumberContext(NewVD->getDeclContext());
7551 if (MCtx) {
7552 Context.setManglingNumber(
7553 NewVD, MCtx->getManglingNumber(
7554 NewVD, getMSManglingNumber(getLangOpts(), S)));
7555 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7556 }
7557 }
7558
7559 // Special handling of variable named 'main'.
7560 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7561 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7562 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7563
7564 // C++ [basic.start.main]p3
7565 // A program that declares a variable main at global scope is ill-formed.
7566 if (getLangOpts().CPlusPlus)
7567 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7568
7569 // In C, and external-linkage variable named main results in undefined
7570 // behavior.
7571 else if (NewVD->hasExternalFormalLinkage())
7572 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7573 }
7574
7575 if (D.isRedeclaration() && !Previous.empty()) {
7576 NamedDecl *Prev = Previous.getRepresentativeDecl();
7577 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7578 D.isFunctionDefinition());
7579 }
7580
7581 if (NewTemplate) {
7582 if (NewVD->isInvalidDecl())
7583 NewTemplate->setInvalidDecl();
7584 ActOnDocumentableDecl(NewTemplate);
7585 return NewTemplate;
7586 }
7587
7588 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7589 CompleteMemberSpecialization(NewVD, Previous);
7590
7591 return NewVD;
7592}
7593
7594/// Enum describing the %select options in diag::warn_decl_shadow.
7595enum ShadowedDeclKind {
7596 SDK_Local,
7597 SDK_Global,
7598 SDK_StaticMember,
7599 SDK_Field,
7600 SDK_Typedef,
7601 SDK_Using,
7602 SDK_StructuredBinding
7603};
7604
7605/// Determine what kind of declaration we're shadowing.
7606static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7607 const DeclContext *OldDC) {
7608 if (isa<TypeAliasDecl>(ShadowedDecl))
7609 return SDK_Using;
7610 else if (isa<TypedefDecl>(ShadowedDecl))
7611 return SDK_Typedef;
7612 else if (isa<BindingDecl>(ShadowedDecl))
7613 return SDK_StructuredBinding;
7614 else if (isa<RecordDecl>(OldDC))
7615 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7616
7617 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7618}
7619
7620/// Return the location of the capture if the given lambda captures the given
7621/// variable \p VD, or an invalid source location otherwise.
7622static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7623 const VarDecl *VD) {
7624 for (const Capture &Capture : LSI->Captures) {
7625 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7626 return Capture.getLocation();
7627 }
7628 return SourceLocation();
7629}
7630
7631static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7632 const LookupResult &R) {
7633 // Only diagnose if we're shadowing an unambiguous field or variable.
7634 if (R.getResultKind() != LookupResult::Found)
7635 return false;
7636
7637 // Return false if warning is ignored.
7638 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7639}
7640
7641/// Return the declaration shadowed by the given variable \p D, or null
7642/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7643NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7644 const LookupResult &R) {
7645 if (!shouldWarnIfShadowedDecl(Diags, R))
7646 return nullptr;
7647
7648 // Don't diagnose declarations at file scope.
7649 if (D->hasGlobalStorage())
7650 return nullptr;
7651
7652 NamedDecl *ShadowedDecl = R.getFoundDecl();
7653 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7654 : nullptr;
7655}
7656
7657/// Return the declaration shadowed by the given typedef \p D, or null
7658/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7659NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7660 const LookupResult &R) {
7661 // Don't warn if typedef declaration is part of a class
7662 if (D->getDeclContext()->isRecord())
7663 return nullptr;
7664
7665 if (!shouldWarnIfShadowedDecl(Diags, R))
7666 return nullptr;
7667
7668 NamedDecl *ShadowedDecl = R.getFoundDecl();
7669 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7670}
7671
7672/// Return the declaration shadowed by the given variable \p D, or null
7673/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7674NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7675 const LookupResult &R) {
7676 if (!shouldWarnIfShadowedDecl(Diags, R))
7677 return nullptr;
7678
7679 NamedDecl *ShadowedDecl = R.getFoundDecl();
7680 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7681 : nullptr;
7682}
7683
7684/// Diagnose variable or built-in function shadowing. Implements
7685/// -Wshadow.
7686///
7687/// This method is called whenever a VarDecl is added to a "useful"
7688/// scope.
7689///
7690/// \param ShadowedDecl the declaration that is shadowed by the given variable
7691/// \param R the lookup of the name
7692///
7693void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7694 const LookupResult &R) {
7695 DeclContext *NewDC = D->getDeclContext();
7696
7697 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7698 // Fields are not shadowed by variables in C++ static methods.
7699 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7700 if (MD->isStatic())
7701 return;
7702
7703 // Fields shadowed by constructor parameters are a special case. Usually
7704 // the constructor initializes the field with the parameter.
7705 if (isa<CXXConstructorDecl>(NewDC))
7706 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7707 // Remember that this was shadowed so we can either warn about its
7708 // modification or its existence depending on warning settings.
7709 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7710 return;
7711 }
7712 }
7713
7714 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7715 if (shadowedVar->isExternC()) {
7716 // For shadowing external vars, make sure that we point to the global
7717 // declaration, not a locally scoped extern declaration.
7718 for (auto I : shadowedVar->redecls())
7719 if (I->isFileVarDecl()) {
7720 ShadowedDecl = I;
7721 break;
7722 }
7723 }
7724
7725 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7726
7727 unsigned WarningDiag = diag::warn_decl_shadow;
7728 SourceLocation CaptureLoc;
7729 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7730 isa<CXXMethodDecl>(NewDC)) {
7731 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7732 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7733 if (RD->getLambdaCaptureDefault() == LCD_None) {
7734 // Try to avoid warnings for lambdas with an explicit capture list.
7735 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7736 // Warn only when the lambda captures the shadowed decl explicitly.
7737 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7738 if (CaptureLoc.isInvalid())
7739 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7740 } else {
7741 // Remember that this was shadowed so we can avoid the warning if the
7742 // shadowed decl isn't captured and the warning settings allow it.
7743 cast<LambdaScopeInfo>(getCurFunction())
7744 ->ShadowingDecls.push_back(
7745 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7746 return;
7747 }
7748 }
7749
7750 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7751 // A variable can't shadow a local variable in an enclosing scope, if
7752 // they are separated by a non-capturing declaration context.
7753 for (DeclContext *ParentDC = NewDC;
7754 ParentDC && !ParentDC->Equals(OldDC);
7755 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7756 // Only block literals, captured statements, and lambda expressions
7757 // can capture; other scopes don't.
7758 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7759 !isLambdaCallOperator(ParentDC)) {
7760 return;
7761 }
7762 }
7763 }
7764 }
7765 }
7766
7767 // Only warn about certain kinds of shadowing for class members.
7768 if (NewDC && NewDC->isRecord()) {
7769 // In particular, don't warn about shadowing non-class members.
7770 if (!OldDC->isRecord())
7771 return;
7772
7773 // TODO: should we warn about static data members shadowing
7774 // static data members from base classes?
7775
7776 // TODO: don't diagnose for inaccessible shadowed members.
7777 // This is hard to do perfectly because we might friend the
7778 // shadowing context, but that's just a false negative.
7779 }
7780
7781
7782 DeclarationName Name = R.getLookupName();
7783
7784 // Emit warning and note.
7785 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7786 return;
7787 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7788 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7789 if (!CaptureLoc.isInvalid())
7790 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7791 << Name << /*explicitly*/ 1;
7792 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7793}
7794
7795/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7796/// when these variables are captured by the lambda.
7797void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7798 for (const auto &Shadow : LSI->ShadowingDecls) {
7799 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7800 // Try to avoid the warning when the shadowed decl isn't captured.
7801 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7802 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7803 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7804 ? diag::warn_decl_shadow_uncaptured_local
7805 : diag::warn_decl_shadow)
7806 << Shadow.VD->getDeclName()
7807 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7808 if (!CaptureLoc.isInvalid())
7809 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7810 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7811 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7812 }
7813}
7814
7815/// Check -Wshadow without the advantage of a previous lookup.
7816void Sema::CheckShadow(Scope *S, VarDecl *D) {
7817 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7818 return;
7819
7820 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7821 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7822 LookupName(R, S);
7823 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7824 CheckShadow(D, ShadowedDecl, R);
7825}
7826
7827/// Check if 'E', which is an expression that is about to be modified, refers
7828/// to a constructor parameter that shadows a field.
7829void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7830 // Quickly ignore expressions that can't be shadowing ctor parameters.
7831 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7832 return;
7833 E = E->IgnoreParenImpCasts();
7834 auto *DRE = dyn_cast<DeclRefExpr>(E);
7835 if (!DRE)
7836 return;
7837 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7838 auto I = ShadowingDecls.find(D);
7839 if (I == ShadowingDecls.end())
7840 return;
7841 const NamedDecl *ShadowedDecl = I->second;
7842 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7843 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7844 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7845 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7846
7847 // Avoid issuing multiple warnings about the same decl.
7848 ShadowingDecls.erase(I);
7849}
7850
7851/// Check for conflict between this global or extern "C" declaration and
7852/// previous global or extern "C" declarations. This is only used in C++.
7853template<typename T>
7854static bool checkGlobalOrExternCConflict(
7855 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7856 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus &&
"only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7856, __extension__ __PRETTY_FUNCTION__))
;
7857 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7858
7859 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7860 // The common case: this global doesn't conflict with any extern "C"
7861 // declaration.
7862 return false;
7863 }
7864
7865 if (Prev) {
7866 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7867 // Both the old and new declarations have C language linkage. This is a
7868 // redeclaration.
7869 Previous.clear();
7870 Previous.addDecl(Prev);
7871 return true;
7872 }
7873
7874 // This is a global, non-extern "C" declaration, and there is a previous
7875 // non-global extern "C" declaration. Diagnose if this is a variable
7876 // declaration.
7877 if (!isa<VarDecl>(ND))
7878 return false;
7879 } else {
7880 // The declaration is extern "C". Check for any declaration in the
7881 // translation unit which might conflict.
7882 if (IsGlobal) {
7883 // We have already performed the lookup into the translation unit.
7884 IsGlobal = false;
7885 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7886 I != E; ++I) {
7887 if (isa<VarDecl>(*I)) {
7888 Prev = *I;
7889 break;
7890 }
7891 }
7892 } else {
7893 DeclContext::lookup_result R =
7894 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7895 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7896 I != E; ++I) {
7897 if (isa<VarDecl>(*I)) {
7898 Prev = *I;
7899 break;
7900 }
7901 // FIXME: If we have any other entity with this name in global scope,
7902 // the declaration is ill-formed, but that is a defect: it breaks the
7903 // 'stat' hack, for instance. Only variables can have mangled name
7904 // clashes with extern "C" declarations, so only they deserve a
7905 // diagnostic.
7906 }
7907 }
7908
7909 if (!Prev)
7910 return false;
7911 }
7912
7913 // Use the first declaration's location to ensure we point at something which
7914 // is lexically inside an extern "C" linkage-spec.
7915 assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose"
) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 7915, __extension__ __PRETTY_FUNCTION__))
;
7916 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7917 Prev = FD->getFirstDecl();
7918 else
7919 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7920
7921 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7922 << IsGlobal << ND;
7923 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7924 << IsGlobal;
7925 return false;
7926}
7927
7928/// Apply special rules for handling extern "C" declarations. Returns \c true
7929/// if we have found that this is a redeclaration of some prior entity.
7930///
7931/// Per C++ [dcl.link]p6:
7932/// Two declarations [for a function or variable] with C language linkage
7933/// with the same name that appear in different scopes refer to the same
7934/// [entity]. An entity with C language linkage shall not be declared with
7935/// the same name as an entity in global scope.
7936template<typename T>
7937static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7938 LookupResult &Previous) {
7939 if (!S.getLangOpts().CPlusPlus) {
7940 // In C, when declaring a global variable, look for a corresponding 'extern'
7941 // variable declared in function scope. We don't need this in C++, because
7942 // we find local extern decls in the surrounding file-scope DeclContext.
7943 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7944 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7945 Previous.clear();
7946 Previous.addDecl(Prev);
7947 return true;
7948 }
7949 }
7950 return false;
7951 }
7952
7953 // A declaration in the translation unit can conflict with an extern "C"
7954 // declaration.
7955 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7956 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7957
7958 // An extern "C" declaration can conflict with a declaration in the
7959 // translation unit or can be a redeclaration of an extern "C" declaration
7960 // in another scope.
7961 if (isIncompleteDeclExternC(S,ND))
7962 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7963
7964 // Neither global nor extern "C": nothing to do.
7965 return false;
7966}
7967
7968void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7969 // If the decl is already known invalid, don't check it.
7970 if (NewVD->isInvalidDecl())
7971 return;
7972
7973 QualType T = NewVD->getType();
7974
7975 // Defer checking an 'auto' type until its initializer is attached.
7976 if (T->isUndeducedType())
7977 return;
7978
7979 if (NewVD->hasAttrs())
7980 CheckAlignasUnderalignment(NewVD);
7981
7982 if (T->isObjCObjectType()) {
7983 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7984 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7985 T = Context.getObjCObjectPointerType(T);
7986 NewVD->setType(T);
7987 }
7988
7989 // Emit an error if an address space was applied to decl with local storage.
7990 // This includes arrays of objects with address space qualifiers, but not
7991 // automatic variables that point to other address spaces.
7992 // ISO/IEC TR 18037 S5.1.2
7993 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7994 T.getAddressSpace() != LangAS::Default) {
7995 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7996 NewVD->setInvalidDecl();
7997 return;
7998 }
7999
8000 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8001 // scope.
8002 if (getLangOpts().OpenCLVersion == 120 &&
8003 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8004 getLangOpts()) &&
8005 NewVD->isStaticLocal()) {
8006 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8007 NewVD->setInvalidDecl();
8008 return;
8009 }
8010
8011 if (getLangOpts().OpenCL) {
8012 if (!diagnoseOpenCLTypes(*this, NewVD))
8013 return;
8014
8015 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8016 if (NewVD->hasAttr<BlocksAttr>()) {
8017 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8018 return;
8019 }
8020
8021 if (T->isBlockPointerType()) {
8022 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8023 // can't use 'extern' storage class.
8024 if (!T.isConstQualified()) {
8025 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8026 << 0 /*const*/;
8027 NewVD->setInvalidDecl();
8028 return;
8029 }
8030 if (NewVD->hasExternalStorage()) {
8031 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8032 NewVD->setInvalidDecl();
8033 return;
8034 }
8035 }
8036
8037 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8038 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8039 NewVD->hasExternalStorage()) {
8040 if (!T->isSamplerT() && !T->isDependentType() &&
8041 !(T.getAddressSpace() == LangAS::opencl_constant ||
8042 (T.getAddressSpace() == LangAS::opencl_global &&
8043 getOpenCLOptions().areProgramScopeVariablesSupported(
8044 getLangOpts())))) {
8045 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8046 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8047 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8048 << Scope << "global or constant";
8049 else
8050 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8051 << Scope << "constant";
8052 NewVD->setInvalidDecl();
8053 return;
8054 }
8055 } else {
8056 if (T.getAddressSpace() == LangAS::opencl_global) {
8057 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8058 << 1 /*is any function*/ << "global";
8059 NewVD->setInvalidDecl();
8060 return;
8061 }
8062 if (T.getAddressSpace() == LangAS::opencl_constant ||
8063 T.getAddressSpace() == LangAS::opencl_local) {
8064 FunctionDecl *FD = getCurFunctionDecl();
8065 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8066 // in functions.
8067 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8068 if (T.getAddressSpace() == LangAS::opencl_constant)
8069 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8070 << 0 /*non-kernel only*/ << "constant";
8071 else
8072 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8073 << 0 /*non-kernel only*/ << "local";
8074 NewVD->setInvalidDecl();
8075 return;
8076 }
8077 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8078 // in the outermost scope of a kernel function.
8079 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8080 if (!getCurScope()->isFunctionScope()) {
8081 if (T.getAddressSpace() == LangAS::opencl_constant)
8082 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8083 << "constant";
8084 else
8085 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8086 << "local";
8087 NewVD->setInvalidDecl();
8088 return;
8089 }
8090 }
8091 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8092 // If we are parsing a template we didn't deduce an addr
8093 // space yet.
8094 T.getAddressSpace() != LangAS::Default) {
8095 // Do not allow other address spaces on automatic variable.
8096 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8097 NewVD->setInvalidDecl();
8098 return;
8099 }
8100 }
8101 }
8102
8103 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8104 && !NewVD->hasAttr<BlocksAttr>()) {
8105 if (getLangOpts().getGC() != LangOptions::NonGC)
8106 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8107 else {
8108 assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ?
void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8108, __extension__ __PRETTY_FUNCTION__))
;
8109 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8110 }
8111 }
8112
8113 bool isVM = T->isVariablyModifiedType();
8114 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8115 NewVD->hasAttr<BlocksAttr>())
8116 setFunctionHasBranchProtectedScope();
8117
8118 if ((isVM && NewVD->hasLinkage()) ||
8119 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8120 bool SizeIsNegative;
8121 llvm::APSInt Oversized;
8122 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8123 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8124 QualType FixedT;
8125 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8126 FixedT = FixedTInfo->getType();
8127 else if (FixedTInfo) {
8128 // Type and type-as-written are canonically different. We need to fix up
8129 // both types separately.
8130 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8131 Oversized);
8132 }
8133 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8134 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8135 // FIXME: This won't give the correct result for
8136 // int a[10][n];
8137 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8138
8139 if (NewVD->isFileVarDecl())
8140 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8141 << SizeRange;
8142 else if (NewVD->isStaticLocal())
8143 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8144 << SizeRange;
8145 else
8146 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8147 << SizeRange;
8148 NewVD->setInvalidDecl();
8149 return;
8150 }
8151
8152 if (!FixedTInfo) {
8153 if (NewVD->isFileVarDecl())
8154 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8155 else
8156 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8157 NewVD->setInvalidDecl();
8158 return;
8159 }
8160
8161 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8162 NewVD->setType(FixedT);
8163 NewVD->setTypeSourceInfo(FixedTInfo);
8164 }
8165
8166 if (T->isVoidType()) {
8167 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8168 // of objects and functions.
8169 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8170 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8171 << T;
8172 NewVD->setInvalidDecl();
8173 return;
8174 }
8175 }
8176
8177 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8178 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8179 NewVD->setInvalidDecl();
8180 return;
8181 }
8182
8183 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8184 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8185 NewVD->setInvalidDecl();
8186 return;
8187 }
8188
8189 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8190 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8191 NewVD->setInvalidDecl();
8192 return;
8193 }
8194
8195 if (NewVD->isConstexpr() && !T->isDependentType() &&
8196 RequireLiteralType(NewVD->getLocation(), T,
8197 diag::err_constexpr_var_non_literal)) {
8198 NewVD->setInvalidDecl();
8199 return;
8200 }
8201
8202 // PPC MMA non-pointer types are not allowed as non-local variable types.
8203 if (Context.getTargetInfo().getTriple().isPPC64() &&
8204 !NewVD->isLocalVarDecl() &&
8205 CheckPPCMMAType(T, NewVD->getLocation())) {
8206 NewVD->setInvalidDecl();
8207 return;
8208 }
8209}
8210
8211/// Perform semantic checking on a newly-created variable
8212/// declaration.
8213///
8214/// This routine performs all of the type-checking required for a
8215/// variable declaration once it has been built. It is used both to
8216/// check variables after they have been parsed and their declarators
8217/// have been translated into a declaration, and to check variables
8218/// that have been instantiated from a template.
8219///
8220/// Sets NewVD->isInvalidDecl() if an error was encountered.
8221///
8222/// Returns true if the variable declaration is a redeclaration.
8223bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8224 CheckVariableDeclarationType(NewVD);
8225
8226 // If the decl is already known invalid, don't check it.
8227 if (NewVD->isInvalidDecl())
8228 return false;
8229
8230 // If we did not find anything by this name, look for a non-visible
8231 // extern "C" declaration with the same name.
8232 if (Previous.empty() &&
8233 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8234 Previous.setShadowed();
8235
8236 if (!Previous.empty()) {
8237 MergeVarDecl(NewVD, Previous);
8238 return true;
8239 }
8240 return false;
8241}
8242
8243/// AddOverriddenMethods - See if a method overrides any in the base classes,
8244/// and if so, check that it's a valid override and remember it.
8245bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8246 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8247
8248 // Look for methods in base classes that this method might override.
8249 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8250 /*DetectVirtual=*/false);
8251 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8252 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8253 DeclarationName Name = MD->getDeclName();
8254
8255 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8256 // We really want to find the base class destructor here.
8257 QualType T = Context.getTypeDeclType(BaseRecord);
8258 CanQualType CT = Context.getCanonicalType(T);
8259 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8260 }
8261
8262 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8263 CXXMethodDecl *BaseMD =
8264 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8265 if (!BaseMD || !BaseMD->isVirtual() ||
8266 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8267 /*ConsiderCudaAttrs=*/true,
8268 // C++2a [class.virtual]p2 does not consider requires
8269 // clauses when overriding.
8270 /*ConsiderRequiresClauses=*/false))
8271 continue;
8272
8273 if (Overridden.insert(BaseMD).second) {
8274 MD->addOverriddenMethod(BaseMD);
8275 CheckOverridingFunctionReturnType(MD, BaseMD);
8276 CheckOverridingFunctionAttributes(MD, BaseMD);
8277 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8278 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8279 }
8280
8281 // A method can only override one function from each base class. We
8282 // don't track indirectly overridden methods from bases of bases.
8283 return true;
8284 }
8285
8286 return false;
8287 };
8288
8289 DC->lookupInBases(VisitBase, Paths);
8290 return !Overridden.empty();
8291}
8292
8293namespace {
8294 // Struct for holding all of the extra arguments needed by
8295 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8296 struct ActOnFDArgs {
8297 Scope *S;
8298 Declarator &D;
8299 MultiTemplateParamsArg TemplateParamLists;
8300 bool AddToScope;
8301 };
8302} // end anonymous namespace
8303
8304namespace {
8305
8306// Callback to only accept typo corrections that have a non-zero edit distance.
8307// Also only accept corrections that have the same parent decl.
8308class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8309 public:
8310 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8311 CXXRecordDecl *Parent)
8312 : Context(Context), OriginalFD(TypoFD),
8313 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8314
8315 bool ValidateCandidate(const TypoCorrection &candidate) override {
8316 if (candidate.getEditDistance() == 0)
8317 return false;
8318
8319 SmallVector<unsigned, 1> MismatchedParams;
8320 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8321 CDeclEnd = candidate.end();
8322 CDecl != CDeclEnd; ++CDecl) {
8323 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8324
8325 if (FD && !FD->hasBody() &&
8326 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8327 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8328 CXXRecordDecl *Parent = MD->getParent();
8329 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8330 return true;
8331 } else if (!ExpectedParent) {
8332 return true;
8333 }
8334 }
8335 }
8336
8337 return false;
8338 }
8339
8340 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8341 return std::make_unique<DifferentNameValidatorCCC>(*this);
8342 }
8343
8344 private:
8345 ASTContext &Context;
8346 FunctionDecl *OriginalFD;
8347 CXXRecordDecl *ExpectedParent;
8348};
8349
8350} // end anonymous namespace
8351
8352void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8353 TypoCorrectedFunctionDefinitions.insert(F);
8354}
8355
8356/// Generate diagnostics for an invalid function redeclaration.
8357///
8358/// This routine handles generating the diagnostic messages for an invalid
8359/// function redeclaration, including finding possible similar declarations
8360/// or performing typo correction if there are no previous declarations with
8361/// the same name.
8362///
8363/// Returns a NamedDecl iff typo correction was performed and substituting in
8364/// the new declaration name does not cause new errors.
8365static NamedDecl *DiagnoseInvalidRedeclaration(
8366 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8367 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8368 DeclarationName Name = NewFD->getDeclName();
8369 DeclContext *NewDC = NewFD->getDeclContext();
8370 SmallVector<unsigned, 1> MismatchedParams;
8371 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8372 TypoCorrection Correction;
8373 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8374 unsigned DiagMsg =
8375 IsLocalFriend ? diag::err_no_matching_local_friend :
8376 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8377 diag::err_member_decl_does_not_match;
8378 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8379 IsLocalFriend ? Sema::LookupLocalFriendName
8380 : Sema::LookupOrdinaryName,
8381 Sema::ForVisibleRedeclaration);
8382
8383 NewFD->setInvalidDecl();
8384 if (IsLocalFriend)
8385 SemaRef.LookupName(Prev, S);
8386 else
8387 SemaRef.LookupQualifiedName(Prev, NewDC);
8388 assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8389, __extension__ __PRETTY_FUNCTION__))
8389 "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8389, __extension__ __PRETTY_FUNCTION__))
;
8390 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8391 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8392 MD ? MD->getParent() : nullptr);
8393 if (!Prev.empty()) {
8394 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8395 Func != FuncEnd; ++Func) {
8396 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8397 if (FD &&
8398 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8399 // Add 1 to the index so that 0 can mean the mismatch didn't
8400 // involve a parameter
8401 unsigned ParamNum =
8402 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8403 NearMatches.push_back(std::make_pair(FD, ParamNum));
8404 }
8405 }
8406 // If the qualified name lookup yielded nothing, try typo correction
8407 } else if ((Correction = SemaRef.CorrectTypo(
8408 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8409 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8410 IsLocalFriend ? nullptr : NewDC))) {
8411 // Set up everything for the call to ActOnFunctionDeclarator
8412 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8413 ExtraArgs.D.getIdentifierLoc());
8414 Previous.clear();
8415 Previous.setLookupName(Correction.getCorrection());
8416 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8417 CDeclEnd = Correction.end();
8418 CDecl != CDeclEnd; ++CDecl) {
8419 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8420 if (FD && !FD->hasBody() &&
8421 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8422 Previous.addDecl(FD);
8423 }
8424 }
8425 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8426
8427 NamedDecl *Result;
8428 // Retry building the function declaration with the new previous
8429 // declarations, and with errors suppressed.
8430 {
8431 // Trap errors.
8432 Sema::SFINAETrap Trap(SemaRef);
8433
8434 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8435 // pieces need to verify the typo-corrected C++ declaration and hopefully
8436 // eliminate the need for the parameter pack ExtraArgs.
8437 Result = SemaRef.ActOnFunctionDeclarator(
8438 ExtraArgs.S, ExtraArgs.D,
8439 Correction.getCorrectionDecl()->getDeclContext(),
8440 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8441 ExtraArgs.AddToScope);
8442
8443 if (Trap.hasErrorOccurred())
8444 Result = nullptr;
8445 }
8446
8447 if (Result) {
8448 // Determine which correction we picked.
8449 Decl *Canonical = Result->getCanonicalDecl();
8450 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8451 I != E; ++I)
8452 if ((*I)->getCanonicalDecl() == Canonical)
8453 Correction.setCorrectionDecl(*I);
8454
8455 // Let Sema know about the correction.
8456 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8457 SemaRef.diagnoseTypo(
8458 Correction,
8459 SemaRef.PDiag(IsLocalFriend
8460 ? diag::err_no_matching_local_friend_suggest
8461 : diag::err_member_decl_does_not_match_suggest)
8462 << Name << NewDC << IsDefinition);
8463 return Result;
8464 }
8465
8466 // Pretend the typo correction never occurred
8467 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8468 ExtraArgs.D.getIdentifierLoc());
8469 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8470 Previous.clear();
8471 Previous.setLookupName(Name);
8472 }
8473
8474 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8475 << Name << NewDC << IsDefinition << NewFD->getLocation();
8476
8477 bool NewFDisConst = false;
8478 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8479 NewFDisConst = NewMD->isConst();
8480
8481 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8482 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8483 NearMatch != NearMatchEnd; ++NearMatch) {
8484 FunctionDecl *FD = NearMatch->first;
8485 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8486 bool FDisConst = MD && MD->isConst();
8487 bool IsMember = MD || !IsLocalFriend;
8488
8489 // FIXME: These notes are poorly worded for the local friend case.
8490 if (unsigned Idx = NearMatch->second) {
8491 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8492 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8493 if (Loc.isInvalid()) Loc = FD->getLocation();
8494 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8495 : diag::note_local_decl_close_param_match)
8496 << Idx << FDParam->getType()
8497 << NewFD->getParamDecl(Idx - 1)->getType();
8498 } else if (FDisConst != NewFDisConst) {
8499 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8500 << NewFDisConst << FD->getSourceRange().getEnd();
8501 } else
8502 SemaRef.Diag(FD->getLocation(),
8503 IsMember ? diag::note_member_def_close_match
8504 : diag::note_local_decl_close_match);
8505 }
8506 return nullptr;
8507}
8508
8509static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8510 switch (D.getDeclSpec().getStorageClassSpec()) {
12
Control jumps to 'case SCS_private_extern:' at line 8538
8511 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8511)
;
8512 case DeclSpec::SCS_auto:
8513 case DeclSpec::SCS_register:
8514 case DeclSpec::SCS_mutable:
8515 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8516 diag::err_typecheck_sclass_func);
8517 D.getMutableDeclSpec().ClearStorageClassSpecs();
8518 D.setInvalidType();
8519 break;
8520 case DeclSpec::SCS_unspecified: break;
8521 case DeclSpec::SCS_extern:
8522 if (D.getDeclSpec().isExternInLinkageSpec())
8523 return SC_None;
8524 return SC_Extern;
8525 case DeclSpec::SCS_static: {
8526 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8527 // C99 6.7.1p5:
8528 // The declaration of an identifier for a function that has
8529 // block scope shall have no explicit storage-class specifier
8530 // other than extern
8531 // See also (C++ [dcl.stc]p4).
8532 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8533 diag::err_static_block_func);
8534 break;
8535 } else
8536 return SC_Static;
8537 }
8538 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
13
Returning without writing to 'D.Redeclaration', which participates in a condition later
8539 }
8540
8541 // No explicit storage class has already been returned
8542 return SC_None;
8543}
8544
8545static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8546 DeclContext *DC, QualType &R,
8547 TypeSourceInfo *TInfo,
8548 StorageClass SC,
8549 bool &IsVirtualOkay) {
8550 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
19
Calling 'Sema::GetNameForDeclarator'
21
Returning from 'Sema::GetNameForDeclarator'
8551 DeclarationName Name = NameInfo.getName();
8552
8553 FunctionDecl *NewFD = nullptr;
8554 bool isInline = D.getDeclSpec().isInlineSpecified();
8555
8556 if (!SemaRef.getLangOpts().CPlusPlus) {
22
Assuming field 'CPlusPlus' is not equal to 0, which participates in a condition later
23
Taking false branch
8557 // Determine whether the function was written with a
8558 // prototype. This true when:
8559 // - there is a prototype in the declarator, or
8560 // - the type R of the function is some kind of typedef or other non-
8561 // attributed reference to a type name (which eventually refers to a
8562 // function type).
8563 bool HasPrototype =
8564 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8565 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8566
8567 NewFD = FunctionDecl::Create(
8568 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8569 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8570 ConstexprSpecKind::Unspecified,
8571 /*TrailingRequiresClause=*/nullptr);
8572 if (D.isInvalidType())
8573 NewFD->setInvalidDecl();
8574
8575 return NewFD;
8576 }
8577
8578 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8579
8580 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8581 if (ConstexprKind == ConstexprSpecKind::Constinit) {
24
Assuming 'ConstexprKind' is not equal to Constinit
25
Taking false branch
8582 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8583 diag::err_constexpr_wrong_decl_kind)
8584 << static_cast<int>(ConstexprKind);
8585 ConstexprKind = ConstexprSpecKind::Unspecified;
8586 D.getMutableDeclSpec().ClearConstexprSpec();
8587 }
8588 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8589
8590 // Check that the return type is not an abstract class type.
8591 // For record types, this is done by the AbstractClassUsageDiagnoser once
8592 // the class has been completely parsed.
8593 if (!DC->isRecord() &&
27
Assuming the condition is false
28
Taking false branch
8594 SemaRef.RequireNonAbstractType(
8595 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
26
The object is a 'FunctionType'
8596 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8597 D.setInvalidType();
8598
8599 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
29
Taking false branch
8600 // This is a C++ constructor declaration.
8601 assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8602, __extension__ __PRETTY_FUNCTION__))
8602 "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8602, __extension__ __PRETTY_FUNCTION__))
;
8603
8604 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8605 return CXXConstructorDecl::Create(
8606 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8607 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8608 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8609 InheritedConstructor(), TrailingRequiresClause);
8610
8611 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
30
Taking false branch
8612 // This is a C++ destructor declaration.
8613 if (DC->isRecord()) {
8614 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8615 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8616 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8617 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8618 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8619 /*isImplicitlyDeclared=*/false, ConstexprKind,
8620 TrailingRequiresClause);
8621
8622 // If the destructor needs an implicit exception specification, set it
8623 // now. FIXME: It'd be nice to be able to create the right type to start
8624 // with, but the type needs to reference the destructor declaration.
8625 if (SemaRef.getLangOpts().CPlusPlus11)
8626 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8627
8628 IsVirtualOkay = true;
8629 return NewDD;
8630
8631 } else {
8632 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8633 D.setInvalidType();
8634
8635 // Create a FunctionDecl to satisfy the function definition parsing
8636 // code path.
8637 return FunctionDecl::Create(
8638 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8639 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8640 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8641 }
8642
8643 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
31
Taking false branch
8644 if (!DC->isRecord()) {
8645 SemaRef.Diag(D.getIdentifierLoc(),
8646 diag::err_conv_function_not_member);
8647 return nullptr;
8648 }
8649
8650 SemaRef.CheckConversionDeclarator(D, R, SC);
8651 if (D.isInvalidType())
8652 return nullptr;
8653
8654 IsVirtualOkay = true;
8655 return CXXConversionDecl::Create(
8656 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8657 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8658 ExplicitSpecifier, ConstexprKind, SourceLocation(),
8659 TrailingRequiresClause);
8660
8661 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
32
Assuming the condition is false
33
Taking false branch
8662 if (TrailingRequiresClause)
8663 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8664 diag::err_trailing_requires_clause_on_deduction_guide)
8665 << TrailingRequiresClause->getSourceRange();
8666 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8667
8668 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8669 ExplicitSpecifier, NameInfo, R, TInfo,
8670 D.getEndLoc());
8671 } else if (DC->isRecord()) {
34
Calling 'DeclContext::isRecord'
36
Returning from 'DeclContext::isRecord'
8672 // If the name of the function is the same as the name of the record,
8673 // then this must be an invalid constructor that has a return type.
8674 // (The parser checks for a return type and makes the declarator a
8675 // constructor if it has no return type).
8676 if (Name.getAsIdentifierInfo() &&
8677 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8678 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8679 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8680 << SourceRange(D.getIdentifierLoc());
8681 return nullptr;
8682 }
8683
8684 // This is a C++ method declaration.
8685 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8686 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8687 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8688 ConstexprKind, SourceLocation(), TrailingRequiresClause);
8689 IsVirtualOkay = !Ret->isStatic();
8690 return Ret;
8691 } else {
8692 bool isFriend =
8693 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
37
Assuming field 'CPlusPlus' is 0
8694 if (!isFriend
37.1
'isFriend' is false
37.1
'isFriend' is false
&& SemaRef.CurContext->isRecord())
38
Calling 'DeclContext::isRecord'
41
Returning from 'DeclContext::isRecord'
42
Taking false branch
8695 return nullptr;
8696
8697 // Determine whether the function was written with a
8698 // prototype. This true when:
8699 // - we're in C++ (where every function has a prototype),
8700 return FunctionDecl::Create(
43
Returning without writing to 'D.Redeclaration', which participates in a condition later
44
Returning pointer, which participates in a condition later
8701 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8702 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8703 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8704 }
8705}
8706
8707enum OpenCLParamType {
8708 ValidKernelParam,
8709 PtrPtrKernelParam,
8710 PtrKernelParam,
8711 InvalidAddrSpacePtrKernelParam,
8712 InvalidKernelParam,
8713 RecordKernelParam
8714};
8715
8716static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8717 // Size dependent types are just typedefs to normal integer types
8718 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8719 // integers other than by their names.
8720 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8721
8722 // Remove typedefs one by one until we reach a typedef
8723 // for a size dependent type.
8724 QualType DesugaredTy = Ty;
8725 do {
8726 ArrayRef<StringRef> Names(SizeTypeNames);
8727 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8728 if (Names.end() != Match)
8729 return true;
8730
8731 Ty = DesugaredTy;
8732 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8733 } while (DesugaredTy != Ty);
8734
8735 return false;
8736}
8737
8738static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8739 if (PT->isDependentType())
8740 return InvalidKernelParam;
8741
8742 if (PT->isPointerType() || PT->isReferenceType()) {
8743 QualType PointeeType = PT->getPointeeType();
8744 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8745 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8746 PointeeType.getAddressSpace() == LangAS::Default)
8747 return InvalidAddrSpacePtrKernelParam;
8748
8749 if (PointeeType->isPointerType()) {
8750 // This is a pointer to pointer parameter.
8751 // Recursively check inner type.
8752 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8753 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8754 ParamKind == InvalidKernelParam)
8755 return ParamKind;
8756
8757 return PtrPtrKernelParam;
8758 }
8759
8760 // C++ for OpenCL v1.0 s2.4:
8761 // Moreover the types used in parameters of the kernel functions must be:
8762 // Standard layout types for pointer parameters. The same applies to
8763 // reference if an implementation supports them in kernel parameters.
8764 if (S.getLangOpts().OpenCLCPlusPlus &&
8765 !S.getOpenCLOptions().isAvailableOption(
8766 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8767 !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8768 !PointeeType->isStandardLayoutType())
8769 return InvalidKernelParam;
8770
8771 return PtrKernelParam;
8772 }
8773
8774 // OpenCL v1.2 s6.9.k:
8775 // Arguments to kernel functions in a program cannot be declared with the
8776 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8777 // uintptr_t or a struct and/or union that contain fields declared to be one
8778 // of these built-in scalar types.
8779 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8780 return InvalidKernelParam;
8781
8782 if (PT->isImageType())
8783 return PtrKernelParam;
8784
8785 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8786 return InvalidKernelParam;
8787
8788 // OpenCL extension spec v1.2 s9.5:
8789 // This extension adds support for half scalar and vector types as built-in
8790 // types that can be used for arithmetic operations, conversions etc.
8791 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8792 PT->isHalfType())
8793 return InvalidKernelParam;
8794
8795 // Look into an array argument to check if it has a forbidden type.
8796 if (PT->isArrayType()) {
8797 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8798 // Call ourself to check an underlying type of an array. Since the
8799 // getPointeeOrArrayElementType returns an innermost type which is not an
8800 // array, this recursive call only happens once.
8801 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8802 }
8803
8804 // C++ for OpenCL v1.0 s2.4:
8805 // Moreover the types used in parameters of the kernel functions must be:
8806 // Trivial and standard-layout types C++17 [basic.types] (plain old data
8807 // types) for parameters passed by value;
8808 if (S.getLangOpts().OpenCLCPlusPlus &&
8809 !S.getOpenCLOptions().isAvailableOption(
8810 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8811 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8812 return InvalidKernelParam;
8813
8814 if (PT->isRecordType())
8815 return RecordKernelParam;
8816
8817 return ValidKernelParam;
8818}
8819
8820static void checkIsValidOpenCLKernelParameter(
8821 Sema &S,
8822 Declarator &D,
8823 ParmVarDecl *Param,
8824 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8825 QualType PT = Param->getType();
8826
8827 // Cache the valid types we encounter to avoid rechecking structs that are
8828 // used again
8829 if (ValidTypes.count(PT.getTypePtr()))
8830 return;
8831
8832 switch (getOpenCLKernelParameterType(S, PT)) {
8833 case PtrPtrKernelParam:
8834 // OpenCL v3.0 s6.11.a:
8835 // A kernel function argument cannot be declared as a pointer to a pointer
8836 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8837 if (S.getLangOpts().OpenCLVersion <= 120 &&
8838 !S.getLangOpts().OpenCLCPlusPlus) {
8839 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8840 D.setInvalidType();
8841 return;
8842 }
8843
8844 ValidTypes.insert(PT.getTypePtr());
8845 return;
8846
8847 case InvalidAddrSpacePtrKernelParam:
8848 // OpenCL v1.0 s6.5:
8849 // __kernel function arguments declared to be a pointer of a type can point
8850 // to one of the following address spaces only : __global, __local or
8851 // __constant.
8852 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8853 D.setInvalidType();
8854 return;
8855
8856 // OpenCL v1.2 s6.9.k:
8857 // Arguments to kernel functions in a program cannot be declared with the
8858 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8859 // uintptr_t or a struct and/or union that contain fields declared to be
8860 // one of these built-in scalar types.
8861
8862 case InvalidKernelParam:
8863 // OpenCL v1.2 s6.8 n:
8864 // A kernel function argument cannot be declared
8865 // of event_t type.
8866 // Do not diagnose half type since it is diagnosed as invalid argument
8867 // type for any function elsewhere.
8868 if (!PT->isHalfType()) {
8869 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8870
8871 // Explain what typedefs are involved.
8872 const TypedefType *Typedef = nullptr;
8873 while ((Typedef = PT->getAs<TypedefType>())) {
8874 SourceLocation Loc = Typedef->getDecl()->getLocation();
8875 // SourceLocation may be invalid for a built-in type.
8876 if (Loc.isValid())
8877 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8878 PT = Typedef->desugar();
8879 }
8880 }
8881
8882 D.setInvalidType();
8883 return;
8884
8885 case PtrKernelParam:
8886 case ValidKernelParam:
8887 ValidTypes.insert(PT.getTypePtr());
8888 return;
8889
8890 case RecordKernelParam:
8891 break;
8892 }
8893
8894 // Track nested structs we will inspect
8895 SmallVector<const Decl *, 4> VisitStack;
8896
8897 // Track where we are in the nested structs. Items will migrate from
8898 // VisitStack to HistoryStack as we do the DFS for bad field.
8899 SmallVector<const FieldDecl *, 4> HistoryStack;
8900 HistoryStack.push_back(nullptr);
8901
8902 // At this point we already handled everything except of a RecordType or
8903 // an ArrayType of a RecordType.
8904 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(static_cast <bool> ((PT->isArrayType() || PT->isRecordType
()) && "Unexpected type.") ? void (0) : __assert_fail
("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8904, __extension__ __PRETTY_FUNCTION__))
;
8905 const RecordType *RecTy =
8906 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8907 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8908
8909 VisitStack.push_back(RecTy->getDecl());
8910 assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?"
) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8910, __extension__ __PRETTY_FUNCTION__))
;
8911
8912 do {
8913 const Decl *Next = VisitStack.pop_back_val();
8914 if (!Next) {
8915 assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) :
__assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8915, __extension__ __PRETTY_FUNCTION__))
;
8916 // Found a marker, we have gone up a level
8917 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8918 ValidTypes.insert(Hist->getType().getTypePtr());
8919
8920 continue;
8921 }
8922
8923 // Adds everything except the original parameter declaration (which is not a
8924 // field itself) to the history stack.
8925 const RecordDecl *RD;
8926 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8927 HistoryStack.push_back(Field);
8928
8929 QualType FieldTy = Field->getType();
8930 // Other field types (known to be valid or invalid) are handled while we
8931 // walk around RecordDecl::fields().
8932 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(static_cast <bool> ((FieldTy->isArrayType() || FieldTy
->isRecordType()) && "Unexpected type.") ? void (0
) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8933, __extension__ __PRETTY_FUNCTION__))
8933 "Unexpected type.")(static_cast <bool> ((FieldTy->isArrayType() || FieldTy
->isRecordType()) && "Unexpected type.") ? void (0
) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 8933, __extension__ __PRETTY_FUNCTION__))
;
8934 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8935
8936 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8937 } else {
8938 RD = cast<RecordDecl>(Next);
8939 }
8940
8941 // Add a null marker so we know when we've gone back up a level
8942 VisitStack.push_back(nullptr);
8943
8944 for (const auto *FD : RD->fields()) {
8945 QualType QT = FD->getType();
8946
8947 if (ValidTypes.count(QT.getTypePtr()))
8948 continue;
8949
8950 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8951 if (ParamType == ValidKernelParam)
8952 continue;
8953
8954 if (ParamType == RecordKernelParam) {
8955 VisitStack.push_back(FD);
8956 continue;
8957 }
8958
8959 // OpenCL v1.2 s6.9.p:
8960 // Arguments to kernel functions that are declared to be a struct or union
8961 // do not allow OpenCL objects to be passed as elements of the struct or
8962 // union.
8963 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8964 ParamType == InvalidAddrSpacePtrKernelParam) {
8965 S.Diag(Param->getLocation(),
8966 diag::err_record_with_pointers_kernel_param)
8967 << PT->isUnionType()
8968 << PT;
8969 } else {
8970 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8971 }
8972
8973 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8974 << OrigRecDecl->getDeclName();
8975
8976 // We have an error, now let's go back up through history and show where
8977 // the offending field came from
8978 for (ArrayRef<const FieldDecl *>::const_iterator
8979 I = HistoryStack.begin() + 1,
8980 E = HistoryStack.end();
8981 I != E; ++I) {
8982 const FieldDecl *OuterField = *I;
8983 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8984 << OuterField->getType();
8985 }
8986
8987 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8988 << QT->isPointerType()
8989 << QT;
8990 D.setInvalidType();
8991 return;
8992 }
8993 } while (!VisitStack.empty());
8994}
8995
8996/// Find the DeclContext in which a tag is implicitly declared if we see an
8997/// elaborated type specifier in the specified context, and lookup finds
8998/// nothing.
8999static DeclContext *getTagInjectionContext(DeclContext *DC) {
9000 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9001 DC = DC->getParent();
9002 return DC;
9003}
9004
9005/// Find the Scope in which a tag is implicitly declared if we see an
9006/// elaborated type specifier in the specified context, and lookup finds
9007/// nothing.
9008static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9009 while (S->isClassScope() ||
9010 (LangOpts.CPlusPlus &&
9011 S->isFunctionPrototypeScope()) ||
9012 ((S->getFlags() & Scope::DeclScope) == 0) ||
9013 (S->getEntity() && S->getEntity()->isTransparentContext()))
9014 S = S->getParent();
9015 return S;
9016}
9017
9018NamedDecl*
9019Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9020 TypeSourceInfo *TInfo, LookupResult &Previous,
9021 MultiTemplateParamsArg TemplateParamListsRef,
9022 bool &AddToScope) {
9023 QualType R = TInfo->getType();
9024
9025 assert(R->isFunctionType())(static_cast <bool> (R->isFunctionType()) ? void (0)
: __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9025, __extension__ __PRETTY_FUNCTION__))
;
1
'?' condition is true
9026 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
2
The object is a 'FunctionType'
3
Assuming the condition is false
4
Taking false branch
9027 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9028
9029 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9030 for (TemplateParameterList *TPL : TemplateParamListsRef)
5
Assuming '__begin1' is equal to '__end1'
9031 TemplateParamLists.push_back(TPL);
9032 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
6
Assuming 'Invented' is null
7
Taking false branch
9033 if (!TemplateParamLists.empty() &&
9034 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9035 TemplateParamLists.back() = Invented;
9036 else
9037 TemplateParamLists.push_back(Invented);
9038 }
9039
9040 // TODO: consider using NameInfo for diagnostic.
9041 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8
Calling 'Sema::GetNameForDeclarator'
10
Returning from 'Sema::GetNameForDeclarator'
9042 DeclarationName Name = NameInfo.getName();
9043 StorageClass SC = getFunctionStorageClass(*this, D);
11
Calling 'getFunctionStorageClass'
14
Returning from 'getFunctionStorageClass'
9044
9045 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15
Assuming 'TSCS' is 0
16
Taking false branch
9046 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9047 diag::err_invalid_thread)
9048 << DeclSpec::getSpecifierName(TSCS);
9049
9050 if (D.isFirstDeclarationOfMember())
17
Taking false branch
9051 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9052 D.getIdentifierLoc());
9053
9054 bool isFriend = false;
9055 FunctionTemplateDecl *FunctionTemplate = nullptr;
9056 bool isMemberSpecialization = false;
9057 bool isFunctionTemplateSpecialization = false;
9058
9059 bool isDependentClassScopeExplicitSpecialization = false;
9060 bool HasExplicitTemplateArgs = false;
9061 TemplateArgumentListInfo TemplateArgs;
9062
9063 bool isVirtualOkay = false;
9064
9065 DeclContext *OriginalDC = DC;
9066 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9067
9068 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
18
Calling 'CreateNewFunctionDecl'
45
Returning from 'CreateNewFunctionDecl'
9069 isVirtualOkay);
9070 if (!NewFD) return nullptr;
46
Assuming 'NewFD' is non-null
9071
9072 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
47
Assuming field 'OriginalLexicalContext' is null
9073 NewFD->setTopLevelDeclInObjCContainer();
9074
9075 // Set the lexical context. If this is a function-scope declaration, or has a
9076 // C++ scope specifier, or is the object of a friend declaration, the lexical
9077 // context will be different from the semantic context.
9078 NewFD->setLexicalDeclContext(CurContext);
9079
9080 if (IsLocalExternDecl
47.1
'IsLocalExternDecl' is false
47.1
'IsLocalExternDecl' is false
)
48
Taking false branch
9081 NewFD->setLocalExternDecl();
9082
9083 if (getLangOpts().CPlusPlus
48.1
Field 'CPlusPlus' is 0
48.1
Field 'CPlusPlus' is 0
) {
49
Taking false branch
9084 bool isInline = D.getDeclSpec().isInlineSpecified();
9085 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9086 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9087 isFriend = D.getDeclSpec().isFriendSpecified();
9088 if (isFriend && !isInline && D.isFunctionDefinition()) {
9089 // C++ [class.friend]p5
9090 // A function can be defined in a friend declaration of a
9091 // class . . . . Such a function is implicitly inline.
9092 NewFD->setImplicitlyInline();
9093 }
9094
9095 // If this is a method defined in an __interface, and is not a constructor
9096 // or an overloaded operator, then set the pure flag (isVirtual will already
9097 // return true).
9098 if (const CXXRecordDecl *Parent =
9099 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9100 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9101 NewFD->setPure(true);
9102
9103 // C++ [class.union]p2
9104 // A union can have member functions, but not virtual functions.
9105 if (isVirtual && Parent->isUnion())
9106 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9107 }
9108
9109 SetNestedNameSpecifier(*this, NewFD, D);
9110 isMemberSpecialization = false;
9111 isFunctionTemplateSpecialization = false;
9112 if (D.isInvalidType())
9113 NewFD->setInvalidDecl();
9114
9115 // Match up the template parameter lists with the scope specifier, then
9116 // determine whether we have a template or a template specialization.
9117 bool Invalid = false;
9118 TemplateParameterList *TemplateParams =
9119 MatchTemplateParametersToScopeSpecifier(
9120 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9121 D.getCXXScopeSpec(),
9122 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9123 ? D.getName().TemplateId
9124 : nullptr,
9125 TemplateParamLists, isFriend, isMemberSpecialization,
9126 Invalid);
9127 if (TemplateParams) {
9128 // Check that we can declare a template here.
9129 if (CheckTemplateDeclScope(S, TemplateParams))
9130 NewFD->setInvalidDecl();
9131
9132 if (TemplateParams->size() > 0) {
9133 // This is a function template
9134
9135 // A destructor cannot be a template.
9136 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9137 Diag(NewFD->getLocation(), diag::err_destructor_template);
9138 NewFD->setInvalidDecl();
9139 }
9140
9141 // If we're adding a template to a dependent context, we may need to
9142 // rebuilding some of the types used within the template parameter list,
9143 // now that we know what the current instantiation is.
9144 if (DC->isDependentContext()) {
9145 ContextRAII SavedContext(*this, DC);
9146 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9147 Invalid = true;
9148 }
9149
9150 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9151 NewFD->getLocation(),
9152 Name, TemplateParams,
9153 NewFD);
9154 FunctionTemplate->setLexicalDeclContext(CurContext);
9155 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9156
9157 // For source fidelity, store the other template param lists.
9158 if (TemplateParamLists.size() > 1) {
9159 NewFD->setTemplateParameterListsInfo(Context,
9160 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9161 .drop_back(1));
9162 }
9163 } else {
9164 // This is a function template specialization.
9165 isFunctionTemplateSpecialization = true;
9166 // For source fidelity, store all the template param lists.
9167 if (TemplateParamLists.size() > 0)
9168 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9169
9170 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9171 if (isFriend) {
9172 // We want to remove the "template<>", found here.
9173 SourceRange RemoveRange = TemplateParams->getSourceRange();
9174
9175 // If we remove the template<> and the name is not a
9176 // template-id, we're actually silently creating a problem:
9177 // the friend declaration will refer to an untemplated decl,
9178 // and clearly the user wants a template specialization. So
9179 // we need to insert '<>' after the name.
9180 SourceLocation InsertLoc;
9181 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9182 InsertLoc = D.getName().getSourceRange().getEnd();
9183 InsertLoc = getLocForEndOfToken(InsertLoc);
9184 }
9185
9186 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9187 << Name << RemoveRange
9188 << FixItHint::CreateRemoval(RemoveRange)
9189 << FixItHint::CreateInsertion(InsertLoc, "<>");
9190 }
9191 }
9192 } else {
9193 // Check that we can declare a template here.
9194 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9195 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9196 NewFD->setInvalidDecl();
9197
9198 // All template param lists were matched against the scope specifier:
9199 // this is NOT (an explicit specialization of) a template.
9200 if (TemplateParamLists.size() > 0)
9201 // For source fidelity, store all the template param lists.
9202 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9203 }
9204
9205 if (Invalid) {
9206 NewFD->setInvalidDecl();
9207 if (FunctionTemplate)
9208 FunctionTemplate->setInvalidDecl();
9209 }
9210
9211 // C++ [dcl.fct.spec]p5:
9212 // The virtual specifier shall only be used in declarations of
9213 // nonstatic class member functions that appear within a
9214 // member-specification of a class declaration; see 10.3.
9215 //
9216 if (isVirtual && !NewFD->isInvalidDecl()) {
9217 if (!isVirtualOkay) {
9218 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9219 diag::err_virtual_non_function);
9220 } else if (!CurContext->isRecord()) {
9221 // 'virtual' was specified outside of the class.
9222 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9223 diag::err_virtual_out_of_class)
9224 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9225 } else if (NewFD->getDescribedFunctionTemplate()) {
9226 // C++ [temp.mem]p3:
9227 // A member function template shall not be virtual.
9228 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9229 diag::err_virtual_member_function_template)
9230 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9231 } else {
9232 // Okay: Add virtual to the method.
9233 NewFD->setVirtualAsWritten(true);
9234 }
9235
9236 if (getLangOpts().CPlusPlus14 &&
9237 NewFD->getReturnType()->isUndeducedType())
9238 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9239 }
9240
9241 if (getLangOpts().CPlusPlus14 &&
9242 (NewFD->isDependentContext() ||
9243 (isFriend && CurContext->isDependentContext())) &&
9244 NewFD->getReturnType()->isUndeducedType()) {
9245 // If the function template is referenced directly (for instance, as a
9246 // member of the current instantiation), pretend it has a dependent type.
9247 // This is not really justified by the standard, but is the only sane
9248 // thing to do.
9249 // FIXME: For a friend function, we have not marked the function as being
9250 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9251 const FunctionProtoType *FPT =
9252 NewFD->getType()->castAs<FunctionProtoType>();
9253 QualType Result =
9254 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9255 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9256 FPT->getExtProtoInfo()));
9257 }
9258
9259 // C++ [dcl.fct.spec]p3:
9260 // The inline specifier shall not appear on a block scope function
9261 // declaration.
9262 if (isInline && !NewFD->isInvalidDecl()) {
9263 if (CurContext->isFunctionOrMethod()) {
9264 // 'inline' is not allowed on block scope function declaration.
9265 Diag(D.getDeclSpec().getInlineSpecLoc(),
9266 diag::err_inline_declaration_block_scope) << Name
9267 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9268 }
9269 }
9270
9271 // C++ [dcl.fct.spec]p6:
9272 // The explicit specifier shall be used only in the declaration of a
9273 // constructor or conversion function within its class definition;
9274 // see 12.3.1 and 12.3.2.
9275 if (hasExplicit && !NewFD->isInvalidDecl() &&
9276 !isa<CXXDeductionGuideDecl>(NewFD)) {
9277 if (!CurContext->isRecord()) {
9278 // 'explicit' was specified outside of the class.
9279 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9280 diag::err_explicit_out_of_class)
9281 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9282 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9283 !isa<CXXConversionDecl>(NewFD)) {
9284 // 'explicit' was specified on a function that wasn't a constructor
9285 // or conversion function.
9286 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9287 diag::err_explicit_non_ctor_or_conv_function)
9288 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9289 }
9290 }
9291
9292 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9293 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9294 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9295 // are implicitly inline.
9296 NewFD->setImplicitlyInline();
9297
9298 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9299 // be either constructors or to return a literal type. Therefore,
9300 // destructors cannot be declared constexpr.
9301 if (isa<CXXDestructorDecl>(NewFD) &&
9302 (!getLangOpts().CPlusPlus20 ||
9303 ConstexprKind == ConstexprSpecKind::Consteval)) {
9304 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9305 << static_cast<int>(ConstexprKind);
9306 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9307 ? ConstexprSpecKind::Unspecified
9308 : ConstexprSpecKind::Constexpr);
9309 }
9310 // C++20 [dcl.constexpr]p2: An allocation function, or a
9311 // deallocation function shall not be declared with the consteval
9312 // specifier.
9313 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9314 (NewFD->getOverloadedOperator() == OO_New ||
9315 NewFD->getOverloadedOperator() == OO_Array_New ||
9316 NewFD->getOverloadedOperator() == OO_Delete ||
9317 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9318 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9319 diag::err_invalid_consteval_decl_kind)
9320 << NewFD;
9321 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9322 }
9323 }
9324
9325 // If __module_private__ was specified, mark the function accordingly.
9326 if (D.getDeclSpec().isModulePrivateSpecified()) {
9327 if (isFunctionTemplateSpecialization) {
9328 SourceLocation ModulePrivateLoc
9329 = D.getDeclSpec().getModulePrivateSpecLoc();
9330 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9331 << 0
9332 << FixItHint::CreateRemoval(ModulePrivateLoc);
9333 } else {
9334 NewFD->setModulePrivate();
9335 if (FunctionTemplate)
9336 FunctionTemplate->setModulePrivate();
9337 }
9338 }
9339
9340 if (isFriend) {
9341 if (FunctionTemplate) {
9342 FunctionTemplate->setObjectOfFriendDecl();
9343 FunctionTemplate->setAccess(AS_public);
9344 }
9345 NewFD->setObjectOfFriendDecl();
9346 NewFD->setAccess(AS_public);
9347 }
9348
9349 // If a function is defined as defaulted or deleted, mark it as such now.
9350 // We'll do the relevant checks on defaulted / deleted functions later.
9351 switch (D.getFunctionDefinitionKind()) {
9352 case FunctionDefinitionKind::Declaration:
9353 case FunctionDefinitionKind::Definition:
9354 break;
9355
9356 case FunctionDefinitionKind::Defaulted:
9357 NewFD->setDefaulted();
9358 break;
9359
9360 case FunctionDefinitionKind::Deleted:
9361 NewFD->setDeletedAsWritten();
9362 break;
9363 }
9364
9365 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9366 D.isFunctionDefinition()) {
9367 // C++ [class.mfct]p2:
9368 // A member function may be defined (8.4) in its class definition, in
9369 // which case it is an inline member function (7.1.2)
9370 NewFD->setImplicitlyInline();
9371 }
9372
9373 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9374 !CurContext->isRecord()) {
9375 // C++ [class.static]p1:
9376 // A data or function member of a class may be declared static
9377 // in a class definition, in which case it is a static member of
9378 // the class.
9379
9380 // Complain about the 'static' specifier if it's on an out-of-line
9381 // member function definition.
9382
9383 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9384 // member function template declaration and class member template
9385 // declaration (MSVC versions before 2015), warn about this.
9386 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9387 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9388 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9389 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9390 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9391 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9392 }
9393
9394 // C++11 [except.spec]p15:
9395 // A deallocation function with no exception-specification is treated
9396 // as if it were specified with noexcept(true).
9397 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9398 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9399 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9400 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9401 NewFD->setType(Context.getFunctionType(
9402 FPT->getReturnType(), FPT->getParamTypes(),
9403 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9404 }
9405
9406 // Filter out previous declarations that don't match the scope.
9407 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9408 D.getCXXScopeSpec().isNotEmpty() ||
9409 isMemberSpecialization ||
9410 isFunctionTemplateSpecialization);
9411
9412 // Handle GNU asm-label extension (encoded as an attribute).
9413 if (Expr *E = (Expr*) D.getAsmLabel()) {
50
Assuming 'E' is null
51
Taking false branch
9414 // The parser guarantees this is a string.
9415 StringLiteral *SE = cast<StringLiteral>(E);
9416 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9417 /*IsLiteralLabel=*/true,
9418 SE->getStrTokenLoc(0)));
9419 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
52
Assuming the condition is false
53
Taking false branch
9420 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9421 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9422 if (I != ExtnameUndeclaredIdentifiers.end()) {
9423 if (isDeclExternC(NewFD)) {
9424 NewFD->addAttr(I->second);
9425 ExtnameUndeclaredIdentifiers.erase(I);
9426 } else
9427 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9428 << /*Variable*/0 << NewFD;
9429 }
9430 }
9431
9432 // Copy the parameter declarations from the declarator D to the function
9433 // declaration NewFD, if they are available. First scavenge them into Params.
9434 SmallVector<ParmVarDecl*, 16> Params;
9435 unsigned FTIIdx;
9436 if (D.isFunctionDeclarator(FTIIdx)) {
54
Assuming the condition is false
55
Taking false branch
9437 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9438
9439 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9440 // function that takes no arguments, not a function that takes a
9441 // single void argument.
9442 // We let through "const void" here because Sema::GetTypeForDeclarator
9443 // already checks for that case.
9444 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9445 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9446 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9447 assert(Param->getDeclContext() != NewFD && "Was set before ?")(static_cast <bool> (Param->getDeclContext() != NewFD
&& "Was set before ?") ? void (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9447, __extension__ __PRETTY_FUNCTION__))
;
9448 Param->setDeclContext(NewFD);
9449 Params.push_back(Param);
9450
9451 if (Param->isInvalidDecl())
9452 NewFD->setInvalidDecl();
9453 }
9454 }
9455
9456 if (!getLangOpts().CPlusPlus) {
9457 // In C, find all the tag declarations from the prototype and move them
9458 // into the function DeclContext. Remove them from the surrounding tag
9459 // injection context of the function, which is typically but not always
9460 // the TU.
9461 DeclContext *PrototypeTagContext =
9462 getTagInjectionContext(NewFD->getLexicalDeclContext());
9463 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9464 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9465
9466 // We don't want to reparent enumerators. Look at their parent enum
9467 // instead.
9468 if (!TD) {
9469 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9470 TD = cast<EnumDecl>(ECD->getDeclContext());
9471 }
9472 if (!TD)
9473 continue;
9474 DeclContext *TagDC = TD->getLexicalDeclContext();
9475 if (!TagDC->containsDecl(TD))
9476 continue;
9477 TagDC->removeDecl(TD);
9478 TD->setDeclContext(NewFD);
9479 NewFD->addDecl(TD);
9480
9481 // Preserve the lexical DeclContext if it is not the surrounding tag
9482 // injection context of the FD. In this example, the semantic context of
9483 // E will be f and the lexical context will be S, while both the
9484 // semantic and lexical contexts of S will be f:
9485 // void f(struct S { enum E { a } f; } s);
9486 if (TagDC != PrototypeTagContext)
9487 TD->setLexicalDeclContext(TagDC);
9488 }
9489 }
9490 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
56
Assuming the object is a 'FunctionProtoType'
57
Assuming 'FT' is non-null
58
Taking true branch
9491 // When we're declaring a function with a typedef, typeof, etc as in the
9492 // following example, we'll need to synthesize (unnamed)
9493 // parameters for use in the declaration.
9494 //
9495 // @code
9496 // typedef void fn(int);
9497 // fn f;
9498 // @endcode
9499
9500 // Synthesize a parameter for each argument type.
9501 for (const auto &AI : FT->param_types()) {
59
Assuming '__begin3' is equal to '__end3'
9502 ParmVarDecl *Param =
9503 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9504 Param->setScopeInfo(0, Params.size());
9505 Params.push_back(Param);
9506 }
9507 } else {
9508 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&(static_cast <bool> (R->isFunctionNoProtoType() &&
NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn"
) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9509, __extension__ __PRETTY_FUNCTION__))
9509 "Should not need args for typedef of non-prototype fn")(static_cast <bool> (R->isFunctionNoProtoType() &&
NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn"
) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9509, __extension__ __PRETTY_FUNCTION__))
;
9510 }
9511
9512 // Finally, we know we have the right number of parameters, install them.
9513 NewFD->setParams(Params);
9514
9515 if (D.getDeclSpec().isNoreturnSpecified())
60
Assuming the condition is false
9516 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9517 D.getDeclSpec().getNoreturnSpecLoc(),
9518 AttributeCommonInfo::AS_Keyword));
9519
9520 // Functions returning a variably modified type violate C99 6.7.5.2p2
9521 // because all functions have linkage.
9522 if (!NewFD->isInvalidDecl() &&
61
Assuming the condition is false
9523 NewFD->getReturnType()->isVariablyModifiedType()) {
9524 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9525 NewFD->setInvalidDecl();
9526 }
9527
9528 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9529 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
62
Assuming field 'Valid' is false
9530 !NewFD->hasAttr<SectionAttr>())
9531 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9532 Context, PragmaClangTextSection.SectionName,
9533 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9534
9535 // Apply an implicit SectionAttr if #pragma code_seg is active.
9536 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
63
Assuming field 'CurrentValue' is null
9537 !NewFD->hasAttr<SectionAttr>()) {
9538 NewFD->addAttr(SectionAttr::CreateImplicit(
9539 Context, CodeSegStack.CurrentValue->getString(),
9540 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9541 SectionAttr::Declspec_allocate));
9542 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9543 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9544 ASTContext::PSF_Read,
9545 NewFD))
9546 NewFD->dropAttr<SectionAttr>();
9547 }
9548
9549 // Apply an implicit CodeSegAttr from class declspec or
9550 // apply an implicit SectionAttr from #pragma code_seg if active.
9551 if (!NewFD->hasAttr<CodeSegAttr>()) {
64
Taking true branch
9552 if (Attr *SAttr
64.1
'SAttr' is null
64.1
'SAttr' is null
= getImplicitCodeSegOrSectionAttrForFunction(NewFD,
65
Taking false branch
9553 D.isFunctionDefinition())) {
9554 NewFD->addAttr(SAttr);
9555 }
9556 }
9557
9558 // Handle attributes.
9559 ProcessDeclAttributes(S, NewFD, D);
9560
9561 if (getLangOpts().OpenCL) {
66
Assuming field 'OpenCL' is 0
9562 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9563 // type declaration will generate a compilation error.
9564 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9565 if (AddressSpace != LangAS::Default) {
9566 Diag(NewFD->getLocation(),
9567 diag::err_opencl_return_value_with_address_space);
9568 NewFD->setInvalidDecl();
9569 }
9570 }
9571
9572 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
67
Assuming field 'SYCLIsDevice' is 0
68
Assuming field 'OpenMP' is 0
9573 checkDeviceDecl(NewFD, D.getBeginLoc());
9574
9575 if (!getLangOpts().CPlusPlus) {
69
Assuming field 'CPlusPlus' is not equal to 0
9576 // Perform semantic checking on the function declaration.
9577 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9578 CheckMain(NewFD, D.getDeclSpec());
9579
9580 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9581 CheckMSVCRTEntryPoint(NewFD);
9582
9583 if (!NewFD->isInvalidDecl())
9584 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9585 isMemberSpecialization));
9586 else if (!Previous.empty())
9587 // Recover gracefully from an invalid redeclaration.
9588 D.setRedeclaration(true);
9589 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9591, __extension__ __PRETTY_FUNCTION__))
9590 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9591, __extension__ __PRETTY_FUNCTION__))
9591 "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9591, __extension__ __PRETTY_FUNCTION__))
;
9592
9593 // Diagnose no-prototype function declarations with calling conventions that
9594 // don't support variadic calls. Only do this in C and do it after merging
9595 // possibly prototyped redeclarations.
9596 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9597 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9598 CallingConv CC = FT->getExtInfo().getCC();
9599 if (!supportsVariadicCall(CC)) {
9600 // Windows system headers sometimes accidentally use stdcall without
9601 // (void) parameters, so we relax this to a warning.
9602 int DiagID =
9603 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9604 Diag(NewFD->getLocation(), DiagID)
9605 << FunctionType::getNameForCallConv(CC);
9606 }
9607 }
9608
9609 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9610 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9611 checkNonTrivialCUnion(NewFD->getReturnType(),
9612 NewFD->getReturnTypeSourceRange().getBegin(),
9613 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9614 } else {
9615 // C++11 [replacement.functions]p3:
9616 // The program's definitions shall not be specified as inline.
9617 //
9618 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9619 //
9620 // Suppress the diagnostic if the function is __attribute__((used)), since
9621 // that forces an external definition to be emitted.
9622 if (D.getDeclSpec().isInlineSpecified() &&
70
Assuming the condition is false
9623 NewFD->isReplaceableGlobalAllocationFunction() &&
9624 !NewFD->hasAttr<UsedAttr>())
9625 Diag(D.getDeclSpec().getInlineSpecLoc(),
9626 diag::ext_operator_new_delete_declared_inline)
9627 << NewFD->getDeclName();
9628
9629 // If the declarator is a template-id, translate the parser's template
9630 // argument list into our AST format.
9631 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
71
Assuming the condition is false
9632 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9633 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9634 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9635 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9636 TemplateId->NumArgs);
9637 translateTemplateArguments(TemplateArgsPtr,
9638 TemplateArgs);
9639
9640 HasExplicitTemplateArgs = true;
9641
9642 if (NewFD->isInvalidDecl()) {
9643 HasExplicitTemplateArgs = false;
9644 } else if (FunctionTemplate) {
9645 // Function template with explicit template arguments.
9646 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9647 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9648
9649 HasExplicitTemplateArgs = false;
9650 } else {
9651 assert((isFunctionTemplateSpecialization ||(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9653, __extension__ __PRETTY_FUNCTION__))
9652 D.getDeclSpec().isFriendSpecified()) &&(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9653, __extension__ __PRETTY_FUNCTION__))
9653 "should have a 'template<>' for this decl")(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9653, __extension__ __PRETTY_FUNCTION__))
;
9654 // "friend void foo<>(int);" is an implicit specialization decl.
9655 isFunctionTemplateSpecialization = true;
9656 }
9657 } else if (isFriend
71.1
'isFriend' is false
71.1
'isFriend' is false
&& isFunctionTemplateSpecialization) {
9658 // This combination is only possible in a recovery case; the user
9659 // wrote something like:
9660 // template <> friend void foo(int);
9661 // which we're recovering from as if the user had written:
9662 // friend void foo<>(int);
9663 // Go ahead and fake up a template id.
9664 HasExplicitTemplateArgs = true;
9665 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9666 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9667 }
9668
9669 // We do not add HD attributes to specializations here because
9670 // they may have different constexpr-ness compared to their
9671 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9672 // may end up with different effective targets. Instead, a
9673 // specialization inherits its target attributes from its template
9674 // in the CheckFunctionTemplateSpecialization() call below.
9675 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
72
Assuming field 'CUDA' is 0
9676 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9677
9678 // If it's a friend (and only if it's a friend), it's possible
9679 // that either the specialized function type or the specialized
9680 // template is dependent, and therefore matching will fail. In
9681 // this case, don't check the specialization yet.
9682 if (isFunctionTemplateSpecialization
72.1
'isFunctionTemplateSpecialization' is false
72.1
'isFunctionTemplateSpecialization' is false
&& isFriend &&
73
Taking false branch
9683 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9684 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9685 TemplateArgs.arguments()))) {
9686 assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9687, __extension__ __PRETTY_FUNCTION__))
9687 "friend function specialization without template args")(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9687, __extension__ __PRETTY_FUNCTION__))
;
9688 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9689 Previous))
9690 NewFD->setInvalidDecl();
9691 } else if (isFunctionTemplateSpecialization
73.1
'isFunctionTemplateSpecialization' is false
73.1
'isFunctionTemplateSpecialization' is false
) {
9692 if (CurContext->isDependentContext() && CurContext->isRecord()
9693 && !isFriend) {
9694 isDependentClassScopeExplicitSpecialization = true;
9695 } else if (!NewFD->isInvalidDecl() &&
9696 CheckFunctionTemplateSpecialization(
9697 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9698 Previous))
9699 NewFD->setInvalidDecl();
9700
9701 // C++ [dcl.stc]p1:
9702 // A storage-class-specifier shall not be specified in an explicit
9703 // specialization (14.7.3)
9704 FunctionTemplateSpecializationInfo *Info =
9705 NewFD->getTemplateSpecializationInfo();
9706 if (Info && SC != SC_None) {
9707 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9708 Diag(NewFD->getLocation(),
9709 diag::err_explicit_specialization_inconsistent_storage_class)
9710 << SC
9711 << FixItHint::CreateRemoval(
9712 D.getDeclSpec().getStorageClassSpecLoc());
9713
9714 else
9715 Diag(NewFD->getLocation(),
9716 diag::ext_explicit_specialization_storage_class)
9717 << FixItHint::CreateRemoval(
9718 D.getDeclSpec().getStorageClassSpecLoc());
9719 }
9720 } else if (isMemberSpecialization
73.2
'isMemberSpecialization' is false
73.2
'isMemberSpecialization' is false
&& isa<CXXMethodDecl>(NewFD)) {
9721 if (CheckMemberSpecialization(NewFD, Previous))
9722 NewFD->setInvalidDecl();
9723 }
9724
9725 // Perform semantic checking on the function declaration.
9726 if (!isDependentClassScopeExplicitSpecialization
73.3
'isDependentClassScopeExplicitSpecialization' is false
73.3
'isDependentClassScopeExplicitSpecialization' is false
) {
9727 if (!NewFD->isInvalidDecl() && NewFD->isMain())
74
Assuming the condition is false
9728 CheckMain(NewFD, D.getDeclSpec());
9729
9730 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9731 CheckMSVCRTEntryPoint(NewFD);
9732
9733 if (!NewFD->isInvalidDecl())
75
Taking false branch
9734 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9735 isMemberSpecialization));
9736 else if (!Previous.empty())
76
Assuming the condition is false
9737 // Recover gracefully from an invalid redeclaration.
9738 D.setRedeclaration(true);
9739 }
9740
9741 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9743, __extension__ __PRETTY_FUNCTION__))
77
Taking false branch
78
'?' condition is true
9742 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9743, __extension__ __PRETTY_FUNCTION__))
9743 "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 9743, __extension__ __PRETTY_FUNCTION__))
;
9744
9745 NamedDecl *PrincipalDecl = (FunctionTemplate
78.1
'FunctionTemplate' is null
78.1
'FunctionTemplate' is null
79
'?' condition is false
9746 ? cast<NamedDecl>(FunctionTemplate) 9747 : NewFD); 9748 9749 if (isFriend
79.1
'isFriend' is false
79.1
'isFriend' is false
&& NewFD->getPreviousDecl()) { 9750 AccessSpecifier Access = AS_public; 9751 if (!NewFD->isInvalidDecl()) 9752 Access = NewFD->getPreviousDecl()->getAccess(); 9753 9754 NewFD->setAccess(Access); 9755 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9756 } 9757 9758 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9759 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9760 PrincipalDecl->setNonMemberOperator(); 9761 9762 // If we have a function template, check the template parameter 9763 // list. This will check and merge default template arguments. 9764 if (FunctionTemplate
79.2
'FunctionTemplate' is null
79.2
'FunctionTemplate' is null
) {
80
Taking false branch
9765 FunctionTemplateDecl *PrevTemplate = 9766 FunctionTemplate->getPreviousDecl(); 9767 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9768 PrevTemplate ? PrevTemplate->getTemplateParameters() 9769 : nullptr, 9770 D.getDeclSpec().isFriendSpecified() 9771 ? (D.isFunctionDefinition() 9772 ? TPC_FriendFunctionTemplateDefinition 9773 : TPC_FriendFunctionTemplate) 9774 : (D.getCXXScopeSpec().isSet() && 9775 DC && DC->isRecord() && 9776 DC->isDependentContext()) 9777 ? TPC_ClassTemplateMember 9778 : TPC_FunctionTemplate); 9779 } 9780 9781 if (NewFD->isInvalidDecl()) {
81
Assuming the condition is false
82
Taking false branch
9782 // Ignore all the rest of this. 9783 } else if (!D.isRedeclaration()) {
83
Assuming the condition is false
9784 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9785 AddToScope }; 9786 // Fake up an access specifier if it's supposed to be a class member. 9787 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9788 NewFD->setAccess(AS_public); 9789 9790 // Qualified decls generally require a previous declaration. 9791 if (D.getCXXScopeSpec().isSet()) { 9792 // ...with the major exception of templated-scope or 9793 // dependent-scope friend declarations. 9794 9795 // TODO: we currently also suppress this check in dependent 9796 // contexts because (1) the parameter depth will be off when 9797 // matching friend templates and (2) we might actually be 9798 // selecting a friend based on a dependent factor. But there 9799 // are situations where these conditions don't apply and we 9800 // can actually do this check immediately. 9801 // 9802 // Unless the scope is dependent, it's always an error if qualified 9803 // redeclaration lookup found nothing at all. Diagnose that now; 9804 // nothing will diagnose that error later. 9805 if (isFriend && 9806 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9807 (!Previous.empty() && CurContext->isDependentContext()))) { 9808 // ignore these 9809 } else if (NewFD->isCPUDispatchMultiVersion() || 9810 NewFD->isCPUSpecificMultiVersion()) { 9811 // ignore this, we allow the redeclaration behavior here to create new 9812 // versions of the function. 9813 } else { 9814 // The user tried to provide an out-of-line definition for a 9815 // function that is a member of a class or namespace, but there 9816 // was no such member function declared (C++ [class.mfct]p2, 9817 // C++ [namespace.memdef]p2). For example: 9818 // 9819 // class X { 9820 // void f() const; 9821 // }; 9822 // 9823 // void X::f() { } // ill-formed 9824 // 9825 // Complain about this problem, and attempt to suggest close 9826 // matches (e.g., those that differ only in cv-qualifiers and 9827 // whether the parameter types are references). 9828 9829 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9830 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9831 AddToScope = ExtraArgs.AddToScope; 9832 return Result; 9833 } 9834 } 9835 9836 // Unqualified local friend declarations are required to resolve 9837 // to something. 9838 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9839 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9840 *this, Previous, NewFD, ExtraArgs, true, S)) { 9841 AddToScope = ExtraArgs.AddToScope; 9842 return Result; 9843 } 9844 } 9845 } else if (!D.isFunctionDefinition() && 9846 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
84
'NewFD' is not a 'CXXMethodDecl'
9847 !isFriend && !isFunctionTemplateSpecialization && 9848 !isMemberSpecialization) { 9849 // An out-of-line member function declaration must also be a 9850 // definition (C++ [class.mfct]p2). 9851 // Note that this is not the case for explicit specializations of 9852 // function templates or member functions of class templates, per 9853 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9854 // extension for compatibility with old SWIG code which likes to 9855 // generate them. 9856 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9857 << D.getCXXScopeSpec().getRange(); 9858 } 9859 } 9860 9861 // If this is the first declaration of a library builtin function, add 9862 // attributes as appropriate. 9863 if (!D.isRedeclaration() && 9864 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9865 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9866 if (unsigned BuiltinID = II->getBuiltinID()) { 9867 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9868 // Validate the type matches unless this builtin is specified as 9869 // matching regardless of its declared type. 9870 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9871 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9872 } else { 9873 ASTContext::GetBuiltinTypeError Error; 9874 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9875 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9876 9877 if (!Error && !BuiltinType.isNull() && 9878 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9879 NewFD->getType(), BuiltinType)) 9880 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9881 } 9882 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9883 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9884 // FIXME: We should consider this a builtin only in the std namespace. 9885 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9886 } 9887 } 9888 } 9889 } 9890 9891 ProcessPragmaWeak(S, NewFD); 9892 checkAttributesAfterMerging(*this, *NewFD); 9893 9894 AddKnownFunctionAttributes(NewFD); 9895 9896 if (NewFD->hasAttr<OverloadableAttr>() &&
86
Taking true branch
9897 !NewFD->getType()->getAs<FunctionProtoType>()) {
85
Assuming the object is not a 'FunctionProtoType'
9898 Diag(NewFD->getLocation(), 9899 diag::err_attribute_overloadable_no_prototype) 9900 << NewFD; 9901 9902 // Turn this into a variadic function with no parameters. 9903 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
87
Assuming the object is not a 'FunctionType'
88
'FT' initialized to a null pointer value
9904 FunctionProtoType::ExtProtoInfo EPI( 9905 Context.getDefaultCallingConvention(true, false)); 9906 EPI.Variadic = true; 9907 EPI.ExtInfo = FT->getExtInfo();
89
Called C++ object pointer is null
9908 9909 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9910 NewFD->setType(R); 9911 } 9912 9913 // If there's a #pragma GCC visibility in scope, and this isn't a class 9914 // member, set the visibility of this function. 9915 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9916 AddPushedVisibilityAttribute(NewFD); 9917 9918 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9919 // marking the function. 9920 AddCFAuditedAttribute(NewFD); 9921 9922 // If this is a function definition, check if we have to apply optnone due to 9923 // a pragma. 9924 if(D.isFunctionDefinition()) 9925 AddRangeBasedOptnone(NewFD); 9926 9927 // If this is the first declaration of an extern C variable, update 9928 // the map of such variables. 9929 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9930 isIncompleteDeclExternC(*this, NewFD)) 9931 RegisterLocallyScopedExternCDecl(NewFD, S); 9932 9933 // Set this FunctionDecl's range up to the right paren. 9934 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9935 9936 if (D.isRedeclaration() && !Previous.empty()) { 9937 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9938 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9939 isMemberSpecialization || 9940 isFunctionTemplateSpecialization, 9941 D.isFunctionDefinition()); 9942 } 9943 9944 if (getLangOpts().CUDA) { 9945 IdentifierInfo *II = NewFD->getIdentifier(); 9946 if (II && II->isStr(getCudaConfigureFuncName()) && 9947 !NewFD->isInvalidDecl() && 9948 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9949 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 9950 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9951 << getCudaConfigureFuncName(); 9952 Context.setcudaConfigureCallDecl(NewFD); 9953 } 9954 9955 // Variadic functions, other than a *declaration* of printf, are not allowed 9956 // in device-side CUDA code, unless someone passed 9957 // -fcuda-allow-variadic-functions. 9958 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9959 (NewFD->hasAttr<CUDADeviceAttr>() || 9960 NewFD->hasAttr<CUDAGlobalAttr>()) && 9961 !(II && II->isStr("printf") && NewFD->isExternC() && 9962 !D.isFunctionDefinition())) { 9963 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9964 } 9965 } 9966 9967 MarkUnusedFileScopedDecl(NewFD); 9968 9969 9970 9971 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9972 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9973 if ((getLangOpts().OpenCLVersion >= 120) 9974 && (SC == SC_Static)) { 9975 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9976 D.setInvalidType(); 9977 } 9978 9979 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9980 if (!NewFD->getReturnType()->isVoidType()) { 9981 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9982 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9983 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9984 : FixItHint()); 9985 D.setInvalidType(); 9986 } 9987 9988 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9989 for (auto Param : NewFD->parameters()) 9990 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9991 9992 if (getLangOpts().OpenCLCPlusPlus) { 9993 if (DC->isRecord()) { 9994 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9995 D.setInvalidType(); 9996 } 9997 if (FunctionTemplate) { 9998 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9999 D.setInvalidType(); 10000 } 10001 } 10002 } 10003 10004 if (getLangOpts().CPlusPlus) { 10005 if (FunctionTemplate) { 10006 if (NewFD->isInvalidDecl()) 10007 FunctionTemplate->setInvalidDecl(); 10008 return FunctionTemplate; 10009 } 10010 10011 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10012 CompleteMemberSpecialization(NewFD, Previous); 10013 } 10014 10015 for (const ParmVarDecl *Param : NewFD->parameters()) { 10016 QualType PT = Param->getType(); 10017 10018 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10019 // types. 10020 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 10021 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10022 QualType ElemTy = PipeTy->getElementType(); 10023 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10024 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10025 D.setInvalidType(); 10026 } 10027 } 10028 } 10029 } 10030 10031 // Here we have an function template explicit specialization at class scope. 10032 // The actual specialization will be postponed to template instatiation 10033 // time via the ClassScopeFunctionSpecializationDecl node. 10034 if (isDependentClassScopeExplicitSpecialization) { 10035 ClassScopeFunctionSpecializationDecl *NewSpec = 10036 ClassScopeFunctionSpecializationDecl::Create( 10037 Context, CurContext, NewFD->getLocation(), 10038 cast<CXXMethodDecl>(NewFD), 10039 HasExplicitTemplateArgs, TemplateArgs); 10040 CurContext->addDecl(NewSpec); 10041 AddToScope = false; 10042 } 10043 10044 // Diagnose availability attributes. Availability cannot be used on functions 10045 // that are run during load/unload. 10046 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10047 if (NewFD->hasAttr<ConstructorAttr>()) { 10048 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10049 << 1; 10050 NewFD->dropAttr<AvailabilityAttr>(); 10051 } 10052 if (NewFD->hasAttr<DestructorAttr>()) { 10053 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10054 << 2; 10055 NewFD->dropAttr<AvailabilityAttr>(); 10056 } 10057 } 10058 10059 // Diagnose no_builtin attribute on function declaration that are not a 10060 // definition. 10061 // FIXME: We should really be doing this in 10062 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10063 // the FunctionDecl and at this point of the code 10064 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10065 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10066 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10067 switch (D.getFunctionDefinitionKind()) { 10068 case FunctionDefinitionKind::Defaulted: 10069 case FunctionDefinitionKind::Deleted: 10070 Diag(NBA->getLocation(), 10071 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10072 << NBA->getSpelling(); 10073 break; 10074 case FunctionDefinitionKind::Declaration: 10075 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10076 << NBA->getSpelling(); 10077 break; 10078 case FunctionDefinitionKind::Definition: 10079 break; 10080 } 10081 10082 return NewFD; 10083} 10084 10085/// Return a CodeSegAttr from a containing class. The Microsoft docs say 10086/// when __declspec(code_seg) "is applied to a class, all member functions of 10087/// the class and nested classes -- this includes compiler-generated special 10088/// member functions -- are put in the specified segment." 10089/// The actual behavior is a little more complicated. The Microsoft compiler 10090/// won't check outer classes if there is an active value from #pragma code_seg. 10091/// The CodeSeg is always applied from the direct parent but only from outer 10092/// classes when the #pragma code_seg stack is empty. See: 10093/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10094/// available since MS has removed the page. 10095static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10096 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10097 if (!Method) 10098 return nullptr; 10099 const CXXRecordDecl *Parent = Method->getParent(); 10100 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10101 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10102 NewAttr->setImplicit(true); 10103 return NewAttr; 10104 } 10105 10106 // The Microsoft compiler won't check outer classes for the CodeSeg 10107 // when the #pragma code_seg stack is active. 10108 if (S.CodeSegStack.CurrentValue) 10109 return nullptr; 10110 10111 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10112 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10113 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10114 NewAttr->setImplicit(true); 10115 return NewAttr; 10116 } 10117 } 10118 return nullptr; 10119} 10120 10121/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10122/// containing class. Otherwise it will return implicit SectionAttr if the 10123/// function is a definition and there is an active value on CodeSegStack 10124/// (from the current #pragma code-seg value). 10125/// 10126/// \param FD Function being declared. 10127/// \param IsDefinition Whether it is a definition or just a declarartion. 10128/// \returns A CodeSegAttr or SectionAttr to apply to the function or 10129/// nullptr if no attribute should be added. 10130Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10131 bool IsDefinition) { 10132 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10133 return A; 10134 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10135 CodeSegStack.CurrentValue) 10136 return SectionAttr::CreateImplicit( 10137 getASTContext(), CodeSegStack.CurrentValue->getString(), 10138 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10139 SectionAttr::Declspec_allocate); 10140 return nullptr; 10141} 10142 10143/// Determines if we can perform a correct type check for \p D as a 10144/// redeclaration of \p PrevDecl. If not, we can generally still perform a 10145/// best-effort check. 10146/// 10147/// \param NewD The new declaration. 10148/// \param OldD The old declaration. 10149/// \param NewT The portion of the type of the new declaration to check. 10150/// \param OldT The portion of the type of the old declaration to check. 10151bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10152 QualType NewT, QualType OldT) { 10153 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10154 return true; 10155 10156 // For dependently-typed local extern declarations and friends, we can't 10157 // perform a correct type check in general until instantiation: 10158 // 10159 // int f(); 10160 // template<typename T> void g() { T f(); } 10161 // 10162 // (valid if g() is only instantiated with T = int). 10163 if (NewT->isDependentType() && 10164 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10165 return false; 10166 10167 // Similarly, if the previous declaration was a dependent local extern 10168 // declaration, we don't really know its type yet. 10169 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10170 return false; 10171 10172 return true; 10173} 10174 10175/// Checks if the new declaration declared in dependent context must be 10176/// put in the same redeclaration chain as the specified declaration. 10177/// 10178/// \param D Declaration that is checked. 10179/// \param PrevDecl Previous declaration found with proper lookup method for the 10180/// same declaration name. 10181/// \returns True if D must be added to the redeclaration chain which PrevDecl 10182/// belongs to. 10183/// 10184bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10185 if (!D->getLexicalDeclContext()->isDependentContext()) 10186 return true; 10187 10188 // Don't chain dependent friend function definitions until instantiation, to 10189 // permit cases like 10190 // 10191 // void func(); 10192 // template<typename T> class C1 { friend void func() {} }; 10193 // template<typename T> class C2 { friend void func() {} }; 10194 // 10195 // ... which is valid if only one of C1 and C2 is ever instantiated. 10196 // 10197 // FIXME: This need only apply to function definitions. For now, we proxy 10198 // this by checking for a file-scope function. We do not want this to apply 10199 // to friend declarations nominating member functions, because that gets in 10200 // the way of access checks. 10201 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10202 return false; 10203 10204 auto *VD = dyn_cast<ValueDecl>(D); 10205 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10206 return !VD || !PrevVD || 10207 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10208 PrevVD->getType()); 10209} 10210 10211/// Check the target attribute of the function for MultiVersion 10212/// validity. 10213/// 10214/// Returns true if there was an error, false otherwise. 10215static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10216 const auto *TA = FD->getAttr<TargetAttr>(); 10217 assert(TA && "MultiVersion Candidate requires a target attribute")(static_cast <bool> (TA && "MultiVersion Candidate requires a target attribute"
) ? void (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10217, __extension__ __PRETTY_FUNCTION__))
; 10218 ParsedTargetAttr ParseInfo = TA->parse(); 10219 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10220 enum ErrType { Feature = 0, Architecture = 1 }; 10221 10222 if (!ParseInfo.Architecture.empty() && 10223 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10224 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10225 << Architecture << ParseInfo.Architecture; 10226 return true; 10227 } 10228 10229 for (const auto &Feat : ParseInfo.Features) { 10230 auto BareFeat = StringRef{Feat}.substr(1); 10231 if (Feat[0] == '-') { 10232 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10233 << Feature << ("no-" + BareFeat).str(); 10234 return true; 10235 } 10236 10237 if (!TargetInfo.validateCpuSupports(BareFeat) || 10238 !TargetInfo.isValidFeatureName(BareFeat)) { 10239 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10240 << Feature << BareFeat; 10241 return true; 10242 } 10243 } 10244 return false; 10245} 10246 10247// Provide a white-list of attributes that are allowed to be combined with 10248// multiversion functions. 10249static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10250 MultiVersionKind MVType) { 10251 // Note: this list/diagnosis must match the list in 10252 // checkMultiversionAttributesAllSame. 10253 switch (Kind) { 10254 default: 10255 return false; 10256 case attr::Used: 10257 return MVType == MultiVersionKind::Target; 10258 case attr::NonNull: 10259 case attr::NoThrow: 10260 return true; 10261 } 10262} 10263 10264static bool checkNonMultiVersionCompatAttributes(Sema &S, 10265 const FunctionDecl *FD, 10266 const FunctionDecl *CausedFD, 10267 MultiVersionKind MVType) { 10268 bool IsCPUSpecificCPUDispatchMVType = 10269 MVType == MultiVersionKind::CPUDispatch || 10270 MVType == MultiVersionKind::CPUSpecific; 10271 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( 10272 Sema &S, const Attr *A) { 10273 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10274 << IsCPUSpecificCPUDispatchMVType << A; 10275 if (CausedFD) 10276 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10277 return true; 10278 }; 10279 10280 for (const Attr *A : FD->attrs()) { 10281 switch (A->getKind()) { 10282 case attr::CPUDispatch: 10283 case attr::CPUSpecific: 10284 if (MVType != MultiVersionKind::CPUDispatch && 10285 MVType != MultiVersionKind::CPUSpecific) 10286 return Diagnose(S, A); 10287 break; 10288 case attr::Target: 10289 if (MVType != MultiVersionKind::Target) 10290 return Diagnose(S, A); 10291 break; 10292 default: 10293 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10294 return Diagnose(S, A); 10295 break; 10296 } 10297 } 10298 return false; 10299} 10300 10301bool Sema::areMultiversionVariantFunctionsCompatible( 10302 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10303 const PartialDiagnostic &NoProtoDiagID, 10304 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10305 const PartialDiagnosticAt &NoSupportDiagIDAt, 10306 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10307 bool ConstexprSupported, bool CLinkageMayDiffer) { 10308 enum DoesntSupport { 10309 FuncTemplates = 0, 10310 VirtFuncs = 1, 10311 DeducedReturn = 2, 10312 Constructors = 3, 10313 Destructors = 4, 10314 DeletedFuncs = 5, 10315 DefaultedFuncs = 6, 10316 ConstexprFuncs = 7, 10317 ConstevalFuncs = 8, 10318 }; 10319 enum Different { 10320 CallingConv = 0, 10321 ReturnType = 1, 10322 ConstexprSpec = 2, 10323 InlineSpec = 3, 10324 StorageClass = 4, 10325 Linkage = 5, 10326 }; 10327 10328 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10329 !OldFD->getType()->getAs<FunctionProtoType>()) { 10330 Diag(OldFD->getLocation(), NoProtoDiagID); 10331 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10332 return true; 10333 } 10334 10335 if (NoProtoDiagID.getDiagID() != 0 && 10336 !NewFD->getType()->getAs<FunctionProtoType>()) 10337 return Diag(NewFD->getLocation(), NoProtoDiagID); 10338 10339 if (!TemplatesSupported && 10340 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10341 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10342 << FuncTemplates; 10343 10344 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10345 if (NewCXXFD->isVirtual()) 10346 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10347 << VirtFuncs; 10348 10349 if (isa<CXXConstructorDecl>(NewCXXFD)) 10350 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10351 << Constructors; 10352 10353 if (isa<CXXDestructorDecl>(NewCXXFD)) 10354 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10355 << Destructors; 10356 } 10357 10358 if (NewFD->isDeleted()) 10359 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10360 << DeletedFuncs; 10361 10362 if (NewFD->isDefaulted()) 10363 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10364 << DefaultedFuncs; 10365 10366 if (!ConstexprSupported && NewFD->isConstexpr()) 10367 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10368 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10369 10370 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10371 const auto *NewType = cast<FunctionType>(NewQType); 10372 QualType NewReturnType = NewType->getReturnType(); 10373 10374 if (NewReturnType->isUndeducedType()) 10375 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10376 << DeducedReturn; 10377 10378 // Ensure the return type is identical. 10379 if (OldFD) { 10380 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10381 const auto *OldType = cast<FunctionType>(OldQType); 10382 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10383 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10384 10385 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10386 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10387 10388 QualType OldReturnType = OldType->getReturnType(); 10389 10390 if (OldReturnType != NewReturnType) 10391 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10392 10393 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10394 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10395 10396 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10397 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10398 10399 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10400 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10401 10402 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10403 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10404 10405 if (CheckEquivalentExceptionSpec( 10406 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10407 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10408 return true; 10409 } 10410 return false; 10411} 10412 10413static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10414 const FunctionDecl *NewFD, 10415 bool CausesMV, 10416 MultiVersionKind MVType) { 10417 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10418 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10419 if (OldFD) 10420 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10421 return true; 10422 } 10423 10424 bool IsCPUSpecificCPUDispatchMVType = 10425 MVType == MultiVersionKind::CPUDispatch || 10426 MVType == MultiVersionKind::CPUSpecific; 10427 10428 if (CausesMV && OldFD && 10429 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) 10430 return true; 10431 10432 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) 10433 return true; 10434 10435 // Only allow transition to MultiVersion if it hasn't been used. 10436 if (OldFD && CausesMV && OldFD->isUsed(false)) 10437 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10438 10439 return S.areMultiversionVariantFunctionsCompatible( 10440 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10441 PartialDiagnosticAt(NewFD->getLocation(), 10442 S.PDiag(diag::note_multiversioning_caused_here)), 10443 PartialDiagnosticAt(NewFD->getLocation(), 10444 S.PDiag(diag::err_multiversion_doesnt_support) 10445 << IsCPUSpecificCPUDispatchMVType), 10446 PartialDiagnosticAt(NewFD->getLocation(), 10447 S.PDiag(diag::err_multiversion_diff)), 10448 /*TemplatesSupported=*/false, 10449 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10450 /*CLinkageMayDiffer=*/false); 10451} 10452 10453/// Check the validity of a multiversion function declaration that is the 10454/// first of its kind. Also sets the multiversion'ness' of the function itself. 10455/// 10456/// This sets NewFD->isInvalidDecl() to true if there was an error. 10457/// 10458/// Returns true if there was an error, false otherwise. 10459static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10460 MultiVersionKind MVType, 10461 const TargetAttr *TA) { 10462 assert(MVType != MultiVersionKind::None &&(static_cast <bool> (MVType != MultiVersionKind::None &&
"Function lacks multiversion attribute") ? void (0) : __assert_fail
("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10463, __extension__ __PRETTY_FUNCTION__))
10463 "Function lacks multiversion attribute")(static_cast <bool> (MVType != MultiVersionKind::None &&
"Function lacks multiversion attribute") ? void (0) : __assert_fail
("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10463, __extension__ __PRETTY_FUNCTION__))
; 10464 10465 // Target only causes MV if it is default, otherwise this is a normal 10466 // function. 10467 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10468 return false; 10469 10470 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10471 FD->setInvalidDecl(); 10472 return true; 10473 } 10474 10475 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10476 FD->setInvalidDecl(); 10477 return true; 10478 } 10479 10480 FD->setIsMultiVersion(); 10481 return false; 10482} 10483 10484static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10485 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10486 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10487 return true; 10488 } 10489 10490 return false; 10491} 10492 10493static bool CheckTargetCausesMultiVersioning( 10494 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10495 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10496 LookupResult &Previous) { 10497 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10498 ParsedTargetAttr NewParsed = NewTA->parse(); 10499 // Sort order doesn't matter, it just needs to be consistent. 10500 llvm::sort(NewParsed.Features); 10501 10502 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10503 // to change, this is a simple redeclaration. 10504 if (!NewTA->isDefaultVersion() && 10505 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10506 return false; 10507 10508 // Otherwise, this decl causes MultiVersioning. 10509 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10510 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10511 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10512 NewFD->setInvalidDecl(); 10513 return true; 10514 } 10515 10516 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10517 MultiVersionKind::Target)) { 10518 NewFD->setInvalidDecl(); 10519 return true; 10520 } 10521 10522 if (CheckMultiVersionValue(S, NewFD)) { 10523 NewFD->setInvalidDecl(); 10524 return true; 10525 } 10526 10527 // If this is 'default', permit the forward declaration. 10528 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10529 Redeclaration = true; 10530 OldDecl = OldFD; 10531 OldFD->setIsMultiVersion(); 10532 NewFD->setIsMultiVersion(); 10533 return false; 10534 } 10535 10536 if (CheckMultiVersionValue(S, OldFD)) { 10537 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10538 NewFD->setInvalidDecl(); 10539 return true; 10540 } 10541 10542 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10543 10544 if (OldParsed == NewParsed) { 10545 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10546 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10547 NewFD->setInvalidDecl(); 10548 return true; 10549 } 10550 10551 for (const auto *FD : OldFD->redecls()) { 10552 const auto *CurTA = FD->getAttr<TargetAttr>(); 10553 // We allow forward declarations before ANY multiversioning attributes, but 10554 // nothing after the fact. 10555 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10556 (!CurTA || CurTA->isInherited())) { 10557 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10558 << 0; 10559 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10560 NewFD->setInvalidDecl(); 10561 return true; 10562 } 10563 } 10564 10565 OldFD->setIsMultiVersion(); 10566 NewFD->setIsMultiVersion(); 10567 Redeclaration = false; 10568 MergeTypeWithPrevious = false; 10569 OldDecl = nullptr; 10570 Previous.clear(); 10571 return false; 10572} 10573 10574/// Check the validity of a new function declaration being added to an existing 10575/// multiversioned declaration collection. 10576static bool CheckMultiVersionAdditionalDecl( 10577 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10578 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10579 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10580 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10581 LookupResult &Previous) { 10582 10583 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10584 // Disallow mixing of multiversioning types. 10585 if ((OldMVType == MultiVersionKind::Target && 10586 NewMVType != MultiVersionKind::Target) || 10587 (NewMVType == MultiVersionKind::Target && 10588 OldMVType != MultiVersionKind::Target)) { 10589 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10590 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10591 NewFD->setInvalidDecl(); 10592 return true; 10593 } 10594 10595 ParsedTargetAttr NewParsed; 10596 if (NewTA) { 10597 NewParsed = NewTA->parse(); 10598 llvm::sort(NewParsed.Features); 10599 } 10600 10601 bool UseMemberUsingDeclRules = 10602 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10603 10604 // Next, check ALL non-overloads to see if this is a redeclaration of a 10605 // previous member of the MultiVersion set. 10606 for (NamedDecl *ND : Previous) { 10607 FunctionDecl *CurFD = ND->getAsFunction(); 10608 if (!CurFD) 10609 continue; 10610 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10611 continue; 10612 10613 if (NewMVType == MultiVersionKind::Target) { 10614 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10615 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10616 NewFD->setIsMultiVersion(); 10617 Redeclaration = true; 10618 OldDecl = ND; 10619 return false; 10620 } 10621 10622 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10623 if (CurParsed == NewParsed) { 10624 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10625 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10626 NewFD->setInvalidDecl(); 10627 return true; 10628 } 10629 } else { 10630 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10631 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10632 // Handle CPUDispatch/CPUSpecific versions. 10633 // Only 1 CPUDispatch function is allowed, this will make it go through 10634 // the redeclaration errors. 10635 if (NewMVType == MultiVersionKind::CPUDispatch && 10636 CurFD->hasAttr<CPUDispatchAttr>()) { 10637 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10638 std::equal( 10639 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10640 NewCPUDisp->cpus_begin(), 10641 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10642 return Cur->getName() == New->getName(); 10643 })) { 10644 NewFD->setIsMultiVersion(); 10645 Redeclaration = true; 10646 OldDecl = ND; 10647 return false; 10648 } 10649 10650 // If the declarations don't match, this is an error condition. 10651 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10652 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10653 NewFD->setInvalidDecl(); 10654 return true; 10655 } 10656 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10657 10658 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10659 std::equal( 10660 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10661 NewCPUSpec->cpus_begin(), 10662 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10663 return Cur->getName() == New->getName(); 10664 })) { 10665 NewFD->setIsMultiVersion(); 10666 Redeclaration = true; 10667 OldDecl = ND; 10668 return false; 10669 } 10670 10671 // Only 1 version of CPUSpecific is allowed for each CPU. 10672 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10673 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10674 if (CurII == NewII) { 10675 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10676 << NewII; 10677 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10678 NewFD->setInvalidDecl(); 10679 return true; 10680 } 10681 } 10682 } 10683 } 10684 // If the two decls aren't the same MVType, there is no possible error 10685 // condition. 10686 } 10687 } 10688 10689 // Else, this is simply a non-redecl case. Checking the 'value' is only 10690 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10691 // handled in the attribute adding step. 10692 if (NewMVType == MultiVersionKind::Target && 10693 CheckMultiVersionValue(S, NewFD)) { 10694 NewFD->setInvalidDecl(); 10695 return true; 10696 } 10697 10698 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10699 !OldFD->isMultiVersion(), NewMVType)) { 10700 NewFD->setInvalidDecl(); 10701 return true; 10702 } 10703 10704 // Permit forward declarations in the case where these two are compatible. 10705 if (!OldFD->isMultiVersion()) { 10706 OldFD->setIsMultiVersion(); 10707 NewFD->setIsMultiVersion(); 10708 Redeclaration = true; 10709 OldDecl = OldFD; 10710 return false; 10711 } 10712 10713 NewFD->setIsMultiVersion(); 10714 Redeclaration = false; 10715 MergeTypeWithPrevious = false; 10716 OldDecl = nullptr; 10717 Previous.clear(); 10718 return false; 10719} 10720 10721 10722/// Check the validity of a mulitversion function declaration. 10723/// Also sets the multiversion'ness' of the function itself. 10724/// 10725/// This sets NewFD->isInvalidDecl() to true if there was an error. 10726/// 10727/// Returns true if there was an error, false otherwise. 10728static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10729 bool &Redeclaration, NamedDecl *&OldDecl, 10730 bool &MergeTypeWithPrevious, 10731 LookupResult &Previous) { 10732 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10733 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10734 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10735 10736 // Mixing Multiversioning types is prohibited. 10737 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10738 (NewCPUDisp && NewCPUSpec)) { 10739 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10740 NewFD->setInvalidDecl(); 10741 return true; 10742 } 10743 10744 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10745 10746 // Main isn't allowed to become a multiversion function, however it IS 10747 // permitted to have 'main' be marked with the 'target' optimization hint. 10748 if (NewFD->isMain()) { 10749 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10750 MVType == MultiVersionKind::CPUDispatch || 10751 MVType == MultiVersionKind::CPUSpecific) { 10752 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10753 NewFD->setInvalidDecl(); 10754 return true; 10755 } 10756 return false; 10757 } 10758 10759 if (!OldDecl || !OldDecl->getAsFunction() || 10760 OldDecl->getDeclContext()->getRedeclContext() != 10761 NewFD->getDeclContext()->getRedeclContext()) { 10762 // If there's no previous declaration, AND this isn't attempting to cause 10763 // multiversioning, this isn't an error condition. 10764 if (MVType == MultiVersionKind::None) 10765 return false; 10766 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10767 } 10768 10769 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10770 10771 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10772 return false; 10773 10774 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10775 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10776 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10777 NewFD->setInvalidDecl(); 10778 return true; 10779 } 10780 10781 // Handle the target potentially causes multiversioning case. 10782 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10783 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10784 Redeclaration, OldDecl, 10785 MergeTypeWithPrevious, Previous); 10786 10787 // At this point, we have a multiversion function decl (in OldFD) AND an 10788 // appropriate attribute in the current function decl. Resolve that these are 10789 // still compatible with previous declarations. 10790 return CheckMultiVersionAdditionalDecl( 10791 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10792 OldDecl, MergeTypeWithPrevious, Previous); 10793} 10794 10795/// Perform semantic checking of a new function declaration. 10796/// 10797/// Performs semantic analysis of the new function declaration 10798/// NewFD. This routine performs all semantic checking that does not 10799/// require the actual declarator involved in the declaration, and is 10800/// used both for the declaration of functions as they are parsed 10801/// (called via ActOnDeclarator) and for the declaration of functions 10802/// that have been instantiated via C++ template instantiation (called 10803/// via InstantiateDecl). 10804/// 10805/// \param IsMemberSpecialization whether this new function declaration is 10806/// a member specialization (that replaces any definition provided by the 10807/// previous declaration). 10808/// 10809/// This sets NewFD->isInvalidDecl() to true if there was an error. 10810/// 10811/// \returns true if the function declaration is a redeclaration. 10812bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10813 LookupResult &Previous, 10814 bool IsMemberSpecialization) { 10815 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType
() && "Variably modified return types are not handled here"
) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10816, __extension__ __PRETTY_FUNCTION__))
10816 "Variably modified return types are not handled here")(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType
() && "Variably modified return types are not handled here"
) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10816, __extension__ __PRETTY_FUNCTION__))
; 10817 10818 // Determine whether the type of this function should be merged with 10819 // a previous visible declaration. This never happens for functions in C++, 10820 // and always happens in C if the previous declaration was visible. 10821 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10822 !Previous.isShadowed(); 10823 10824 bool Redeclaration = false; 10825 NamedDecl *OldDecl = nullptr; 10826 bool MayNeedOverloadableChecks = false; 10827 10828 // Merge or overload the declaration with an existing declaration of 10829 // the same name, if appropriate. 10830 if (!Previous.empty()) { 10831 // Determine whether NewFD is an overload of PrevDecl or 10832 // a declaration that requires merging. If it's an overload, 10833 // there's no more work to do here; we'll just add the new 10834 // function to the scope. 10835 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10836 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10837 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10838 Redeclaration = true; 10839 OldDecl = Candidate; 10840 } 10841 } else { 10842 MayNeedOverloadableChecks = true; 10843 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10844 /*NewIsUsingDecl*/ false)) { 10845 case Ovl_Match: 10846 Redeclaration = true; 10847 break; 10848 10849 case Ovl_NonFunction: 10850 Redeclaration = true; 10851 break; 10852 10853 case Ovl_Overload: 10854 Redeclaration = false; 10855 break; 10856 } 10857 } 10858 } 10859 10860 // Check for a previous extern "C" declaration with this name. 10861 if (!Redeclaration && 10862 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10863 if (!Previous.empty()) { 10864 // This is an extern "C" declaration with the same name as a previous 10865 // declaration, and thus redeclares that entity... 10866 Redeclaration = true; 10867 OldDecl = Previous.getFoundDecl(); 10868 MergeTypeWithPrevious = false; 10869 10870 // ... except in the presence of __attribute__((overloadable)). 10871 if (OldDecl->hasAttr<OverloadableAttr>() || 10872 NewFD->hasAttr<OverloadableAttr>()) { 10873 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10874 MayNeedOverloadableChecks = true; 10875 Redeclaration = false; 10876 OldDecl = nullptr; 10877 } 10878 } 10879 } 10880 } 10881 10882 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10883 MergeTypeWithPrevious, Previous)) 10884 return Redeclaration; 10885 10886 // PPC MMA non-pointer types are not allowed as function return types. 10887 if (Context.getTargetInfo().getTriple().isPPC64() && 10888 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 10889 NewFD->setInvalidDecl(); 10890 } 10891 10892 // C++11 [dcl.constexpr]p8: 10893 // A constexpr specifier for a non-static member function that is not 10894 // a constructor declares that member function to be const. 10895 // 10896 // This needs to be delayed until we know whether this is an out-of-line 10897 // definition of a static member function. 10898 // 10899 // This rule is not present in C++1y, so we produce a backwards 10900 // compatibility warning whenever it happens in C++11. 10901 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10902 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10903 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10904 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10905 CXXMethodDecl *OldMD = nullptr; 10906 if (OldDecl) 10907 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10908 if (!OldMD || !OldMD->isStatic()) { 10909 const FunctionProtoType *FPT = 10910 MD->getType()->castAs<FunctionProtoType>(); 10911 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10912 EPI.TypeQuals.addConst(); 10913 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10914 FPT->getParamTypes(), EPI)); 10915 10916 // Warn that we did this, if we're not performing template instantiation. 10917 // In that case, we'll have warned already when the template was defined. 10918 if (!inTemplateInstantiation()) { 10919 SourceLocation AddConstLoc; 10920 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10921 .IgnoreParens().getAs<FunctionTypeLoc>()) 10922 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10923 10924 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10925 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10926 } 10927 } 10928 } 10929 10930 if (Redeclaration) { 10931 // NewFD and OldDecl represent declarations that need to be 10932 // merged. 10933 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10934 NewFD->setInvalidDecl(); 10935 return Redeclaration; 10936 } 10937 10938 Previous.clear(); 10939 Previous.addDecl(OldDecl); 10940 10941 if (FunctionTemplateDecl *OldTemplateDecl = 10942 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10943 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10944 FunctionTemplateDecl *NewTemplateDecl 10945 = NewFD->getDescribedFunctionTemplate(); 10946 assert(NewTemplateDecl && "Template/non-template mismatch")(static_cast <bool> (NewTemplateDecl && "Template/non-template mismatch"
) ? void (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10946, __extension__ __PRETTY_FUNCTION__))
; 10947 10948 // The call to MergeFunctionDecl above may have created some state in 10949 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10950 // can add it as a redeclaration. 10951 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10952 10953 NewFD->setPreviousDeclaration(OldFD); 10954 if (NewFD->isCXXClassMember()) { 10955 NewFD->setAccess(OldTemplateDecl->getAccess()); 10956 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10957 } 10958 10959 // If this is an explicit specialization of a member that is a function 10960 // template, mark it as a member specialization. 10961 if (IsMemberSpecialization && 10962 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10963 NewTemplateDecl->setMemberSpecialization(); 10964 assert(OldTemplateDecl->isMemberSpecialization())(static_cast <bool> (OldTemplateDecl->isMemberSpecialization
()) ? void (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10964, __extension__ __PRETTY_FUNCTION__))
; 10965 // Explicit specializations of a member template do not inherit deleted 10966 // status from the parent member template that they are specializing. 10967 if (OldFD->isDeleted()) { 10968 // FIXME: This assert will not hold in the presence of modules. 10969 assert(OldFD->getCanonicalDecl() == OldFD)(static_cast <bool> (OldFD->getCanonicalDecl() == OldFD
) ? void (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10969, __extension__ __PRETTY_FUNCTION__))
; 10970 // FIXME: We need an update record for this AST mutation. 10971 OldFD->setDeletedAsWritten(false); 10972 } 10973 } 10974 10975 } else { 10976 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10977 auto *OldFD = cast<FunctionDecl>(OldDecl); 10978 // This needs to happen first so that 'inline' propagates. 10979 NewFD->setPreviousDeclaration(OldFD); 10980 if (NewFD->isCXXClassMember()) 10981 NewFD->setAccess(OldFD->getAccess()); 10982 } 10983 } 10984 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10985 !NewFD->getAttr<OverloadableAttr>()) { 10986 assert((Previous.empty() ||(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10991, __extension__ __PRETTY_FUNCTION__))
10987 llvm::any_of(Previous,(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10991, __extension__ __PRETTY_FUNCTION__))
10988 [](const NamedDecl *ND) {(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10991, __extension__ __PRETTY_FUNCTION__))
10989 return ND->hasAttr<OverloadableAttr>();(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10991, __extension__ __PRETTY_FUNCTION__))
10990 })) &&(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10991, __extension__ __PRETTY_FUNCTION__))
10991 "Non-redecls shouldn't happen without overloadable present")(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 10991, __extension__ __PRETTY_FUNCTION__))
; 10992 10993 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10994 const auto *FD = dyn_cast<FunctionDecl>(ND); 10995 return FD && !FD->hasAttr<OverloadableAttr>(); 10996 }); 10997 10998 if (OtherUnmarkedIter != Previous.end()) { 10999 Diag(NewFD->getLocation(), 11000 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11001 Diag((*OtherUnmarkedIter)->getLocation(), 11002 diag::note_attribute_overloadable_prev_overload) 11003 << false; 11004 11005 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11006 } 11007 } 11008 11009 if (LangOpts.OpenMP) 11010 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11011 11012 // Semantic checking for this function declaration (in isolation). 11013 11014 if (getLangOpts().CPlusPlus) { 11015 // C++-specific checks. 11016 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11017 CheckConstructor(Constructor); 11018 } else if (CXXDestructorDecl *Destructor = 11019 dyn_cast<CXXDestructorDecl>(NewFD)) { 11020 CXXRecordDecl *Record = Destructor->getParent(); 11021 QualType ClassType = Context.getTypeDeclType(Record); 11022 11023 // FIXME: Shouldn't we be able to perform this check even when the class 11024 // type is dependent? Both gcc and edg can handle that. 11025 if (!ClassType->isDependentType()) { 11026 DeclarationName Name 11027 = Context.DeclarationNames.getCXXDestructorName( 11028 Context.getCanonicalType(ClassType)); 11029 if (NewFD->getDeclName() != Name) { 11030 Diag(NewFD->getLocation(), diag::err_destructor_name); 11031 NewFD->setInvalidDecl(); 11032 return Redeclaration; 11033 } 11034 } 11035 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11036 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11037 CheckDeductionGuideTemplate(TD); 11038 11039 // A deduction guide is not on the list of entities that can be 11040 // explicitly specialized. 11041 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11042 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11043 << /*explicit specialization*/ 1; 11044 } 11045 11046 // Find any virtual functions that this function overrides. 11047 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11048 if (!Method->isFunctionTemplateSpecialization() && 11049 !Method->getDescribedFunctionTemplate() && 11050 Method->isCanonicalDecl()) { 11051 AddOverriddenMethods(Method->getParent(), Method); 11052 } 11053 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11054 // C++2a [class.virtual]p6 11055 // A virtual method shall not have a requires-clause. 11056 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11057 diag::err_constrained_virtual_method); 11058 11059 if (Method->isStatic()) 11060 checkThisInStaticMemberFunctionType(Method); 11061 } 11062 11063 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11064 ActOnConversionDeclarator(Conversion); 11065 11066 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11067 if (NewFD->isOverloadedOperator() && 11068 CheckOverloadedOperatorDeclaration(NewFD)) { 11069 NewFD->setInvalidDecl(); 11070 return Redeclaration; 11071 } 11072 11073 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11074 if (NewFD->getLiteralIdentifier() && 11075 CheckLiteralOperatorDeclaration(NewFD)) { 11076 NewFD->setInvalidDecl(); 11077 return Redeclaration; 11078 } 11079 11080 // In C++, check default arguments now that we have merged decls. Unless 11081 // the lexical context is the class, because in this case this is done 11082 // during delayed parsing anyway. 11083 if (!CurContext->isRecord()) 11084 CheckCXXDefaultArguments(NewFD); 11085 11086 // If this function is declared as being extern "C", then check to see if 11087 // the function returns a UDT (class, struct, or union type) that is not C 11088 // compatible, and if it does, warn the user. 11089 // But, issue any diagnostic on the first declaration only. 11090 if (Previous.empty() && NewFD->isExternC()) { 11091 QualType R = NewFD->getReturnType(); 11092 if (R->isIncompleteType() && !R->isVoidType()) 11093 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11094 << NewFD << R; 11095 else if (!R.isPODType(Context) && !R->isVoidType() && 11096 !R->isObjCObjectPointerType()) 11097 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11098 } 11099 11100 // C++1z [dcl.fct]p6: 11101 // [...] whether the function has a non-throwing exception-specification 11102 // [is] part of the function type 11103 // 11104 // This results in an ABI break between C++14 and C++17 for functions whose 11105 // declared type includes an exception-specification in a parameter or 11106 // return type. (Exception specifications on the function itself are OK in 11107 // most cases, and exception specifications are not permitted in most other 11108 // contexts where they could make it into a mangling.) 11109 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11110 auto HasNoexcept = [&](QualType T) -> bool { 11111 // Strip off declarator chunks that could be between us and a function 11112 // type. We don't need to look far, exception specifications are very 11113 // restricted prior to C++17. 11114 if (auto *RT = T->getAs<ReferenceType>()) 11115 T = RT->getPointeeType(); 11116 else if (T->isAnyPointerType()) 11117 T = T->getPointeeType(); 11118 else if (auto *MPT = T->getAs<MemberPointerType>()) 11119 T = MPT->getPointeeType(); 11120 if (auto *FPT = T->getAs<FunctionProtoType>()) 11121 if (FPT->isNothrow()) 11122 return true; 11123 return false; 11124 }; 11125 11126 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11127 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11128 for (QualType T : FPT->param_types()) 11129 AnyNoexcept |= HasNoexcept(T); 11130 if (AnyNoexcept) 11131 Diag(NewFD->getLocation(), 11132 diag::warn_cxx17_compat_exception_spec_in_signature) 11133 << NewFD; 11134 } 11135 11136 if (!Redeclaration && LangOpts.CUDA) 11137 checkCUDATargetOverload(NewFD, Previous); 11138 } 11139 return Redeclaration; 11140} 11141 11142void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11143 // C++11 [basic.start.main]p3: 11144 // A program that [...] declares main to be inline, static or 11145 // constexpr is ill-formed. 11146 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11147 // appear in a declaration of main. 11148 // static main is not an error under C99, but we should warn about it. 11149 // We accept _Noreturn main as an extension. 11150 if (FD->getStorageClass() == SC_Static) 11151 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11152 ? diag::err_static_main : diag::warn_static_main) 11153 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11154 if (FD->isInlineSpecified()) 11155 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11156 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11157 if (DS.isNoreturnSpecified()) { 11158 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11159 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11160 Diag(NoreturnLoc, diag::ext_noreturn_main); 11161 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11162 << FixItHint::CreateRemoval(NoreturnRange); 11163 } 11164 if (FD->isConstexpr()) { 11165 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11166 << FD->isConsteval() 11167 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11168 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11169 } 11170 11171 if (getLangOpts().OpenCL) { 11172 Diag(FD->getLocation(), diag::err_opencl_no_main) 11173 << FD->hasAttr<OpenCLKernelAttr>(); 11174 FD->setInvalidDecl(); 11175 return; 11176 } 11177 11178 QualType T = FD->getType(); 11179 assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11179, __extension__ __PRETTY_FUNCTION__))
; 11180 const FunctionType* FT = T->castAs<FunctionType>(); 11181 11182 // Set default calling convention for main() 11183 if (FT->getCallConv() != CC_C) { 11184 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11185 FD->setType(QualType(FT, 0)); 11186 T = Context.getCanonicalType(FD->getType()); 11187 } 11188 11189 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11190 // In C with GNU extensions we allow main() to have non-integer return 11191 // type, but we should warn about the extension, and we disable the 11192 // implicit-return-zero rule. 11193 11194 // GCC in C mode accepts qualified 'int'. 11195 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11196 FD->setHasImplicitReturnZero(true); 11197 else { 11198 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11199 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11200 if (RTRange.isValid()) 11201 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11202 << FixItHint::CreateReplacement(RTRange, "int"); 11203 } 11204 } else { 11205 // In C and C++, main magically returns 0 if you fall off the end; 11206 // set the flag which tells us that. 11207 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11208 11209 // All the standards say that main() should return 'int'. 11210 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11211 FD->setHasImplicitReturnZero(true); 11212 else { 11213 // Otherwise, this is just a flat-out error. 11214 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11215 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11216 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11217 : FixItHint()); 11218 FD->setInvalidDecl(true); 11219 } 11220 } 11221 11222 // Treat protoless main() as nullary. 11223 if (isa<FunctionNoProtoType>(FT)) return; 11224 11225 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11226 unsigned nparams = FTP->getNumParams(); 11227 assert(FD->getNumParams() == nparams)(static_cast <bool> (FD->getNumParams() == nparams) ?
void (0) : __assert_fail ("FD->getNumParams() == nparams"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11227, __extension__ __PRETTY_FUNCTION__))
; 11228 11229 bool HasExtraParameters = (nparams > 3); 11230 11231 if (FTP->isVariadic()) { 11232 Diag(FD->getLocation(), diag::ext_variadic_main); 11233 // FIXME: if we had information about the location of the ellipsis, we 11234 // could add a FixIt hint to remove it as a parameter. 11235 } 11236 11237 // Darwin passes an undocumented fourth argument of type char**. If 11238 // other platforms start sprouting these, the logic below will start 11239 // getting shifty. 11240 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11241 HasExtraParameters = false; 11242 11243 if (HasExtraParameters) { 11244 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11245 FD->setInvalidDecl(true); 11246 nparams = 3; 11247 } 11248 11249 // FIXME: a lot of the following diagnostics would be improved 11250 // if we had some location information about types. 11251 11252 QualType CharPP = 11253 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11254 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11255 11256 for (unsigned i = 0; i < nparams; ++i) { 11257 QualType AT = FTP->getParamType(i); 11258 11259 bool mismatch = true; 11260 11261 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11262 mismatch = false; 11263 else if (Expected[i] == CharPP) { 11264 // As an extension, the following forms are okay: 11265 // char const ** 11266 // char const * const * 11267 // char * const * 11268 11269 QualifierCollector qs; 11270 const PointerType* PT; 11271 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11272 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11273 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11274 Context.CharTy)) { 11275 qs.removeConst(); 11276 mismatch = !qs.empty(); 11277 } 11278 } 11279 11280 if (mismatch) { 11281 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11282 // TODO: suggest replacing given type with expected type 11283 FD->setInvalidDecl(true); 11284 } 11285 } 11286 11287 if (nparams == 1 && !FD->isInvalidDecl()) { 11288 Diag(FD->getLocation(), diag::warn_main_one_arg); 11289 } 11290 11291 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11292 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11293 FD->setInvalidDecl(); 11294 } 11295} 11296 11297static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11298 11299 // Default calling convention for main and wmain is __cdecl 11300 if (FD->getName() == "main" || FD->getName() == "wmain") 11301 return false; 11302 11303 // Default calling convention for MinGW is __cdecl 11304 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11305 if (T.isWindowsGNUEnvironment()) 11306 return false; 11307 11308 // Default calling convention for WinMain, wWinMain and DllMain 11309 // is __stdcall on 32 bit Windows 11310 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11311 return true; 11312 11313 return false; 11314} 11315 11316void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11317 QualType T = FD->getType(); 11318 assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11318, __extension__ __PRETTY_FUNCTION__))
; 11319 const FunctionType *FT = T->castAs<FunctionType>(); 11320 11321 // Set an implicit return of 'zero' if the function can return some integral, 11322 // enumeration, pointer or nullptr type. 11323 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11324 FT->getReturnType()->isAnyPointerType() || 11325 FT->getReturnType()->isNullPtrType()) 11326 // DllMain is exempt because a return value of zero means it failed. 11327 if (FD->getName() != "DllMain") 11328 FD->setHasImplicitReturnZero(true); 11329 11330 // Explicity specified calling conventions are applied to MSVC entry points 11331 if (!hasExplicitCallingConv(T)) { 11332 if (isDefaultStdCall(FD, *this)) { 11333 if (FT->getCallConv() != CC_X86StdCall) { 11334 FT = Context.adjustFunctionType( 11335 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11336 FD->setType(QualType(FT, 0)); 11337 } 11338 } else if (FT->getCallConv() != CC_C) { 11339 FT = Context.adjustFunctionType(FT, 11340 FT->getExtInfo().withCallingConv(CC_C)); 11341 FD->setType(QualType(FT, 0)); 11342 } 11343 } 11344 11345 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11346 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11347 FD->setInvalidDecl(); 11348 } 11349} 11350 11351bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11352 // FIXME: Need strict checking. In C89, we need to check for 11353 // any assignment, increment, decrement, function-calls, or 11354 // commas outside of a sizeof. In C99, it's the same list, 11355 // except that the aforementioned are allowed in unevaluated 11356 // expressions. Everything else falls under the 11357 // "may accept other forms of constant expressions" exception. 11358 // 11359 // Regular C++ code will not end up here (exceptions: language extensions, 11360 // OpenCL C++ etc), so the constant expression rules there don't matter. 11361 if (Init->isValueDependent()) { 11362 assert(Init->containsErrors() &&(static_cast <bool> (Init->containsErrors() &&
"Dependent code should only occur in error-recovery path.") ?
void (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11363, __extension__ __PRETTY_FUNCTION__))
11363 "Dependent code should only occur in error-recovery path.")(static_cast <bool> (Init->containsErrors() &&
"Dependent code should only occur in error-recovery path.") ?
void (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11363, __extension__ __PRETTY_FUNCTION__))
; 11364 return true; 11365 } 11366 const Expr *Culprit; 11367 if (Init->isConstantInitializer(Context, false, &Culprit)) 11368 return false; 11369 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11370 << Culprit->getSourceRange(); 11371 return true; 11372} 11373 11374namespace { 11375 // Visits an initialization expression to see if OrigDecl is evaluated in 11376 // its own initialization and throws a warning if it does. 11377 class SelfReferenceChecker 11378 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11379 Sema &S; 11380 Decl *OrigDecl; 11381 bool isRecordType; 11382 bool isPODType; 11383 bool isReferenceType; 11384 11385 bool isInitList; 11386 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11387 11388 public: 11389 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11390 11391 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11392 S(S), OrigDecl(OrigDecl) { 11393 isPODType = false; 11394 isRecordType = false; 11395 isReferenceType = false; 11396 isInitList = false; 11397 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11398 isPODType = VD->getType().isPODType(S.Context); 11399 isRecordType = VD->getType()->isRecordType(); 11400 isReferenceType = VD->getType()->isReferenceType(); 11401 } 11402 } 11403 11404 // For most expressions, just call the visitor. For initializer lists, 11405 // track the index of the field being initialized since fields are 11406 // initialized in order allowing use of previously initialized fields. 11407 void CheckExpr(Expr *E) { 11408 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11409 if (!InitList) { 11410 Visit(E); 11411 return; 11412 } 11413 11414 // Track and increment the index here. 11415 isInitList = true; 11416 InitFieldIndex.push_back(0); 11417 for (auto Child : InitList->children()) { 11418 CheckExpr(cast<Expr>(Child)); 11419 ++InitFieldIndex.back(); 11420 } 11421 InitFieldIndex.pop_back(); 11422 } 11423 11424 // Returns true if MemberExpr is checked and no further checking is needed. 11425 // Returns false if additional checking is required. 11426 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11427 llvm::SmallVector<FieldDecl*, 4> Fields; 11428 Expr *Base = E; 11429 bool ReferenceField = false; 11430 11431 // Get the field members used. 11432 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11433 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11434 if (!FD) 11435 return false; 11436 Fields.push_back(FD); 11437 if (FD->getType()->isReferenceType()) 11438 ReferenceField = true; 11439 Base = ME->getBase()->IgnoreParenImpCasts(); 11440 } 11441 11442 // Keep checking only if the base Decl is the same. 11443 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11444 if (!DRE || DRE->getDecl() != OrigDecl) 11445 return false; 11446 11447 // A reference field can be bound to an unininitialized field. 11448 if (CheckReference && !ReferenceField) 11449 return true; 11450 11451 // Convert FieldDecls to their index number. 11452 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11453 for (const FieldDecl *I : llvm::reverse(Fields)) 11454 UsedFieldIndex.push_back(I->getFieldIndex()); 11455 11456 // See if a warning is needed by checking the first difference in index 11457 // numbers. If field being used has index less than the field being 11458 // initialized, then the use is safe. 11459 for (auto UsedIter = UsedFieldIndex.begin(), 11460 UsedEnd = UsedFieldIndex.end(), 11461 OrigIter = InitFieldIndex.begin(), 11462 OrigEnd = InitFieldIndex.end(); 11463 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11464 if (*UsedIter < *OrigIter) 11465 return true; 11466 if (*UsedIter > *OrigIter) 11467 break; 11468 } 11469 11470 // TODO: Add a different warning which will print the field names. 11471 HandleDeclRefExpr(DRE); 11472 return true; 11473 } 11474 11475 // For most expressions, the cast is directly above the DeclRefExpr. 11476 // For conditional operators, the cast can be outside the conditional 11477 // operator if both expressions are DeclRefExpr's. 11478 void HandleValue(Expr *E) { 11479 E = E->IgnoreParens(); 11480 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11481 HandleDeclRefExpr(DRE); 11482 return; 11483 } 11484 11485 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11486 Visit(CO->getCond()); 11487 HandleValue(CO->getTrueExpr()); 11488 HandleValue(CO->getFalseExpr()); 11489 return; 11490 } 11491 11492 if (BinaryConditionalOperator *BCO = 11493 dyn_cast<BinaryConditionalOperator>(E)) { 11494 Visit(BCO->getCond()); 11495 HandleValue(BCO->getFalseExpr()); 11496 return; 11497 } 11498 11499 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11500 HandleValue(OVE->getSourceExpr()); 11501 return; 11502 } 11503 11504 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11505 if (BO->getOpcode() == BO_Comma) { 11506 Visit(BO->getLHS()); 11507 HandleValue(BO->getRHS()); 11508 return; 11509 } 11510 } 11511 11512 if (isa<MemberExpr>(E)) { 11513 if (isInitList) { 11514 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11515 false /*CheckReference*/)) 11516 return; 11517 } 11518 11519 Expr *Base = E->IgnoreParenImpCasts(); 11520 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11521 // Check for static member variables and don't warn on them. 11522 if (!isa<FieldDecl>(ME->getMemberDecl())) 11523 return; 11524 Base = ME->getBase()->IgnoreParenImpCasts(); 11525 } 11526 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11527 HandleDeclRefExpr(DRE); 11528 return; 11529 } 11530 11531 Visit(E); 11532 } 11533 11534 // Reference types not handled in HandleValue are handled here since all 11535 // uses of references are bad, not just r-value uses. 11536 void VisitDeclRefExpr(DeclRefExpr *E) { 11537 if (isReferenceType) 11538 HandleDeclRefExpr(E); 11539 } 11540 11541 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11542 if (E->getCastKind() == CK_LValueToRValue) { 11543 HandleValue(E->getSubExpr()); 11544 return; 11545 } 11546 11547 Inherited::VisitImplicitCastExpr(E); 11548 } 11549 11550 void VisitMemberExpr(MemberExpr *E) { 11551 if (isInitList) { 11552 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11553 return; 11554 } 11555 11556 // Don't warn on arrays since they can be treated as pointers. 11557 if (E->getType()->canDecayToPointerType()) return; 11558 11559 // Warn when a non-static method call is followed by non-static member 11560 // field accesses, which is followed by a DeclRefExpr. 11561 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11562 bool Warn = (MD && !MD->isStatic()); 11563 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11564 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11565 if (!isa<FieldDecl>(ME->getMemberDecl())) 11566 Warn = false; 11567 Base = ME->getBase()->IgnoreParenImpCasts(); 11568 } 11569 11570 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11571 if (Warn) 11572 HandleDeclRefExpr(DRE); 11573 return; 11574 } 11575 11576 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11577 // Visit that expression. 11578 Visit(Base); 11579 } 11580 11581 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11582 Expr *Callee = E->getCallee(); 11583 11584 if (isa<UnresolvedLookupExpr>(Callee)) 11585 return Inherited::VisitCXXOperatorCallExpr(E); 11586 11587 Visit(Callee); 11588 for (auto Arg: E->arguments()) 11589 HandleValue(Arg->IgnoreParenImpCasts()); 11590 } 11591 11592 void VisitUnaryOperator(UnaryOperator *E) { 11593 // For POD record types, addresses of its own members are well-defined. 11594 if (E->getOpcode() == UO_AddrOf && isRecordType && 11595 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11596 if (!isPODType) 11597 HandleValue(E->getSubExpr()); 11598 return; 11599 } 11600 11601 if (E->isIncrementDecrementOp()) { 11602 HandleValue(E->getSubExpr()); 11603 return; 11604 } 11605 11606 Inherited::VisitUnaryOperator(E); 11607 } 11608 11609 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11610 11611 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11612 if (E->getConstructor()->isCopyConstructor()) { 11613 Expr *ArgExpr = E->getArg(0); 11614 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11615 if (ILE->getNumInits() == 1) 11616 ArgExpr = ILE->getInit(0); 11617 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11618 if (ICE->getCastKind() == CK_NoOp) 11619 ArgExpr = ICE->getSubExpr(); 11620 HandleValue(ArgExpr); 11621 return; 11622 } 11623 Inherited::VisitCXXConstructExpr(E); 11624 } 11625 11626 void VisitCallExpr(CallExpr *E) { 11627 // Treat std::move as a use. 11628 if (E->isCallToStdMove()) { 11629 HandleValue(E->getArg(0)); 11630 return; 11631 } 11632 11633 Inherited::VisitCallExpr(E); 11634 } 11635 11636 void VisitBinaryOperator(BinaryOperator *E) { 11637 if (E->isCompoundAssignmentOp()) { 11638 HandleValue(E->getLHS()); 11639 Visit(E->getRHS()); 11640 return; 11641 } 11642 11643 Inherited::VisitBinaryOperator(E); 11644 } 11645 11646 // A custom visitor for BinaryConditionalOperator is needed because the 11647 // regular visitor would check the condition and true expression separately 11648 // but both point to the same place giving duplicate diagnostics. 11649 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11650 Visit(E->getCond()); 11651 Visit(E->getFalseExpr()); 11652 } 11653 11654 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11655 Decl* ReferenceDecl = DRE->getDecl(); 11656 if (OrigDecl != ReferenceDecl) return; 11657 unsigned diag; 11658 if (isReferenceType) { 11659 diag = diag::warn_uninit_self_reference_in_reference_init; 11660 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11661 diag = diag::warn_static_self_reference_in_init; 11662 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11663 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11664 DRE->getDecl()->getType()->isRecordType()) { 11665 diag = diag::warn_uninit_self_reference_in_init; 11666 } else { 11667 // Local variables will be handled by the CFG analysis. 11668 return; 11669 } 11670 11671 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11672 S.PDiag(diag) 11673 << DRE->getDecl() << OrigDecl->getLocation() 11674 << DRE->getSourceRange()); 11675 } 11676 }; 11677 11678 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11679 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11680 bool DirectInit) { 11681 // Parameters arguments are occassionially constructed with itself, 11682 // for instance, in recursive functions. Skip them. 11683 if (isa<ParmVarDecl>(OrigDecl)) 11684 return; 11685 11686 E = E->IgnoreParens(); 11687 11688 // Skip checking T a = a where T is not a record or reference type. 11689 // Doing so is a way to silence uninitialized warnings. 11690 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11691 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11692 if (ICE->getCastKind() == CK_LValueToRValue) 11693 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11694 if (DRE->getDecl() == OrigDecl) 11695 return; 11696 11697 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11698 } 11699} // end anonymous namespace 11700 11701namespace { 11702 // Simple wrapper to add the name of a variable or (if no variable is 11703 // available) a DeclarationName into a diagnostic. 11704 struct VarDeclOrName { 11705 VarDecl *VDecl; 11706 DeclarationName Name; 11707 11708 friend const Sema::SemaDiagnosticBuilder & 11709 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11710 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11711 } 11712 }; 11713} // end anonymous namespace 11714 11715QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11716 DeclarationName Name, QualType Type, 11717 TypeSourceInfo *TSI, 11718 SourceRange Range, bool DirectInit, 11719 Expr *Init) { 11720 bool IsInitCapture = !VDecl; 11721 assert((!VDecl || !VDecl->isInitCapture()) &&(static_cast <bool> ((!VDecl || !VDecl->isInitCapture
()) && "init captures are expected to be deduced prior to initialization"
) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11722, __extension__ __PRETTY_FUNCTION__))
11722 "init captures are expected to be deduced prior to initialization")(static_cast <bool> ((!VDecl || !VDecl->isInitCapture
()) && "init captures are expected to be deduced prior to initialization"
) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11722, __extension__ __PRETTY_FUNCTION__))
; 11723 11724 VarDeclOrName VN{VDecl, Name}; 11725 11726 DeducedType *Deduced = Type->getContainedDeducedType(); 11727 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")(static_cast <bool> (Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? void (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11727, __extension__ __PRETTY_FUNCTION__))
; 11728 11729 // C++11 [dcl.spec.auto]p3 11730 if (!Init) { 11731 assert(VDecl && "no init for init capture deduction?")(static_cast <bool> (VDecl && "no init for init capture deduction?"
) ? void (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11731, __extension__ __PRETTY_FUNCTION__))
; 11732 11733 // Except for class argument deduction, and then for an initializing 11734 // declaration only, i.e. no static at class scope or extern. 11735 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11736 VDecl->hasExternalStorage() || 11737 VDecl->isStaticDataMember()) { 11738 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11739 << VDecl->getDeclName() << Type; 11740 return QualType(); 11741 } 11742 } 11743 11744 ArrayRef<Expr*> DeduceInits; 11745 if (Init) 11746 DeduceInits = Init; 11747 11748 if (DirectInit) { 11749 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11750 DeduceInits = PL->exprs(); 11751 } 11752 11753 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11754 assert(VDecl && "non-auto type for init capture deduction?")(static_cast <bool> (VDecl && "non-auto type for init capture deduction?"
) ? void (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11754, __extension__ __PRETTY_FUNCTION__))
; 11755 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11756 InitializationKind Kind = InitializationKind::CreateForInit( 11757 VDecl->getLocation(), DirectInit, Init); 11758 // FIXME: Initialization should not be taking a mutable list of inits. 11759 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11760 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11761 InitsCopy); 11762 } 11763 11764 if (DirectInit) { 11765 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11766 DeduceInits = IL->inits(); 11767 } 11768 11769 // Deduction only works if we have exactly one source expression. 11770 if (DeduceInits.empty()) { 11771 // It isn't possible to write this directly, but it is possible to 11772 // end up in this situation with "auto x(some_pack...);" 11773 Diag(Init->getBeginLoc(), IsInitCapture 11774 ? diag::err_init_capture_no_expression 11775 : diag::err_auto_var_init_no_expression) 11776 << VN << Type << Range; 11777 return QualType(); 11778 } 11779 11780 if (DeduceInits.size() > 1) { 11781 Diag(DeduceInits[1]->getBeginLoc(), 11782 IsInitCapture ? diag::err_init_capture_multiple_expressions 11783 : diag::err_auto_var_init_multiple_expressions) 11784 << VN << Type << Range; 11785 return QualType(); 11786 } 11787 11788 Expr *DeduceInit = DeduceInits[0]; 11789 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11790 Diag(Init->getBeginLoc(), IsInitCapture 11791 ? diag::err_init_capture_paren_braces 11792 : diag::err_auto_var_init_paren_braces) 11793 << isa<InitListExpr>(Init) << VN << Type << Range; 11794 return QualType(); 11795 } 11796 11797 // Expressions default to 'id' when we're in a debugger. 11798 bool DefaultedAnyToId = false; 11799 if (getLangOpts().DebuggerCastResultToId && 11800 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11801 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11802 if (Result.isInvalid()) { 11803 return QualType(); 11804 } 11805 Init = Result.get(); 11806 DefaultedAnyToId = true; 11807 } 11808 11809 // C++ [dcl.decomp]p1: 11810 // If the assignment-expression [...] has array type A and no ref-qualifier 11811 // is present, e has type cv A 11812 if (VDecl && isa<DecompositionDecl>(VDecl) && 11813 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11814 DeduceInit->getType()->isConstantArrayType()) 11815 return Context.getQualifiedType(DeduceInit->getType(), 11816 Type.getQualifiers()); 11817 11818 QualType DeducedType; 11819 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11820 if (!IsInitCapture) 11821 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11822 else if (isa<InitListExpr>(Init)) 11823 Diag(Range.getBegin(), 11824 diag::err_init_capture_deduction_failure_from_init_list) 11825 << VN 11826 << (DeduceInit->getType().isNull() ? TSI->getType() 11827 : DeduceInit->getType()) 11828 << DeduceInit->getSourceRange(); 11829 else 11830 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11831 << VN << TSI->getType() 11832 << (DeduceInit->getType().isNull() ? TSI->getType() 11833 : DeduceInit->getType()) 11834 << DeduceInit->getSourceRange(); 11835 } 11836 11837 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11838 // 'id' instead of a specific object type prevents most of our usual 11839 // checks. 11840 // We only want to warn outside of template instantiations, though: 11841 // inside a template, the 'id' could have come from a parameter. 11842 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11843 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11844 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11845 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11846 } 11847 11848 return DeducedType; 11849} 11850 11851bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11852 Expr *Init) { 11853 assert(!Init || !Init->containsErrors())(static_cast <bool> (!Init || !Init->containsErrors(
)) ? void (0) : __assert_fail ("!Init || !Init->containsErrors()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11853, __extension__ __PRETTY_FUNCTION__))
; 11854 QualType DeducedType = deduceVarTypeFromInitializer( 11855 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11856 VDecl->getSourceRange(), DirectInit, Init); 11857 if (DeducedType.isNull()) { 11858 VDecl->setInvalidDecl(); 11859 return true; 11860 } 11861 11862 VDecl->setType(DeducedType); 11863 assert(VDecl->isLinkageValid())(static_cast <bool> (VDecl->isLinkageValid()) ? void
(0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11863, __extension__ __PRETTY_FUNCTION__))
; 11864 11865 // In ARC, infer lifetime. 11866 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11867 VDecl->setInvalidDecl(); 11868 11869 if (getLangOpts().OpenCL) 11870 deduceOpenCLAddressSpace(VDecl); 11871 11872 // If this is a redeclaration, check that the type we just deduced matches 11873 // the previously declared type. 11874 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11875 // We never need to merge the type, because we cannot form an incomplete 11876 // array of auto, nor deduce such a type. 11877 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11878 } 11879 11880 // Check the deduced type is valid for a variable declaration. 11881 CheckVariableDeclarationType(VDecl); 11882 return VDecl->isInvalidDecl(); 11883} 11884 11885void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11886 SourceLocation Loc) { 11887 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11888 Init = EWC->getSubExpr(); 11889 11890 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11891 Init = CE->getSubExpr(); 11892 11893 QualType InitType = Init->getType(); 11894 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11896, __extension__ __PRETTY_FUNCTION__))
11895 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11896, __extension__ __PRETTY_FUNCTION__))
11896 "shouldn't be called if type doesn't have a non-trivial C struct")(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 11896, __extension__ __PRETTY_FUNCTION__))
; 11897 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11898 for (auto I : ILE->inits()) { 11899 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11900 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11901 continue; 11902 SourceLocation SL = I->getExprLoc(); 11903 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11904 } 11905 return; 11906 } 11907 11908 if (isa<ImplicitValueInitExpr>(Init)) { 11909 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11910 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11911 NTCUK_Init); 11912 } else { 11913 // Assume all other explicit initializers involving copying some existing 11914 // object. 11915 // TODO: ignore any explicit initializers where we can guarantee 11916 // copy-elision. 11917 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11918 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11919 } 11920} 11921 11922namespace { 11923 11924bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11925 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11926 // in the source code or implicitly by the compiler if it is in a union 11927 // defined in a system header and has non-trivial ObjC ownership 11928 // qualifications. We don't want those fields to participate in determining 11929 // whether the containing union is non-trivial. 11930 return FD->hasAttr<UnavailableAttr>(); 11931} 11932 11933struct DiagNonTrivalCUnionDefaultInitializeVisitor 11934 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11935 void> { 11936 using Super = 11937 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11938 void>; 11939 11940 DiagNonTrivalCUnionDefaultInitializeVisitor( 11941 QualType OrigTy, SourceLocation OrigLoc, 11942 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11943 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11944 11945 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11946 const FieldDecl *FD, bool InNonTrivialUnion) { 11947 if (const auto *AT = S.Context.getAsArrayType(QT)) 11948 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11949 InNonTrivialUnion); 11950 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11951 } 11952 11953 void visitARCStrong(QualType QT, const FieldDecl *FD, 11954 bool InNonTrivialUnion) { 11955 if (InNonTrivialUnion) 11956 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11957 << 1 << 0 << QT << FD->getName(); 11958 } 11959 11960 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11961 if (InNonTrivialUnion) 11962 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11963 << 1 << 0 << QT << FD->getName(); 11964 } 11965 11966 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11967 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11968 if (RD->isUnion()) { 11969 if (OrigLoc.isValid()) { 11970 bool IsUnion = false; 11971 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11972 IsUnion = OrigRD->isUnion(); 11973 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11974 << 0 << OrigTy << IsUnion << UseContext; 11975 // Reset OrigLoc so that this diagnostic is emitted only once. 11976 OrigLoc = SourceLocation(); 11977 } 11978 InNonTrivialUnion = true; 11979 } 11980 11981 if (InNonTrivialUnion) 11982 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11983 << 0 << 0 << QT.getUnqualifiedType() << ""; 11984 11985 for (const FieldDecl *FD : RD->fields()) 11986 if (!shouldIgnoreForRecordTriviality(FD)) 11987 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11988 } 11989 11990 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11991 11992 // The non-trivial C union type or the struct/union type that contains a 11993 // non-trivial C union. 11994 QualType OrigTy; 11995 SourceLocation OrigLoc; 11996 Sema::NonTrivialCUnionContext UseContext; 11997 Sema &S; 11998}; 11999 12000struct DiagNonTrivalCUnionDestructedTypeVisitor 12001 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12002 using Super = 12003 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12004 12005 DiagNonTrivalCUnionDestructedTypeVisitor( 12006 QualType OrigTy, SourceLocation OrigLoc, 12007 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12008 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12009 12010 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12011 const FieldDecl *FD, bool InNonTrivialUnion) { 12012 if (const auto *AT = S.Context.getAsArrayType(QT)) 12013 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12014 InNonTrivialUnion); 12015 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12016 } 12017 12018 void visitARCStrong(QualType QT, const FieldDecl *FD, 12019 bool InNonTrivialUnion) { 12020 if (InNonTrivialUnion) 12021 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12022 << 1 << 1 << QT << FD->getName(); 12023 } 12024 12025 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12026 if (InNonTrivialUnion) 12027 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12028 << 1 << 1 << QT << FD->getName(); 12029 } 12030 12031 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12032 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12033 if (RD->isUnion()) { 12034 if (OrigLoc.isValid()) { 12035 bool IsUnion = false; 12036 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12037 IsUnion = OrigRD->isUnion(); 12038 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12039 << 1 << OrigTy << IsUnion << UseContext; 12040 // Reset OrigLoc so that this diagnostic is emitted only once. 12041 OrigLoc = SourceLocation(); 12042 } 12043 InNonTrivialUnion = true; 12044 } 12045 12046 if (InNonTrivialUnion) 12047 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12048 << 0 << 1 << QT.getUnqualifiedType() << ""; 12049 12050 for (const FieldDecl *FD : RD->fields()) 12051 if (!shouldIgnoreForRecordTriviality(FD)) 12052 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12053 } 12054 12055 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12056 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12057 bool InNonTrivialUnion) {} 12058 12059 // The non-trivial C union type or the struct/union type that contains a 12060 // non-trivial C union. 12061 QualType OrigTy; 12062 SourceLocation OrigLoc; 12063 Sema::NonTrivialCUnionContext UseContext; 12064 Sema &S; 12065}; 12066 12067struct DiagNonTrivalCUnionCopyVisitor 12068 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12069 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12070 12071 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12072 Sema::NonTrivialCUnionContext UseContext, 12073 Sema &S) 12074 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12075 12076 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12077 const FieldDecl *FD, bool InNonTrivialUnion) { 12078 if (const auto *AT = S.Context.getAsArrayType(QT)) 12079 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12080 InNonTrivialUnion); 12081 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12082 } 12083 12084 void visitARCStrong(QualType QT, const FieldDecl *FD, 12085 bool InNonTrivialUnion) { 12086 if (InNonTrivialUnion) 12087 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12088 << 1 << 2 << QT << FD->getName(); 12089 } 12090 12091 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12092 if (InNonTrivialUnion) 12093 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12094 << 1 << 2 << QT << FD->getName(); 12095 } 12096 12097 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12098 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12099 if (RD->isUnion()) { 12100 if (OrigLoc.isValid()) { 12101 bool IsUnion = false; 12102 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12103 IsUnion = OrigRD->isUnion(); 12104 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12105 << 2 << OrigTy << IsUnion << UseContext; 12106 // Reset OrigLoc so that this diagnostic is emitted only once. 12107 OrigLoc = SourceLocation(); 12108 } 12109 InNonTrivialUnion = true; 12110 } 12111 12112 if (InNonTrivialUnion) 12113 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12114 << 0 << 2 << QT.getUnqualifiedType() << ""; 12115 12116 for (const FieldDecl *FD : RD->fields()) 12117 if (!shouldIgnoreForRecordTriviality(FD)) 12118 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12119 } 12120 12121 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12122 const FieldDecl *FD, bool InNonTrivialUnion) {} 12123 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12124 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12125 bool InNonTrivialUnion) {} 12126 12127 // The non-trivial C union type or the struct/union type that contains a 12128 // non-trivial C union. 12129 QualType OrigTy; 12130 SourceLocation OrigLoc; 12131 Sema::NonTrivialCUnionContext UseContext; 12132 Sema &S; 12133}; 12134 12135} // namespace 12136 12137void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12138 NonTrivialCUnionContext UseContext, 12139 unsigned NonTrivialKind) { 12140 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 12143, __extension__ __PRETTY_FUNCTION__))
12141 QT.hasNonTrivialToPrimitiveDestructCUnion() ||(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 12143, __extension__ __PRETTY_FUNCTION__))
12142 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 12143, __extension__ __PRETTY_FUNCTION__))
12143 "shouldn't be called if type doesn't have a non-trivial C union")(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 12143, __extension__ __PRETTY_FUNCTION__))
; 12144 12145 if ((NonTrivialKind & NTCUK_Init) && 12146 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12147 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12148 .visit(QT, nullptr, false); 12149 if ((NonTrivialKind & NTCUK_Destruct) && 12150 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12151 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12152 .visit(QT, nullptr, false); 12153 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12154 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12155 .visit(QT, nullptr, false); 12156} 12157 12158/// AddInitializerToDecl - Adds the initializer Init to the 12159/// declaration dcl. If DirectInit is true, this is C++ direct 12160/// initialization rather than copy initialization. 12161void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12162 // If there is no declaration, there was an error parsing it. Just ignore 12163 // the initializer. 12164 if (!RealDecl || RealDecl->isInvalidDecl()) { 12165 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12166 return; 12167 } 12168 12169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12170 // Pure-specifiers are handled in ActOnPureSpecifier. 12171 Diag(Method->getLocation(), diag::err_member_function_initialization) 12172 << Method->getDeclName() << Init->getSourceRange(); 12173 Method->setInvalidDecl(); 12174 return; 12175 } 12176 12177 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12178 if (!VDecl) { 12179 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")(static_cast <bool> (!isa<FieldDecl>(RealDecl) &&
"field init shouldn't get here") ? void (0) : __assert_fail (
"!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 12179, __extension__ __PRETTY_FUNCTION__))
; 12180 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12181 RealDecl->setInvalidDecl(); 12182 return; 12183 } 12184 12185 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12186 if (VDecl->getType()->isUndeducedType()) { 12187 // Attempt typo correction early so that the type of the init expression can 12188 // be deduced based on the chosen correction if the original init contains a 12189 // TypoExpr. 12190 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12191 if (!Res.isUsable()) { 12192 // There are unresolved typos in Init, just drop them. 12193 // FIXME: improve the recovery strategy to preserve the Init. 12194 RealDecl->setInvalidDecl(); 12195 return; 12196 } 12197 if (Res.get()->containsErrors()) { 12198 // Invalidate the decl as we don't know the type for recovery-expr yet. 12199 RealDecl->setInvalidDecl(); 12200 VDecl->setInit(Res.get()); 12201 return; 12202 } 12203 Init = Res.get(); 12204 12205 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12206 return; 12207 } 12208 12209 // dllimport cannot be used on variable definitions. 12210 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12211 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12212 VDecl->setInvalidDecl(); 12213 return; 12214 } 12215 12216 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12217 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12218 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12219 VDecl->setInvalidDecl(); 12220 return; 12221 } 12222 12223 if (!VDecl->getType()->isDependentType()) { 12224 // A definition must end up with a complete type, which means it must be 12225 // complete with the restriction that an array type might be completed by 12226 // the initializer; note that later code assumes this restriction. 12227 QualType BaseDeclType = VDecl->getType(); 12228 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12229 BaseDeclType = Array->getElementType(); 12230 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12231 diag::err_typecheck_decl_incomplete_type)) { 12232 RealDecl->setInvalidDecl(); 12233 return; 12234 } 12235 12236 // The variable can not have an abstract class type. 12237 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12238 diag::err_abstract_type_in_decl, 12239 AbstractVariableType)) 12240 VDecl->setInvalidDecl(); 12241 } 12242 12243 // If adding the initializer will turn this declaration into a definition, 12244 // and we already have a definition for this variable, diagnose or otherwise 12245 // handle the situation. 12246 if (VarDecl *Def = VDecl->getDefinition()) 12247 if (Def != VDecl && 12248 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12249 !VDecl->isThisDeclarationADemotedDefinition() && 12250 checkVarDeclRedefinition(Def, VDecl)) 12251 return; 12252 12253 if (getLangOpts().CPlusPlus) { 12254 // C++ [class.static.data]p4 12255 // If a static data member is of const integral or const 12256 // enumeration type, its declaration in the class definition can 12257 // specify a constant-initializer which shall be an integral 12258 // constant expression (5.19). In that case, the member can appear 12259 // in integral constant expressions. The member shall still be 12260 // defined in a namespace scope if it is used in the program and the 12261 // namespace scope definition shall not contain an initializer. 12262 // 12263 // We already performed a redefinition check above, but for static 12264 // data members we also need to check whether there was an in-class 12265 // declaration with an initializer. 12266 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12267 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12268 << VDecl->getDeclName(); 12269 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12270 diag::note_previous_initializer) 12271 << 0; 12272 return; 12273 } 12274 12275 if (VDecl->hasLocalStorage()) 12276 setFunctionHasBranchProtectedScope(); 12277 12278 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12279 VDecl->setInvalidDecl(); 12280 return; 12281 } 12282 } 12283 12284 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12285 // a kernel function cannot be initialized." 12286 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12287 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12288 VDecl->setInvalidDecl(); 12289 return; 12290 } 12291 12292 // The LoaderUninitialized attribute acts as a definition (of undef). 12293 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12294 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12295 VDecl->setInvalidDecl(); 12296 return; 12297 } 12298 12299 // Get the decls type and save a reference for later, since 12300 // CheckInitializerTypes may change it. 12301 QualType DclT = VDecl->getType(), SavT = DclT; 12302 12303 // Expressions default to 'id' when we're in a debugger 12304 // and we are assigning it to a variable of Objective-C pointer type. 12305 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12306 Init->getType() == Context.UnknownAnyTy) { 12307 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12308 if (Result.isInvalid()) { 12309 VDecl->setInvalidDecl(); 12310 return; 12311 } 12312 Init = Result.get(); 12313 } 12314 12315 // Perform the initialization. 12316 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12317 if (!VDecl->isInvalidDecl()) { 12318 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12319 InitializationKind Kind = InitializationKind::CreateForInit( 12320 VDecl->getLocation(), DirectInit, Init); 12321 12322 MultiExprArg Args = Init; 12323 if (CXXDirectInit) 12324 Args = MultiExprArg(CXXDirectInit->getExprs(), 12325 CXXDirectInit->getNumExprs()); 12326 12327 // Try to correct any TypoExprs in the initialization arguments. 12328 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12329 ExprResult Res = CorrectDelayedTyposInExpr( 12330 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12331 [this, Entity, Kind](Expr *E) { 12332 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12333 return Init.Failed() ? ExprError() : E; 12334 }); 12335 if (Res.isInvalid()) { 12336 VDecl->setInvalidDecl(); 12337 } else if (Res.get() != Args[Idx]) { 12338 Args[Idx] = Res.get(); 12339 } 12340 } 12341 if (VDecl->isInvalidDecl()) 12342 return; 12343 12344 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12345 /*TopLevelOfInitList=*/false, 12346 /*TreatUnavailableAsInvalid=*/false); 12347 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12348 if (Result.isInvalid()) { 12349 // If the provied initializer fails to initialize the var decl, 12350 // we attach a recovery expr for better recovery. 12351 auto RecoveryExpr = 12352 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12353 if (RecoveryExpr.get()) 12354 VDecl->setInit(RecoveryExpr.get()); 12355 return; 12356 } 12357 12358 Init = Result.getAs<Expr>(); 12359 } 12360 12361 // Check for self-references within variable initializers. 12362 // Variables declared within a function/method body (except for references) 12363 // are handled by a dataflow analysis. 12364 // This is undefined behavior in C++, but valid in C. 12365 if (getLangOpts().CPlusPlus) 12366 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12367 VDecl->getType()->isReferenceType()) 12368 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12369 12370 // If the type changed, it means we had an incomplete type that was 12371 // completed by the initializer. For example: 12372 // int ary[] = { 1, 3, 5 }; 12373 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12374 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12375 VDecl->setType(DclT); 12376 12377 if (!VDecl->isInvalidDecl()) { 12378 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12379 12380 if (VDecl->hasAttr<BlocksAttr>()) 12381 checkRetainCycles(VDecl, Init); 12382 12383 // It is safe to assign a weak reference into a strong variable. 12384 // Although this code can still have problems: 12385 // id x = self.weakProp; 12386 // id y = self.weakProp; 12387 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12388 // paths through the function. This should be revisited if 12389 // -Wrepeated-use-of-weak is made flow-sensitive. 12390 if (FunctionScopeInfo *FSI = getCurFunction()) 12391 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12392 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12393 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12394 Init->getBeginLoc())) 12395 FSI->markSafeWeakUse(Init); 12396 } 12397 12398 // The initialization is usually a full-expression. 12399 // 12400 // FIXME: If this is a braced initialization of an aggregate, it is not 12401 // an expression, and each individual field initializer is a separate 12402 // full-expression. For instance, in: 12403 // 12404 // struct Temp { ~Temp(); }; 12405 // struct S { S(Temp); }; 12406 // struct T { S a, b; } t = { Temp(), Temp() } 12407 // 12408 // we should destroy the first Temp before constructing the second. 12409 ExprResult Result = 12410 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12411 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12412 if (Result.isInvalid()) { 12413 VDecl->setInvalidDecl(); 12414 return; 12415 } 12416 Init = Result.get(); 12417 12418 // Attach the initializer to the decl. 12419 VDecl->setInit(Init); 12420 12421 if (VDecl->isLocalVarDecl()) { 12422 // Don't check the initializer if the declaration is malformed. 12423 if (VDecl->isInvalidDecl()) { 12424 // do nothing 12425 12426 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12427 // This is true even in C++ for OpenCL. 12428 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12429 CheckForConstantInitializer(Init, DclT); 12430 12431 // Otherwise, C++ does not restrict the initializer. 12432 } else if (getLangOpts().CPlusPlus) { 12433 // do nothing 12434 12435 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12436 // static storage duration shall be constant expressions or string literals. 12437 } else if (VDecl->getStorageClass() == SC_Static) { 12438 CheckForConstantInitializer(Init, DclT); 12439 12440 // C89 is stricter than C99 for aggregate initializers. 12441 // C89 6.5.7p3: All the expressions [...] in an initializer list 12442 // for an object that has aggregate or union type shall be 12443 // constant expressions. 12444 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12445 isa<InitListExpr>(Init)) { 12446 const Expr *Culprit; 12447 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12448 Diag(Culprit->getExprLoc(), 12449 diag::ext_aggregate_init_not_constant) 12450 << Culprit->getSourceRange(); 12451 } 12452 } 12453 12454 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12455 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12456 if (VDecl->hasLocalStorage()) 12457 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12458 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12459 VDecl->getLexicalDeclContext()->isRecord()) { 12460 // This is an in-class initialization for a static data member, e.g., 12461 // 12462 // struct S { 12463 // static const int value = 17; 12464 // }; 12465 12466 // C++ [class.mem]p4: 12467 // A member-declarator can contain a constant-initializer only 12468 // if it declares a static member (9.4) of const integral or 12469 // const enumeration type, see 9.4.2. 12470 // 12471 // C++11 [class.static.data]p3: 12472 // If a non-volatile non-inline const static data member is of integral 12473 // or enumeration type, its declaration in the class definition can 12474 // specify a brace-or-equal-initializer in which every initializer-clause 12475 // that is an assignment-expression is a constant expression. A static 12476 // data member of literal type can be declared in the class definition 12477 // with the constexpr specifier; if so, its declaration shall specify a 12478 // brace-or-equal-initializer in which every initializer-clause that is 12479 // an assignment-expression is a constant expression. 12480 12481 // Do nothing on dependent types. 12482 if (DclT->isDependentType()) { 12483 12484 // Allow any 'static constexpr' members, whether or not they are of literal 12485 // type. We separately check that every constexpr variable is of literal 12486 // type. 12487 } else if (VDecl->isConstexpr()) { 12488 12489 // Require constness. 12490 } else if (!DclT.isConstQualified()) { 12491 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12492 << Init->getSourceRange(); 12493 VDecl->setInvalidDecl(); 12494 12495 // We allow integer constant expressions in all cases. 12496 } else if (DclT->isIntegralOrEnumerationType()) { 12497 // Check whether the expression is a constant expression. 12498 SourceLocation Loc; 12499 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12500 // In C++11, a non-constexpr const static data member with an 12501 // in-class initializer cannot be volatile. 12502 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12503 else if (Init->isValueDependent()) 12504 ; // Nothing to check. 12505 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12506 ; // Ok, it's an ICE! 12507 else if (Init->getType()->isScopedEnumeralType() && 12508 Init->isCXX11ConstantExpr(Context)) 12509 ; // Ok, it is a scoped-enum constant expression. 12510 else if (Init->isEvaluatable(Context)) { 12511 // If we can constant fold the initializer through heroics, accept it, 12512 // but report this as a use of an extension for -pedantic. 12513 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12514 << Init->getSourceRange(); 12515 } else { 12516 // Otherwise, this is some crazy unknown case. Report the issue at the 12517 // location provided by the isIntegerConstantExpr failed check. 12518 Diag(Loc, diag::err_in_class_initializer_non_constant) 12519 << Init->getSourceRange(); 12520 VDecl->setInvalidDecl(); 12521 } 12522 12523 // We allow foldable floating-point constants as an extension. 12524 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12525 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12526 // it anyway and provide a fixit to add the 'constexpr'. 12527 if (getLangOpts().CPlusPlus11) { 12528 Diag(VDecl->getLocation(), 12529 diag::ext_in_class_initializer_float_type_cxx11) 12530 << DclT << Init->getSourceRange(); 12531 Diag(VDecl->getBeginLoc(), 12532 diag::note_in_class_initializer_float_type_cxx11) 12533 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12534 } else { 12535 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12536 << DclT << Init->getSourceRange(); 12537 12538 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12539 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12540 << Init->getSourceRange(); 12541 VDecl->setInvalidDecl(); 12542 } 12543 } 12544 12545 // Suggest adding 'constexpr' in C++11 for literal types. 12546 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12547 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12548 << DclT << Init->getSourceRange() 12549 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12550 VDecl->setConstexpr(true); 12551 12552 } else { 12553 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12554 << DclT << Init->getSourceRange(); 12555 VDecl->setInvalidDecl(); 12556 } 12557 } else if (VDecl->isFileVarDecl()) { 12558 // In C, extern is typically used to avoid tentative definitions when 12559 // declaring variables in headers, but adding an intializer makes it a 12560 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12561 // In C++, extern is often used to give implictly static const variables 12562 // external linkage, so don't warn in that case. If selectany is present, 12563 // this might be header code intended for C and C++ inclusion, so apply the 12564 // C++ rules. 12565 if (VDecl->getStorageClass() == SC_Extern && 12566 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12567 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12568 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12569 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12570 Diag(VDecl->getLocation(), diag::warn_extern_init); 12571 12572 // In Microsoft C++ mode, a const variable defined in namespace scope has 12573 // external linkage by default if the variable is declared with 12574 // __declspec(dllexport). 12575 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12576 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12577 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12578 VDecl->setStorageClass(SC_Extern); 12579 12580 // C99 6.7.8p4. All file scoped initializers need to be constant. 12581 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12582 CheckForConstantInitializer(Init, DclT); 12583 } 12584 12585 QualType InitType = Init->getType(); 12586 if (!InitType.isNull() && 12587 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12588 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12589 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12590 12591 // We will represent direct-initialization similarly to copy-initialization: 12592 // int x(1); -as-> int x = 1; 12593 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12594 // 12595 // Clients that want to distinguish between the two forms, can check for 12596 // direct initializer using VarDecl::getInitStyle(). 12597 // A major benefit is that clients that don't particularly care about which 12598 // exactly form was it (like the CodeGen) can handle both cases without 12599 // special case code. 12600 12601 // C++ 8.5p11: 12602 // The form of initialization (using parentheses or '=') is generally 12603 // insignificant, but does matter when the entity being initialized has a 12604 // class type. 12605 if (CXXDirectInit) { 12606 assert(DirectInit && "Call-style initializer must be direct init.")(static_cast <bool> (DirectInit && "Call-style initializer must be direct init."
) ? void (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 12606, __extension__ __PRETTY_FUNCTION__))
; 12607 VDecl->setInitStyle(VarDecl::CallInit); 12608 } else if (DirectInit) { 12609 // This must be list-initialization. No other way is direct-initialization. 12610 VDecl->setInitStyle(VarDecl::ListInit); 12611 } 12612 12613 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12614 DeclsToCheckForDeferredDiags.insert(VDecl); 12615 CheckCompleteVariableDeclaration(VDecl); 12616} 12617 12618/// ActOnInitializerError - Given that there was an error parsing an 12619/// initializer for the given declaration, try to return to some form 12620/// of sanity. 12621void Sema::ActOnInitializerError(Decl *D) { 12622 // Our main concern here is re-establishing invariants like "a 12623 // variable's type is either dependent or complete". 12624 if (!D || D->isInvalidDecl()) return; 12625 12626 VarDecl *VD = dyn_cast<VarDecl>(D); 12627 if (!VD) return; 12628 12629 // Bindings are not usable if we can't make sense of the initializer. 12630 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12631 for (auto *BD : DD->bindings()) 12632 BD->setInvalidDecl(); 12633 12634 // Auto types are meaningless if we can't make sense of the initializer. 12635 if (VD->getType()->isUndeducedType()) { 12636 D->setInvalidDecl(); 12637 return; 12638 } 12639 12640 QualType Ty = VD->getType(); 12641 if (Ty->isDependentType()) return; 12642 12643 // Require a complete type. 12644 if (RequireCompleteType(VD->getLocation(), 12645 Context.getBaseElementType(Ty), 12646 diag::err_typecheck_decl_incomplete_type)) { 12647 VD->setInvalidDecl(); 12648 return; 12649 } 12650 12651 // Require a non-abstract type. 12652 if (RequireNonAbstractType(VD->getLocation(), Ty, 12653 diag::err_abstract_type_in_decl, 12654 AbstractVariableType)) { 12655 VD->setInvalidDecl(); 12656 return; 12657 } 12658 12659 // Don't bother complaining about constructors or destructors, 12660 // though. 12661} 12662 12663void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12664 // If there is no declaration, there was an error parsing it. Just ignore it. 12665 if (!RealDecl) 12666 return; 12667 12668 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12669 QualType Type = Var->getType(); 12670 12671 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12672 if (isa<DecompositionDecl>(RealDecl)) { 12673 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12674 Var->setInvalidDecl(); 12675 return; 12676 } 12677 12678 if (Type->isUndeducedType() && 12679 DeduceVariableDeclarationType(Var, false, nullptr)) 12680 return; 12681 12682 // C++11 [class.static.data]p3: A static data member can be declared with 12683 // the constexpr specifier; if so, its declaration shall specify 12684 // a brace-or-equal-initializer. 12685 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12686 // the definition of a variable [...] or the declaration of a static data 12687 // member. 12688 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12689 !Var->isThisDeclarationADemotedDefinition()) { 12690 if (Var->isStaticDataMember()) { 12691 // C++1z removes the relevant rule; the in-class declaration is always 12692 // a definition there. 12693 if (!getLangOpts().CPlusPlus17 && 12694 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12695 Diag(Var->getLocation(), 12696 diag::err_constexpr_static_mem_var_requires_init) 12697 << Var; 12698 Var->setInvalidDecl(); 12699 return; 12700 } 12701 } else { 12702 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12703 Var->setInvalidDecl(); 12704 return; 12705 } 12706 } 12707 12708 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12709 // be initialized. 12710 if (!Var->isInvalidDecl() && 12711 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12712 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12713 bool HasConstExprDefaultConstructor = false; 12714 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12715 for (auto *Ctor : RD->ctors()) { 12716 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12717 Ctor->getMethodQualifiers().getAddressSpace() == 12718 LangAS::opencl_constant) { 12719 HasConstExprDefaultConstructor = true; 12720 } 12721 } 12722 } 12723 if (!HasConstExprDefaultConstructor) { 12724 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12725 Var->setInvalidDecl(); 12726 return; 12727 } 12728 } 12729 12730 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12731 if (Var->getStorageClass() == SC_Extern) { 12732 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12733 << Var; 12734 Var->setInvalidDecl(); 12735 return; 12736 } 12737 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12738 diag::err_typecheck_decl_incomplete_type)) { 12739 Var->setInvalidDecl(); 12740 return; 12741 } 12742 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12743 if (!RD->hasTrivialDefaultConstructor()) { 12744 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12745 Var->setInvalidDecl(); 12746 return; 12747 } 12748 } 12749 // The declaration is unitialized, no need for further checks. 12750 return; 12751 } 12752 12753 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12754 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12755 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12756 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12757 NTCUC_DefaultInitializedObject, NTCUK_Init); 12758 12759 12760 switch (DefKind) { 12761 case VarDecl::Definition: 12762 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12763 break; 12764 12765 // We have an out-of-line definition of a static data member 12766 // that has an in-class initializer, so we type-check this like 12767 // a declaration. 12768 // 12769 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 12770 12771 case VarDecl::DeclarationOnly: 12772 // It's only a declaration. 12773 12774 // Block scope. C99 6.7p7: If an identifier for an object is 12775 // declared with no linkage (C99 6.2.2p6), the type for the 12776 // object shall be complete. 12777 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12778 !Var->hasLinkage() && !Var->isInvalidDecl() && 12779 RequireCompleteType(Var->getLocation(), Type, 12780 diag::err_typecheck_decl_incomplete_type)) 12781 Var->setInvalidDecl(); 12782 12783 // Make sure that the type is not abstract. 12784 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12785 RequireNonAbstractType(Var->getLocation(), Type, 12786 diag::err_abstract_type_in_decl, 12787 AbstractVariableType)) 12788 Var->setInvalidDecl(); 12789 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12790 Var->getStorageClass() == SC_PrivateExtern) { 12791 Diag(Var->getLocation(), diag::warn_private_extern); 12792 Diag(Var->getLocation(), diag::note_private_extern); 12793 } 12794 12795 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12796 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12797 ExternalDeclarations.push_back(Var); 12798 12799 return; 12800 12801 case VarDecl::TentativeDefinition: 12802 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12803 // object that has file scope without an initializer, and without a 12804 // storage-class specifier or with the storage-class specifier "static", 12805 // constitutes a tentative definition. Note: A tentative definition with 12806 // external linkage is valid (C99 6.2.2p5). 12807 if (!Var->isInvalidDecl()) { 12808 if (const IncompleteArrayType *ArrayT 12809 = Context.getAsIncompleteArrayType(Type)) { 12810 if (RequireCompleteSizedType( 12811 Var->getLocation(), ArrayT->getElementType(), 12812 diag::err_array_incomplete_or_sizeless_type)) 12813 Var->setInvalidDecl(); 12814 } else if (Var->getStorageClass() == SC_Static) { 12815 // C99 6.9.2p3: If the declaration of an identifier for an object is 12816 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12817 // declared type shall not be an incomplete type. 12818 // NOTE: code such as the following 12819 // static struct s; 12820 // struct s { int a; }; 12821 // is accepted by gcc. Hence here we issue a warning instead of 12822 // an error and we do not invalidate the static declaration. 12823 // NOTE: to avoid multiple warnings, only check the first declaration. 12824 if (Var->isFirstDecl()) 12825 RequireCompleteType(Var->getLocation(), Type, 12826 diag::ext_typecheck_decl_incomplete_type); 12827 } 12828 } 12829 12830 // Record the tentative definition; we're done. 12831 if (!Var->isInvalidDecl()) 12832 TentativeDefinitions.push_back(Var); 12833 return; 12834 } 12835 12836 // Provide a specific diagnostic for uninitialized variable 12837 // definitions with incomplete array type. 12838 if (Type->isIncompleteArrayType()) { 12839 Diag(Var->getLocation(), 12840 diag::err_typecheck_incomplete_array_needs_initializer); 12841 Var->setInvalidDecl(); 12842 return; 12843 } 12844 12845 // Provide a specific diagnostic for uninitialized variable 12846 // definitions with reference type. 12847 if (Type->isReferenceType()) { 12848 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12849 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 12850 Var->setInvalidDecl(); 12851 return; 12852 } 12853 12854 // Do not attempt to type-check the default initializer for a 12855 // variable with dependent type. 12856 if (Type->isDependentType()) 12857 return; 12858 12859 if (Var->isInvalidDecl()) 12860 return; 12861 12862 if (!Var->hasAttr<AliasAttr>()) { 12863 if (RequireCompleteType(Var->getLocation(), 12864 Context.getBaseElementType(Type), 12865 diag::err_typecheck_decl_incomplete_type)) { 12866 Var->setInvalidDecl(); 12867 return; 12868 } 12869 } else { 12870 return; 12871 } 12872 12873 // The variable can not have an abstract class type. 12874 if (RequireNonAbstractType(Var->getLocation(), Type, 12875 diag::err_abstract_type_in_decl, 12876 AbstractVariableType)) { 12877 Var->setInvalidDecl(); 12878 return; 12879 } 12880 12881 // Check for jumps past the implicit initializer. C++0x 12882 // clarifies that this applies to a "variable with automatic 12883 // storage duration", not a "local variable". 12884 // C++11 [stmt.dcl]p3 12885 // A program that jumps from a point where a variable with automatic 12886 // storage duration is not in scope to a point where it is in scope is 12887 // ill-formed unless the variable has scalar type, class type with a 12888 // trivial default constructor and a trivial destructor, a cv-qualified 12889 // version of one of these types, or an array of one of the preceding 12890 // types and is declared without an initializer. 12891 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12892 if (const RecordType *Record 12893 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12894 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12895 // Mark the function (if we're in one) for further checking even if the 12896 // looser rules of C++11 do not require such checks, so that we can 12897 // diagnose incompatibilities with C++98. 12898 if (!CXXRecord->isPOD()) 12899 setFunctionHasBranchProtectedScope(); 12900 } 12901 } 12902 // In OpenCL, we can't initialize objects in the __local address space, 12903 // even implicitly, so don't synthesize an implicit initializer. 12904 if (getLangOpts().OpenCL && 12905 Var->getType().getAddressSpace() == LangAS::opencl_local) 12906 return; 12907 // C++03 [dcl.init]p9: 12908 // If no initializer is specified for an object, and the 12909 // object is of (possibly cv-qualified) non-POD class type (or 12910 // array thereof), the object shall be default-initialized; if 12911 // the object is of const-qualified type, the underlying class 12912 // type shall have a user-declared default 12913 // constructor. Otherwise, if no initializer is specified for 12914 // a non- static object, the object and its subobjects, if 12915 // any, have an indeterminate initial value); if the object 12916 // or any of its subobjects are of const-qualified type, the 12917 // program is ill-formed. 12918 // C++0x [dcl.init]p11: 12919 // If no initializer is specified for an object, the object is 12920 // default-initialized; [...]. 12921 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12922 InitializationKind Kind 12923 = InitializationKind::CreateDefault(Var->getLocation()); 12924 12925 InitializationSequence InitSeq(*this, Entity, Kind, None); 12926 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12927 12928 if (Init.get()) { 12929 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12930 // This is important for template substitution. 12931 Var->setInitStyle(VarDecl::CallInit); 12932 } else if (Init.isInvalid()) { 12933 // If default-init fails, attach a recovery-expr initializer to track 12934 // that initialization was attempted and failed. 12935 auto RecoveryExpr = 12936 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12937 if (RecoveryExpr.get()) 12938 Var->setInit(RecoveryExpr.get()); 12939 } 12940 12941 CheckCompleteVariableDeclaration(Var); 12942 } 12943} 12944 12945void Sema::ActOnCXXForRangeDecl(Decl *D) { 12946 // If there is no declaration, there was an error parsing it. Ignore it. 12947 if (!D) 12948 return; 12949 12950 VarDecl *VD = dyn_cast<VarDecl>(D); 12951 if (!VD) { 12952 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12953 D->setInvalidDecl(); 12954 return; 12955 } 12956 12957 VD->setCXXForRangeDecl(true); 12958 12959 // for-range-declaration cannot be given a storage class specifier. 12960 int Error = -1; 12961 switch (VD->getStorageClass()) { 12962 case SC_None: 12963 break; 12964 case SC_Extern: 12965 Error = 0; 12966 break; 12967 case SC_Static: 12968 Error = 1; 12969 break; 12970 case SC_PrivateExtern: 12971 Error = 2; 12972 break; 12973 case SC_Auto: 12974 Error = 3; 12975 break; 12976 case SC_Register: 12977 Error = 4; 12978 break; 12979 } 12980 12981 // for-range-declaration cannot be given a storage class specifier con't. 12982 switch (VD->getTSCSpec()) { 12983 case TSCS_thread_local: 12984 Error = 6; 12985 break; 12986 case TSCS___thread: 12987 case TSCS__Thread_local: 12988 case TSCS_unspecified: 12989 break; 12990 } 12991 12992 if (Error != -1) { 12993 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12994 << VD << Error; 12995 D->setInvalidDecl(); 12996 } 12997} 12998 12999StmtResult 13000Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13001 IdentifierInfo *Ident, 13002 ParsedAttributes &Attrs, 13003 SourceLocation AttrEnd) { 13004 // C++1y [stmt.iter]p1: 13005 // A range-based for statement of the form 13006 // for ( for-range-identifier : for-range-initializer ) statement 13007 // is equivalent to 13008 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13009 DeclSpec DS(Attrs.getPool().getFactory()); 13010 13011 const char *PrevSpec; 13012 unsigned DiagID; 13013 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13014 getPrintingPolicy()); 13015 13016 Declarator D(DS, DeclaratorContext::ForInit); 13017 D.SetIdentifier(Ident, IdentLoc); 13018 D.takeAttributes(Attrs, AttrEnd); 13019 13020 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13021 IdentLoc); 13022 Decl *Var = ActOnDeclarator(S, D); 13023 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13024 FinalizeDeclaration(Var); 13025 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13026 AttrEnd.isValid() ? AttrEnd : IdentLoc); 13027} 13028 13029void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13030 if (var->isInvalidDecl()) return; 13031 13032 MaybeAddCUDAConstantAttr(var); 13033 13034 if (getLangOpts().OpenCL) { 13035 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13036 // initialiser 13037 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13038 !var->hasInit()) { 13039 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13040 << 1 /*Init*/; 13041 var->setInvalidDecl(); 13042 return; 13043 } 13044 } 13045 13046 // In Objective-C, don't allow jumps past the implicit initialization of a 13047 // local retaining variable. 13048 if (getLangOpts().ObjC && 13049 var->hasLocalStorage()) { 13050 switch (var->getType().getObjCLifetime()) { 13051 case Qualifiers::OCL_None: 13052 case Qualifiers::OCL_ExplicitNone: 13053 case Qualifiers::OCL_Autoreleasing: 13054 break; 13055 13056 case Qualifiers::OCL_Weak: 13057 case Qualifiers::OCL_Strong: 13058 setFunctionHasBranchProtectedScope(); 13059 break; 13060 } 13061 } 13062 13063 if (var->hasLocalStorage() && 13064 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13065 setFunctionHasBranchProtectedScope(); 13066 13067 // Warn about externally-visible variables being defined without a 13068 // prior declaration. We only want to do this for global 13069 // declarations, but we also specifically need to avoid doing it for 13070 // class members because the linkage of an anonymous class can 13071 // change if it's later given a typedef name. 13072 if (var->isThisDeclarationADefinition() && 13073 var->getDeclContext()->getRedeclContext()->isFileContext() && 13074 var->isExternallyVisible() && var->hasLinkage() && 13075 !var->isInline() && !var->getDescribedVarTemplate() && 13076 !isa<VarTemplatePartialSpecializationDecl>(var) && 13077 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13078 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13079 var->getLocation())) { 13080 // Find a previous declaration that's not a definition. 13081 VarDecl *prev = var->getPreviousDecl(); 13082 while (prev && prev->isThisDeclarationADefinition()) 13083 prev = prev->getPreviousDecl(); 13084 13085 if (!prev) { 13086 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13087 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13088 << /* variable */ 0; 13089 } 13090 } 13091 13092 // Cache the result of checking for constant initialization. 13093 Optional<bool> CacheHasConstInit; 13094 const Expr *CacheCulprit = nullptr; 13095 auto checkConstInit = [&]() mutable { 13096 if (!CacheHasConstInit) 13097 CacheHasConstInit = var->getInit()->isConstantInitializer( 13098 Context, var->getType()->isReferenceType(), &CacheCulprit); 13099 return *CacheHasConstInit; 13100 }; 13101 13102 if (var->getTLSKind() == VarDecl::TLS_Static) { 13103 if (var->getType().isDestructedType()) { 13104 // GNU C++98 edits for __thread, [basic.start.term]p3: 13105 // The type of an object with thread storage duration shall not 13106 // have a non-trivial destructor. 13107 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13108 if (getLangOpts().CPlusPlus11) 13109 Diag(var->getLocation(), diag::note_use_thread_local); 13110 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13111 if (!checkConstInit()) { 13112 // GNU C++98 edits for __thread, [basic.start.init]p4: 13113 // An object of thread storage duration shall not require dynamic 13114 // initialization. 13115 // FIXME: Need strict checking here. 13116 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13117 << CacheCulprit->getSourceRange(); 13118 if (getLangOpts().CPlusPlus11) 13119 Diag(var->getLocation(), diag::note_use_thread_local); 13120 } 13121 } 13122 } 13123 13124 13125 if (!var->getType()->isStructureType() && var->hasInit() && 13126 isa<InitListExpr>(var->getInit())) { 13127 const auto *ILE = cast<InitListExpr>(var->getInit()); 13128 unsigned NumInits = ILE->getNumInits(); 13129 if (NumInits > 2) 13130 for (unsigned I = 0; I < NumInits; ++I) { 13131 const auto *Init = ILE->getInit(I); 13132 if (!Init) 13133 break; 13134 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13135 if (!SL) 13136 break; 13137 13138 unsigned NumConcat = SL->getNumConcatenated(); 13139 // Diagnose missing comma in string array initialization. 13140 // Do not warn when all the elements in the initializer are concatenated 13141 // together. Do not warn for macros too. 13142 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13143 bool OnlyOneMissingComma = true; 13144 for (unsigned J = I + 1; J < NumInits; ++J) { 13145 const auto *Init = ILE->getInit(J); 13146 if (!Init) 13147 break; 13148 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13149 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13150 OnlyOneMissingComma = false; 13151 break; 13152 } 13153 } 13154 13155 if (OnlyOneMissingComma) { 13156 SmallVector<FixItHint, 1> Hints; 13157 for (unsigned i = 0; i < NumConcat - 1; ++i) 13158 Hints.push_back(FixItHint::CreateInsertion( 13159 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13160 13161 Diag(SL->getStrTokenLoc(1), 13162 diag::warn_concatenated_literal_array_init) 13163 << Hints; 13164 Diag(SL->getBeginLoc(), 13165 diag::note_concatenated_string_literal_silence); 13166 } 13167 // In any case, stop now. 13168 break; 13169 } 13170 } 13171 } 13172 13173 13174 QualType type = var->getType(); 13175 13176 if (var->hasAttr<BlocksAttr>()) 13177 getCurFunction()->addByrefBlockVar(var); 13178 13179 Expr *Init = var->getInit(); 13180 bool GlobalStorage = var->hasGlobalStorage(); 13181 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13182 QualType baseType = Context.getBaseElementType(type); 13183 bool HasConstInit = true; 13184 13185 // Check whether the initializer is sufficiently constant. 13186 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13187 !Init->isValueDependent() && 13188 (GlobalStorage || var->isConstexpr() || 13189 var->mightBeUsableInConstantExpressions(Context))) { 13190 // If this variable might have a constant initializer or might be usable in 13191 // constant expressions, check whether or not it actually is now. We can't 13192 // do this lazily, because the result might depend on things that change 13193 // later, such as which constexpr functions happen to be defined. 13194 SmallVector<PartialDiagnosticAt, 8> Notes; 13195 if (!getLangOpts().CPlusPlus11) { 13196 // Prior to C++11, in contexts where a constant initializer is required, 13197 // the set of valid constant initializers is described by syntactic rules 13198 // in [expr.const]p2-6. 13199 // FIXME: Stricter checking for these rules would be useful for constinit / 13200 // -Wglobal-constructors. 13201 HasConstInit = checkConstInit(); 13202 13203 // Compute and cache the constant value, and remember that we have a 13204 // constant initializer. 13205 if (HasConstInit) { 13206 (void)var->checkForConstantInitialization(Notes); 13207 Notes.clear(); 13208 } else if (CacheCulprit) { 13209 Notes.emplace_back(CacheCulprit->getExprLoc(), 13210 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13211 Notes.back().second << CacheCulprit->getSourceRange(); 13212 } 13213 } else { 13214 // Evaluate the initializer to see if it's a constant initializer. 13215 HasConstInit = var->checkForConstantInitialization(Notes); 13216 } 13217 13218 if (HasConstInit) { 13219 // FIXME: Consider replacing the initializer with a ConstantExpr. 13220 } else if (var->isConstexpr()) { 13221 SourceLocation DiagLoc = var->getLocation(); 13222 // If the note doesn't add any useful information other than a source 13223 // location, fold it into the primary diagnostic. 13224 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13225 diag::note_invalid_subexpr_in_const_expr) { 13226 DiagLoc = Notes[0].first; 13227 Notes.clear(); 13228 } 13229 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13230 << var << Init->getSourceRange(); 13231 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13232 Diag(Notes[I].first, Notes[I].second); 13233 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13234 auto *Attr = var->getAttr<ConstInitAttr>(); 13235 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13236 << Init->getSourceRange(); 13237 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13238 << Attr->getRange() << Attr->isConstinit(); 13239 for (auto &it : Notes) 13240 Diag(it.first, it.second); 13241 } else if (IsGlobal && 13242 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13243 var->getLocation())) { 13244 // Warn about globals which don't have a constant initializer. Don't 13245 // warn about globals with a non-trivial destructor because we already 13246 // warned about them. 13247 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13248 if (!(RD && !RD->hasTrivialDestructor())) { 13249 // checkConstInit() here permits trivial default initialization even in 13250 // C++11 onwards, where such an initializer is not a constant initializer 13251 // but nonetheless doesn't require a global constructor. 13252 if (!checkConstInit()) 13253 Diag(var->getLocation(), diag::warn_global_constructor) 13254 << Init->getSourceRange(); 13255 } 13256 } 13257 } 13258 13259 // Apply section attributes and pragmas to global variables. 13260 if (GlobalStorage && var->isThisDeclarationADefinition() && 13261 !inTemplateInstantiation()) { 13262 PragmaStack<StringLiteral *> *Stack = nullptr; 13263 int SectionFlags = ASTContext::PSF_Read; 13264 if (var->getType().isConstQualified()) { 13265 if (HasConstInit) 13266 Stack = &ConstSegStack; 13267 else { 13268 Stack = &BSSSegStack; 13269 SectionFlags |= ASTContext::PSF_Write; 13270 } 13271 } else if (var->hasInit() && HasConstInit) { 13272 Stack = &DataSegStack; 13273 SectionFlags |= ASTContext::PSF_Write; 13274 } else { 13275 Stack = &BSSSegStack; 13276 SectionFlags |= ASTContext::PSF_Write; 13277 } 13278 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13279 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13280 SectionFlags |= ASTContext::PSF_Implicit; 13281 UnifySection(SA->getName(), SectionFlags, var); 13282 } else if (Stack->CurrentValue) { 13283 SectionFlags |= ASTContext::PSF_Implicit; 13284 auto SectionName = Stack->CurrentValue->getString(); 13285 var->addAttr(SectionAttr::CreateImplicit( 13286 Context, SectionName, Stack->CurrentPragmaLocation, 13287 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13288 if (UnifySection(SectionName, SectionFlags, var)) 13289 var->dropAttr<SectionAttr>(); 13290 } 13291 13292 // Apply the init_seg attribute if this has an initializer. If the 13293 // initializer turns out to not be dynamic, we'll end up ignoring this 13294 // attribute. 13295 if (CurInitSeg && var->getInit()) 13296 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13297 CurInitSegLoc, 13298 AttributeCommonInfo::AS_Pragma)); 13299 } 13300 13301 // All the following checks are C++ only. 13302 if (!getLangOpts().CPlusPlus) { 13303 // If this variable must be emitted, add it as an initializer for the 13304 // current module. 13305 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13306 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13307 return; 13308 } 13309 13310 // Require the destructor. 13311 if (!type->isDependentType()) 13312 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13313 FinalizeVarWithDestructor(var, recordType); 13314 13315 // If this variable must be emitted, add it as an initializer for the current 13316 // module. 13317 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13318 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13319 13320 // Build the bindings if this is a structured binding declaration. 13321 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13322 CheckCompleteDecompositionDeclaration(DD); 13323} 13324 13325/// Check if VD needs to be dllexport/dllimport due to being in a 13326/// dllexport/import function. 13327void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13328 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 13328, __extension__ __PRETTY_FUNCTION__))
; 13329 13330 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13331 13332 // Find outermost function when VD is in lambda function. 13333 while (FD && !getDLLAttr(FD) && 13334 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13335 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13336 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13337 } 13338 13339 if (!FD) 13340 return; 13341 13342 // Static locals inherit dll attributes from their function. 13343 if (Attr *A = getDLLAttr(FD)) { 13344 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13345 NewAttr->setInherited(true); 13346 VD->addAttr(NewAttr); 13347 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13348 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13349 NewAttr->setInherited(true); 13350 VD->addAttr(NewAttr); 13351 13352 // Export this function to enforce exporting this static variable even 13353 // if it is not used in this compilation unit. 13354 if (!FD->hasAttr<DLLExportAttr>()) 13355 FD->addAttr(NewAttr); 13356 13357 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13358 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13359 NewAttr->setInherited(true); 13360 VD->addAttr(NewAttr); 13361 } 13362} 13363 13364/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13365/// any semantic actions necessary after any initializer has been attached. 13366void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13367 // Note that we are no longer parsing the initializer for this declaration. 13368 ParsingInitForAutoVars.erase(ThisDecl); 13369 13370 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13371 if (!VD) 13372 return; 13373 13374 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13375 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13376 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13377 if (PragmaClangBSSSection.Valid) 13378 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13379 Context, PragmaClangBSSSection.SectionName, 13380 PragmaClangBSSSection.PragmaLocation, 13381 AttributeCommonInfo::AS_Pragma)); 13382 if (PragmaClangDataSection.Valid) 13383 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13384 Context, PragmaClangDataSection.SectionName, 13385 PragmaClangDataSection.PragmaLocation, 13386 AttributeCommonInfo::AS_Pragma)); 13387 if (PragmaClangRodataSection.Valid) 13388 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13389 Context, PragmaClangRodataSection.SectionName, 13390 PragmaClangRodataSection.PragmaLocation, 13391 AttributeCommonInfo::AS_Pragma)); 13392 if (PragmaClangRelroSection.Valid) 13393 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13394 Context, PragmaClangRelroSection.SectionName, 13395 PragmaClangRelroSection.PragmaLocation, 13396 AttributeCommonInfo::AS_Pragma)); 13397 } 13398 13399 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13400 for (auto *BD : DD->bindings()) { 13401 FinalizeDeclaration(BD); 13402 } 13403 } 13404 13405 checkAttributesAfterMerging(*this, *VD); 13406 13407 // Perform TLS alignment check here after attributes attached to the variable 13408 // which may affect the alignment have been processed. Only perform the check 13409 // if the target has a maximum TLS alignment (zero means no constraints). 13410 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13411 // Protect the check so that it's not performed on dependent types and 13412 // dependent alignments (we can't determine the alignment in that case). 13413 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13414 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13415 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13416 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13417 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13418 << (unsigned)MaxAlignChars.getQuantity(); 13419 } 13420 } 13421 } 13422 13423 if (VD->isStaticLocal()) 13424 CheckStaticLocalForDllExport(VD); 13425 13426 // Perform check for initializers of device-side global variables. 13427 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13428 // 7.5). We must also apply the same checks to all __shared__ 13429 // variables whether they are local or not. CUDA also allows 13430 // constant initializers for __constant__ and __device__ variables. 13431 if (getLangOpts().CUDA) 13432 checkAllowedCUDAInitializer(VD); 13433 13434 // Grab the dllimport or dllexport attribute off of the VarDecl. 13435 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13436 13437 // Imported static data members cannot be defined out-of-line. 13438 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13439 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13440 VD->isThisDeclarationADefinition()) { 13441 // We allow definitions of dllimport class template static data members 13442 // with a warning. 13443 CXXRecordDecl *Context = 13444 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13445 bool IsClassTemplateMember = 13446 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13447 Context->getDescribedClassTemplate(); 13448 13449 Diag(VD->getLocation(), 13450 IsClassTemplateMember 13451 ? diag::warn_attribute_dllimport_static_field_definition 13452 : diag::err_attribute_dllimport_static_field_definition); 13453 Diag(IA->getLocation(), diag::note_attribute); 13454 if (!IsClassTemplateMember) 13455 VD->setInvalidDecl(); 13456 } 13457 } 13458 13459 // dllimport/dllexport variables cannot be thread local, their TLS index 13460 // isn't exported with the variable. 13461 if (DLLAttr && VD->getTLSKind()) { 13462 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13463 if (F && getDLLAttr(F)) { 13464 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 13464, __extension__ __PRETTY_FUNCTION__))
; 13465 // But if this is a static local in a dlimport/dllexport function, the 13466 // function will never be inlined, which means the var would never be 13467 // imported, so having it marked import/export is safe. 13468 } else { 13469 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13470 << DLLAttr; 13471 VD->setInvalidDecl(); 13472 } 13473 } 13474 13475 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13476 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13477 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13478 << Attr; 13479 VD->dropAttr<UsedAttr>(); 13480 } 13481 } 13482 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13483 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13484 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13485 << Attr; 13486 VD->dropAttr<RetainAttr>(); 13487 } 13488 } 13489 13490 const DeclContext *DC = VD->getDeclContext(); 13491 // If there's a #pragma GCC visibility in scope, and this isn't a class 13492 // member, set the visibility of this variable. 13493 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13494 AddPushedVisibilityAttribute(VD); 13495 13496 // FIXME: Warn on unused var template partial specializations. 13497 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13498 MarkUnusedFileScopedDecl(VD); 13499 13500 // Now we have parsed the initializer and can update the table of magic 13501 // tag values. 13502 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13503 !VD->getType()->isIntegralOrEnumerationType()) 13504 return; 13505 13506 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13507 const Expr *MagicValueExpr = VD->getInit(); 13508 if (!MagicValueExpr) { 13509 continue; 13510 } 13511 Optional<llvm::APSInt> MagicValueInt; 13512 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13513 Diag(I->getRange().getBegin(), 13514 diag::err_type_tag_for_datatype_not_ice) 13515 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13516 continue; 13517 } 13518 if (MagicValueInt->getActiveBits() > 64) { 13519 Diag(I->getRange().getBegin(), 13520 diag::err_type_tag_for_datatype_too_large) 13521 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13522 continue; 13523 } 13524 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13525 RegisterTypeTagForDatatype(I->getArgumentKind(), 13526 MagicValue, 13527 I->getMatchingCType(), 13528 I->getLayoutCompatible(), 13529 I->getMustBeNull()); 13530 } 13531} 13532 13533static bool hasDeducedAuto(DeclaratorDecl *DD) { 13534 auto *VD = dyn_cast<VarDecl>(DD); 13535 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13536} 13537 13538Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13539 ArrayRef<Decl *> Group) { 13540 SmallVector<Decl*, 8> Decls; 13541 13542 if (DS.isTypeSpecOwned()) 13543 Decls.push_back(DS.getRepAsDecl()); 13544 13545 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13546 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13547 bool DiagnosedMultipleDecomps = false; 13548 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13549 bool DiagnosedNonDeducedAuto = false; 13550 13551 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13552 if (Decl *D = Group[i]) { 13553 // For declarators, there are some additional syntactic-ish checks we need 13554 // to perform. 13555 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13556 if (!FirstDeclaratorInGroup) 13557 FirstDeclaratorInGroup = DD; 13558 if (!FirstDecompDeclaratorInGroup) 13559 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13560 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13561 !hasDeducedAuto(DD)) 13562 FirstNonDeducedAutoInGroup = DD; 13563 13564 if (FirstDeclaratorInGroup != DD) { 13565 // A decomposition declaration cannot be combined with any other 13566 // declaration in the same group. 13567 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13568 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13569 diag::err_decomp_decl_not_alone) 13570 << FirstDeclaratorInGroup->getSourceRange() 13571 << DD->getSourceRange(); 13572 DiagnosedMultipleDecomps = true; 13573 } 13574 13575 // A declarator that uses 'auto' in any way other than to declare a 13576 // variable with a deduced type cannot be combined with any other 13577 // declarator in the same group. 13578 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13579 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13580 diag::err_auto_non_deduced_not_alone) 13581 << FirstNonDeducedAutoInGroup->getType() 13582 ->hasAutoForTrailingReturnType() 13583 << FirstDeclaratorInGroup->getSourceRange() 13584 << DD->getSourceRange(); 13585 DiagnosedNonDeducedAuto = true; 13586 } 13587 } 13588 } 13589 13590 Decls.push_back(D); 13591 } 13592 } 13593 13594 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13595 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13596 handleTagNumbering(Tag, S); 13597 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13598 getLangOpts().CPlusPlus) 13599 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13600 } 13601 } 13602 13603 return BuildDeclaratorGroup(Decls); 13604} 13605 13606/// BuildDeclaratorGroup - convert a list of declarations into a declaration 13607/// group, performing any necessary semantic checking. 13608Sema::DeclGroupPtrTy 13609Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13610 // C++14 [dcl.spec.auto]p7: (DR1347) 13611 // If the type that replaces the placeholder type is not the same in each 13612 // deduction, the program is ill-formed. 13613 if (Group.size() > 1) { 13614 QualType Deduced; 13615 VarDecl *DeducedDecl = nullptr; 13616 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13617 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13618 if (!D || D->isInvalidDecl()) 13619 break; 13620 DeducedType *DT = D->getType()->getContainedDeducedType(); 13621 if (!DT || DT->getDeducedType().isNull()) 13622 continue; 13623 if (Deduced.isNull()) { 13624 Deduced = DT->getDeducedType(); 13625 DeducedDecl = D; 13626 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13627 auto *AT = dyn_cast<AutoType>(DT); 13628 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13629 diag::err_auto_different_deductions) 13630 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13631 << DeducedDecl->getDeclName() << DT->getDeducedType() 13632 << D->getDeclName(); 13633 if (DeducedDecl->hasInit()) 13634 Dia << DeducedDecl->getInit()->getSourceRange(); 13635 if (D->getInit()) 13636 Dia << D->getInit()->getSourceRange(); 13637 D->setInvalidDecl(); 13638 break; 13639 } 13640 } 13641 } 13642 13643 ActOnDocumentableDecls(Group); 13644 13645 return DeclGroupPtrTy::make( 13646 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13647} 13648 13649void Sema::ActOnDocumentableDecl(Decl *D) { 13650 ActOnDocumentableDecls(D); 13651} 13652 13653void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13654 // Don't parse the comment if Doxygen diagnostics are ignored. 13655 if (Group.empty() || !Group[0]) 13656 return; 13657 13658 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13659 Group[0]->getLocation()) && 13660 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13661 Group[0]->getLocation())) 13662 return; 13663 13664 if (Group.size() >= 2) { 13665 // This is a decl group. Normally it will contain only declarations 13666 // produced from declarator list. But in case we have any definitions or 13667 // additional declaration references: 13668 // 'typedef struct S {} S;' 13669 // 'typedef struct S *S;' 13670 // 'struct S *pS;' 13671 // FinalizeDeclaratorGroup adds these as separate declarations. 13672 Decl *MaybeTagDecl = Group[0]; 13673 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13674 Group = Group.slice(1); 13675 } 13676 } 13677 13678 // FIMXE: We assume every Decl in the group is in the same file. 13679 // This is false when preprocessor constructs the group from decls in 13680 // different files (e. g. macros or #include). 13681 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13682} 13683 13684/// Common checks for a parameter-declaration that should apply to both function 13685/// parameters and non-type template parameters. 13686void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13687 // Check that there are no default arguments inside the type of this 13688 // parameter. 13689 if (getLangOpts().CPlusPlus) 13690 CheckExtraCXXDefaultArguments(D); 13691 13692 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13693 if (D.getCXXScopeSpec().isSet()) { 13694 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13695 << D.getCXXScopeSpec().getRange(); 13696 } 13697 13698 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13699 // simple identifier except [...irrelevant cases...]. 13700 switch (D.getName().getKind()) { 13701 case UnqualifiedIdKind::IK_Identifier: 13702 break; 13703 13704 case UnqualifiedIdKind::IK_OperatorFunctionId: 13705 case UnqualifiedIdKind::IK_ConversionFunctionId: 13706 case UnqualifiedIdKind::IK_LiteralOperatorId: 13707 case UnqualifiedIdKind::IK_ConstructorName: 13708 case UnqualifiedIdKind::IK_DestructorName: 13709 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13710 case UnqualifiedIdKind::IK_DeductionGuideName: 13711 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13712 << GetNameForDeclarator(D).getName(); 13713 break; 13714 13715 case UnqualifiedIdKind::IK_TemplateId: 13716 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13717 // GetNameForDeclarator would not produce a useful name in this case. 13718 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13719 break; 13720 } 13721} 13722 13723/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13724/// to introduce parameters into function prototype scope. 13725Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13726 const DeclSpec &DS = D.getDeclSpec(); 13727 13728 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13729 13730 // C++03 [dcl.stc]p2 also permits 'auto'. 13731 StorageClass SC = SC_None; 13732 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13733 SC = SC_Register; 13734 // In C++11, the 'register' storage class specifier is deprecated. 13735 // In C++17, it is not allowed, but we tolerate it as an extension. 13736 if (getLangOpts().CPlusPlus11) { 13737 Diag(DS.getStorageClassSpecLoc(), 13738 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13739 : diag::warn_deprecated_register) 13740 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13741 } 13742 } else if (getLangOpts().CPlusPlus && 13743 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13744 SC = SC_Auto; 13745 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13746 Diag(DS.getStorageClassSpecLoc(), 13747 diag::err_invalid_storage_class_in_func_decl); 13748 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13749 } 13750 13751 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13752 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13753 << DeclSpec::getSpecifierName(TSCS); 13754 if (DS.isInlineSpecified()) 13755 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13756 << getLangOpts().CPlusPlus17; 13757 if (DS.hasConstexprSpecifier()) 13758 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13759 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13760 13761 DiagnoseFunctionSpecifiers(DS); 13762 13763 CheckFunctionOrTemplateParamDeclarator(S, D); 13764 13765 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13766 QualType parmDeclType = TInfo->getType(); 13767 13768 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13769 IdentifierInfo *II = D.getIdentifier(); 13770 if (II) { 13771 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13772 ForVisibleRedeclaration); 13773 LookupName(R, S); 13774 if (R.isSingleResult()) { 13775 NamedDecl *PrevDecl = R.getFoundDecl(); 13776 if (PrevDecl->isTemplateParameter()) { 13777 // Maybe we will complain about the shadowed template parameter. 13778 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13779 // Just pretend that we didn't see the previous declaration. 13780 PrevDecl = nullptr; 13781 } else if (S->isDeclScope(PrevDecl)) { 13782 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13783 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13784 13785 // Recover by removing the name 13786 II = nullptr; 13787 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13788 D.setInvalidType(true); 13789 } 13790 } 13791 } 13792 13793 // Temporarily put parameter variables in the translation unit, not 13794 // the enclosing context. This prevents them from accidentally 13795 // looking like class members in C++. 13796 ParmVarDecl *New = 13797 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13798 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13799 13800 if (D.isInvalidType()) 13801 New->setInvalidDecl(); 13802 13803 assert(S->isFunctionPrototypeScope())(static_cast <bool> (S->isFunctionPrototypeScope()) ?
void (0) : __assert_fail ("S->isFunctionPrototypeScope()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 13803, __extension__ __PRETTY_FUNCTION__))
; 13804 assert(S->getFunctionPrototypeDepth() >= 1)(static_cast <bool> (S->getFunctionPrototypeDepth() >=
1) ? void (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 13804, __extension__ __PRETTY_FUNCTION__))
; 13805 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13806 S->getNextFunctionPrototypeIndex()); 13807 13808 // Add the parameter declaration into this scope. 13809 S->AddDecl(New); 13810 if (II) 13811 IdResolver.AddDecl(New); 13812 13813 ProcessDeclAttributes(S, New, D); 13814 13815 if (D.getDeclSpec().isModulePrivateSpecified()) 13816 Diag(New->getLocation(), diag::err_module_private_local) 13817 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13818 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13819 13820 if (New->hasAttr<BlocksAttr>()) { 13821 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13822 } 13823 13824 if (getLangOpts().OpenCL) 13825 deduceOpenCLAddressSpace(New); 13826 13827 return New; 13828} 13829 13830/// Synthesizes a variable for a parameter arising from a 13831/// typedef. 13832ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13833 SourceLocation Loc, 13834 QualType T) { 13835 /* FIXME: setting StartLoc == Loc. 13836 Would it be worth to modify callers so as to provide proper source 13837 location for the unnamed parameters, embedding the parameter's type? */ 13838 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13839 T, Context.getTrivialTypeSourceInfo(T, Loc), 13840 SC_None, nullptr); 13841 Param->setImplicit(); 13842 return Param; 13843} 13844 13845void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13846 // Don't diagnose unused-parameter errors in template instantiations; we 13847 // will already have done so in the template itself. 13848 if (inTemplateInstantiation()) 13849 return; 13850 13851 for (const ParmVarDecl *Parameter : Parameters) { 13852 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13853 !Parameter->hasAttr<UnusedAttr>()) { 13854 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13855 << Parameter->getDeclName(); 13856 } 13857 } 13858} 13859 13860void Sema::DiagnoseSizeOfParametersAndReturnValue( 13861 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13862 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13863 return; 13864 13865 // Warn if the return value is pass-by-value and larger than the specified 13866 // threshold. 13867 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13868 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13869 if (Size > LangOpts.NumLargeByValueCopy) 13870 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 13871 } 13872 13873 // Warn if any parameter is pass-by-value and larger than the specified 13874 // threshold. 13875 for (const ParmVarDecl *Parameter : Parameters) { 13876 QualType T = Parameter->getType(); 13877 if (T->isDependentType() || !T.isPODType(Context)) 13878 continue; 13879 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13880 if (Size > LangOpts.NumLargeByValueCopy) 13881 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13882 << Parameter << Size; 13883 } 13884} 13885 13886ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13887 SourceLocation NameLoc, IdentifierInfo *Name, 13888 QualType T, TypeSourceInfo *TSInfo, 13889 StorageClass SC) { 13890 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13891 if (getLangOpts().ObjCAutoRefCount && 13892 T.getObjCLifetime() == Qualifiers::OCL_None && 13893 T->isObjCLifetimeType()) { 13894 13895 Qualifiers::ObjCLifetime lifetime; 13896 13897 // Special cases for arrays: 13898 // - if it's const, use __unsafe_unretained 13899 // - otherwise, it's an error 13900 if (T->isArrayType()) { 13901 if (!T.isConstQualified()) { 13902 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13903 DelayedDiagnostics.add( 13904 sema::DelayedDiagnostic::makeForbiddenType( 13905 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13906 else 13907 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13908 << TSInfo->getTypeLoc().getSourceRange(); 13909 } 13910 lifetime = Qualifiers::OCL_ExplicitNone; 13911 } else { 13912 lifetime = T->getObjCARCImplicitLifetime(); 13913 } 13914 T = Context.getLifetimeQualifiedType(T, lifetime); 13915 } 13916 13917 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13918 Context.getAdjustedParameterType(T), 13919 TSInfo, SC, nullptr); 13920 13921 // Make a note if we created a new pack in the scope of a lambda, so that 13922 // we know that references to that pack must also be expanded within the 13923 // lambda scope. 13924 if (New->isParameterPack()) 13925 if (auto *LSI = getEnclosingLambda()) 13926 LSI->LocalPacks.push_back(New); 13927 13928 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13929 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13930 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13931 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13932 13933 // Parameters can not be abstract class types. 13934 // For record types, this is done by the AbstractClassUsageDiagnoser once 13935 // the class has been completely parsed. 13936 if (!CurContext->isRecord() && 13937 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13938 AbstractParamType)) 13939 New->setInvalidDecl(); 13940 13941 // Parameter declarators cannot be interface types. All ObjC objects are 13942 // passed by reference. 13943 if (T->isObjCObjectType()) { 13944 SourceLocation TypeEndLoc = 13945 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13946 Diag(NameLoc, 13947 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13948 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13949 T = Context.getObjCObjectPointerType(T); 13950 New->setType(T); 13951 } 13952 13953 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13954 // duration shall not be qualified by an address-space qualifier." 13955 // Since all parameters have automatic store duration, they can not have 13956 // an address space. 13957 if (T.getAddressSpace() != LangAS::Default && 13958 // OpenCL allows function arguments declared to be an array of a type 13959 // to be qualified with an address space. 13960 !(getLangOpts().OpenCL && 13961 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13962 Diag(NameLoc, diag::err_arg_with_address_space); 13963 New->setInvalidDecl(); 13964 } 13965 13966 // PPC MMA non-pointer types are not allowed as function argument types. 13967 if (Context.getTargetInfo().getTriple().isPPC64() && 13968 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 13969 New->setInvalidDecl(); 13970 } 13971 13972 return New; 13973} 13974 13975void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13976 SourceLocation LocAfterDecls) { 13977 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13978 13979 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13980 // for a K&R function. 13981 if (!FTI.hasPrototype) { 13982 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13983 --i; 13984 if (FTI.Params[i].Param == nullptr) { 13985 SmallString<256> Code; 13986 llvm::raw_svector_ostream(Code) 13987 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13988 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13989 << FTI.Params[i].Ident 13990 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13991 13992 // Implicitly declare the argument as type 'int' for lack of a better 13993 // type. 13994 AttributeFactory attrs; 13995 DeclSpec DS(attrs); 13996 const char* PrevSpec; // unused 13997 unsigned DiagID; // unused 13998 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13999 DiagID, Context.getPrintingPolicy()); 14000 // Use the identifier location for the type source range. 14001 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14002 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14003 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14004 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14005 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14006 } 14007 } 14008 } 14009} 14010 14011Decl * 14012Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14013 MultiTemplateParamsArg TemplateParameterLists, 14014 SkipBodyInfo *SkipBody) { 14015 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")(static_cast <bool> (getCurFunctionDecl() == nullptr &&
"Function parsing confused") ? void (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14015, __extension__ __PRETTY_FUNCTION__))
; 14016 assert(D.isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (D.isFunctionDeclarator() &&
"Not a function declarator!") ? void (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14016, __extension__ __PRETTY_FUNCTION__))
; 14017 Scope *ParentScope = FnBodyScope->getParent(); 14018 14019 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14020 // we define a non-templated function definition, we will create a declaration 14021 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14022 // The base function declaration will have the equivalent of an `omp declare 14023 // variant` annotation which specifies the mangled definition as a 14024 // specialization function under the OpenMP context defined as part of the 14025 // `omp begin declare variant`. 14026 SmallVector<FunctionDecl *, 4> Bases; 14027 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14028 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14029 ParentScope, D, TemplateParameterLists, Bases); 14030 14031 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14032 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14033 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14034 14035 if (!Bases.empty()) 14036 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14037 14038 return Dcl; 14039} 14040 14041void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14042 Consumer.HandleInlineFunctionDefinition(D); 14043} 14044 14045static bool 14046ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14047 const FunctionDecl *&PossiblePrototype) { 14048 // Don't warn about invalid declarations. 14049 if (FD->isInvalidDecl()) 14050 return false; 14051 14052 // Or declarations that aren't global. 14053 if (!FD->isGlobal()) 14054 return false; 14055 14056 // Don't warn about C++ member functions. 14057 if (isa<CXXMethodDecl>(FD)) 14058 return false; 14059 14060 // Don't warn about 'main'. 14061 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14062 if (IdentifierInfo *II = FD->getIdentifier()) 14063 if (II->isStr("main") || II->isStr("efi_main")) 14064 return false; 14065 14066 // Don't warn about inline functions. 14067 if (FD->isInlined()) 14068 return false; 14069 14070 // Don't warn about function templates. 14071 if (FD->getDescribedFunctionTemplate()) 14072 return false; 14073 14074 // Don't warn about function template specializations. 14075 if (FD->isFunctionTemplateSpecialization()) 14076 return false; 14077 14078 // Don't warn for OpenCL kernels. 14079 if (FD->hasAttr<OpenCLKernelAttr>()) 14080 return false; 14081 14082 // Don't warn on explicitly deleted functions. 14083 if (FD->isDeleted()) 14084 return false; 14085 14086 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14087 Prev; Prev = Prev->getPreviousDecl()) { 14088 // Ignore any declarations that occur in function or method 14089 // scope, because they aren't visible from the header. 14090 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14091 continue; 14092 14093 PossiblePrototype = Prev; 14094 return Prev->getType()->isFunctionNoProtoType(); 14095 } 14096 14097 return true; 14098} 14099 14100void 14101Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14102 const FunctionDecl *EffectiveDefinition, 14103 SkipBodyInfo *SkipBody) { 14104 const FunctionDecl *Definition = EffectiveDefinition; 14105 if (!Definition && 14106 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14107 return; 14108 14109 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14110 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14111 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14112 // A merged copy of the same function, instantiated as a member of 14113 // the same class, is OK. 14114 if (declaresSameEntity(OrigFD, OrigDef) && 14115 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14116 cast<Decl>(FD->getLexicalDeclContext()))) 14117 return; 14118 } 14119 } 14120 } 14121 14122 if (canRedefineFunction(Definition, getLangOpts())) 14123 return; 14124 14125 // Don't emit an error when this is redefinition of a typo-corrected 14126 // definition. 14127 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14128 return; 14129 14130 // If we don't have a visible definition of the function, and it's inline or 14131 // a template, skip the new definition. 14132 if (SkipBody && !hasVisibleDefinition(Definition) && 14133 (Definition->getFormalLinkage() == InternalLinkage || 14134 Definition->isInlined() || 14135 Definition->getDescribedFunctionTemplate() || 14136 Definition->getNumTemplateParameterLists())) { 14137 SkipBody->ShouldSkip = true; 14138 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14139 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14140 makeMergedDefinitionVisible(TD); 14141 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14142 return; 14143 } 14144 14145 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14146 Definition->getStorageClass() == SC_Extern) 14147 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14148 << FD << getLangOpts().CPlusPlus; 14149 else 14150 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14151 14152 Diag(Definition->getLocation(), diag::note_previous_definition); 14153 FD->setInvalidDecl(); 14154} 14155 14156static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14157 Sema &S) { 14158 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14159 14160 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14161 LSI->CallOperator = CallOperator; 14162 LSI->Lambda = LambdaClass; 14163 LSI->ReturnType = CallOperator->getReturnType(); 14164 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14165 14166 if (LCD == LCD_None) 14167 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14168 else if (LCD == LCD_ByCopy) 14169 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14170 else if (LCD == LCD_ByRef) 14171 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14172 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14173 14174 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14175 LSI->Mutable = !CallOperator->isConst(); 14176 14177 // Add the captures to the LSI so they can be noted as already 14178 // captured within tryCaptureVar. 14179 auto I = LambdaClass->field_begin(); 14180 for (const auto &C : LambdaClass->captures()) { 14181 if (C.capturesVariable()) { 14182 VarDecl *VD = C.getCapturedVar(); 14183 if (VD->isInitCapture()) 14184 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14185 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14186 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14187 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14188 /*EllipsisLoc*/C.isPackExpansion() 14189 ? C.getEllipsisLoc() : SourceLocation(), 14190 I->getType(), /*Invalid*/false); 14191 14192 } else if (C.capturesThis()) { 14193 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14194 C.getCaptureKind() == LCK_StarThis); 14195 } else { 14196 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14197 I->getType()); 14198 } 14199 ++I; 14200 } 14201} 14202 14203Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14204 SkipBodyInfo *SkipBody) { 14205 if (!D) { 14206 // Parsing the function declaration failed in some way. Push on a fake scope 14207 // anyway so we can try to parse the function body. 14208 PushFunctionScope(); 14209 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14210 return D; 14211 } 14212 14213 FunctionDecl *FD = nullptr; 14214 14215 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14216 FD = FunTmpl->getTemplatedDecl(); 14217 else 14218 FD = cast<FunctionDecl>(D); 14219 14220 // Do not push if it is a lambda because one is already pushed when building 14221 // the lambda in ActOnStartOfLambdaDefinition(). 14222 if (!isLambdaCallOperator(FD)) 14223 PushExpressionEvaluationContext( 14224 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14225 : ExprEvalContexts.back().Context); 14226 14227 // Check for defining attributes before the check for redefinition. 14228 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14229 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14230 FD->dropAttr<AliasAttr>(); 14231 FD->setInvalidDecl(); 14232 } 14233 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14234 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14235 FD->dropAttr<IFuncAttr>(); 14236 FD->setInvalidDecl(); 14237 } 14238 14239 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14240 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14241 Ctor->isDefaultConstructor() && 14242 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14243 // If this is an MS ABI dllexport default constructor, instantiate any 14244 // default arguments. 14245 InstantiateDefaultCtorDefaultArgs(Ctor); 14246 } 14247 } 14248 14249 // See if this is a redefinition. If 'will have body' (or similar) is already 14250 // set, then these checks were already performed when it was set. 14251 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14252 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14253 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14254 14255 // If we're skipping the body, we're done. Don't enter the scope. 14256 if (SkipBody && SkipBody->ShouldSkip) 14257 return D; 14258 } 14259 14260 // Mark this function as "will have a body eventually". This lets users to 14261 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14262 // this function. 14263 FD->setWillHaveBody(); 14264 14265 // If we are instantiating a generic lambda call operator, push 14266 // a LambdaScopeInfo onto the function stack. But use the information 14267 // that's already been calculated (ActOnLambdaExpr) to prime the current 14268 // LambdaScopeInfo. 14269 // When the template operator is being specialized, the LambdaScopeInfo, 14270 // has to be properly restored so that tryCaptureVariable doesn't try 14271 // and capture any new variables. In addition when calculating potential 14272 // captures during transformation of nested lambdas, it is necessary to 14273 // have the LSI properly restored. 14274 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14275 assert(inTemplateInstantiation() &&(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14277, __extension__ __PRETTY_FUNCTION__))
14276 "There should be an active template instantiation on the stack "(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14277, __extension__ __PRETTY_FUNCTION__))
14277 "when instantiating a generic lambda!")(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14277, __extension__ __PRETTY_FUNCTION__))
; 14278 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14279 } else { 14280 // Enter a new function scope 14281 PushFunctionScope(); 14282 } 14283 14284 // Builtin functions cannot be defined. 14285 if (unsigned BuiltinID = FD->getBuiltinID()) { 14286 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14287 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14288 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14289 FD->setInvalidDecl(); 14290 } 14291 } 14292 14293 // The return type of a function definition must be complete 14294 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14295 QualType ResultType = FD->getReturnType(); 14296 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14297 !FD->isInvalidDecl() && 14298 RequireCompleteType(FD->getLocation(), ResultType, 14299 diag::err_func_def_incomplete_result)) 14300 FD->setInvalidDecl(); 14301 14302 if (FnBodyScope) 14303 PushDeclContext(FnBodyScope, FD); 14304 14305 // Check the validity of our function parameters 14306 CheckParmsForFunctionDef(FD->parameters(), 14307 /*CheckParameterNames=*/true); 14308 14309 // Add non-parameter declarations already in the function to the current 14310 // scope. 14311 if (FnBodyScope) { 14312 for (Decl *NPD : FD->decls()) { 14313 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14314 if (!NonParmDecl) 14315 continue; 14316 assert(!isa<ParmVarDecl>(NonParmDecl) &&(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl
) && "parameters should not be in newly created FD yet"
) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14317, __extension__ __PRETTY_FUNCTION__))
14317 "parameters should not be in newly created FD yet")(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl
) && "parameters should not be in newly created FD yet"
) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14317, __extension__ __PRETTY_FUNCTION__))
; 14318 14319 // If the decl has a name, make it accessible in the current scope. 14320 if (NonParmDecl->getDeclName()) 14321 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14322 14323 // Similarly, dive into enums and fish their constants out, making them 14324 // accessible in this scope. 14325 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14326 for (auto *EI : ED->enumerators()) 14327 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14328 } 14329 } 14330 } 14331 14332 // Introduce our parameters into the function scope 14333 for (auto Param : FD->parameters()) { 14334 Param->setOwningFunction(FD); 14335 14336 // If this has an identifier, add it to the scope stack. 14337 if (Param->getIdentifier() && FnBodyScope) { 14338 CheckShadow(FnBodyScope, Param); 14339 14340 PushOnScopeChains(Param, FnBodyScope); 14341 } 14342 } 14343 14344 // Ensure that the function's exception specification is instantiated. 14345 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14346 ResolveExceptionSpec(D->getLocation(), FPT); 14347 14348 // dllimport cannot be applied to non-inline function definitions. 14349 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14350 !FD->isTemplateInstantiation()) { 14351 assert(!FD->hasAttr<DLLExportAttr>())(static_cast <bool> (!FD->hasAttr<DLLExportAttr>
()) ? void (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14351, __extension__ __PRETTY_FUNCTION__))
; 14352 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14353 FD->setInvalidDecl(); 14354 return D; 14355 } 14356 // We want to attach documentation to original Decl (which might be 14357 // a function template). 14358 ActOnDocumentableDecl(D); 14359 if (getCurLexicalContext()->isObjCContainer() && 14360 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14361 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14362 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14363 14364 return D; 14365} 14366 14367/// Given the set of return statements within a function body, 14368/// compute the variables that are subject to the named return value 14369/// optimization. 14370/// 14371/// Each of the variables that is subject to the named return value 14372/// optimization will be marked as NRVO variables in the AST, and any 14373/// return statement that has a marked NRVO variable as its NRVO candidate can 14374/// use the named return value optimization. 14375/// 14376/// This function applies a very simplistic algorithm for NRVO: if every return 14377/// statement in the scope of a variable has the same NRVO candidate, that 14378/// candidate is an NRVO variable. 14379void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14380 ReturnStmt **Returns = Scope->Returns.data(); 14381 14382 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14383 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14384 if (!NRVOCandidate->isNRVOVariable()) 14385 Returns[I]->setNRVOCandidate(nullptr); 14386 } 14387 } 14388} 14389 14390bool Sema::canDelayFunctionBody(const Declarator &D) { 14391 // We can't delay parsing the body of a constexpr function template (yet). 14392 if (D.getDeclSpec().hasConstexprSpecifier()) 14393 return false; 14394 14395 // We can't delay parsing the body of a function template with a deduced 14396 // return type (yet). 14397 if (D.getDeclSpec().hasAutoTypeSpec()) { 14398 // If the placeholder introduces a non-deduced trailing return type, 14399 // we can still delay parsing it. 14400 if (D.getNumTypeObjects()) { 14401 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14402 if (Outer.Kind == DeclaratorChunk::Function && 14403 Outer.Fun.hasTrailingReturnType()) { 14404 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14405 return Ty.isNull() || !Ty->isUndeducedType(); 14406 } 14407 } 14408 return false; 14409 } 14410 14411 return true; 14412} 14413 14414bool Sema::canSkipFunctionBody(Decl *D) { 14415 // We cannot skip the body of a function (or function template) which is 14416 // constexpr, since we may need to evaluate its body in order to parse the 14417 // rest of the file. 14418 // We cannot skip the body of a function with an undeduced return type, 14419 // because any callers of that function need to know the type. 14420 if (const FunctionDecl *FD = D->getAsFunction()) { 14421 if (FD->isConstexpr()) 14422 return false; 14423 // We can't simply call Type::isUndeducedType here, because inside template 14424 // auto can be deduced to a dependent type, which is not considered 14425 // "undeduced". 14426 if (FD->getReturnType()->getContainedDeducedType()) 14427 return false; 14428 } 14429 return Consumer.shouldSkipFunctionBody(D); 14430} 14431 14432Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14433 if (!Decl) 14434 return nullptr; 14435 if (FunctionDecl *FD = Decl->getAsFunction()) 14436 FD->setHasSkippedBody(); 14437 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14438 MD->setHasSkippedBody(); 14439 return Decl; 14440} 14441 14442Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14443 return ActOnFinishFunctionBody(D, BodyArg, false); 14444} 14445 14446/// RAII object that pops an ExpressionEvaluationContext when exiting a function 14447/// body. 14448class ExitFunctionBodyRAII { 14449public: 14450 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14451 ~ExitFunctionBodyRAII() { 14452 if (!IsLambda) 14453 S.PopExpressionEvaluationContext(); 14454 } 14455 14456private: 14457 Sema &S; 14458 bool IsLambda = false; 14459}; 14460 14461static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14462 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14463 14464 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14465 if (EscapeInfo.count(BD)) 14466 return EscapeInfo[BD]; 14467 14468 bool R = false; 14469 const BlockDecl *CurBD = BD; 14470 14471 do { 14472 R = !CurBD->doesNotEscape(); 14473 if (R) 14474 break; 14475 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14476 } while (CurBD); 14477 14478 return EscapeInfo[BD] = R; 14479 }; 14480 14481 // If the location where 'self' is implicitly retained is inside a escaping 14482 // block, emit a diagnostic. 14483 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14484 S.ImplicitlyRetainedSelfLocs) 14485 if (IsOrNestedInEscapingBlock(P.second)) 14486 S.Diag(P.first, diag::warn_implicitly_retains_self) 14487 << FixItHint::CreateInsertion(P.first, "self->"); 14488} 14489 14490Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14491 bool IsInstantiation) { 14492 FunctionScopeInfo *FSI = getCurFunction(); 14493 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14494 14495 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>()) 14496 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14497 14498 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14499 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14500 14501 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14502 CheckCompletedCoroutineBody(FD, Body); 14503 14504 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14505 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14506 // meant to pop the context added in ActOnStartOfFunctionDef(). 14507 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14508 14509 if (FD) { 14510 FD->setBody(Body); 14511 FD->setWillHaveBody(false); 14512 14513 if (getLangOpts().CPlusPlus14) { 14514 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14515 FD->getReturnType()->isUndeducedType()) { 14516 // If the function has a deduced result type but contains no 'return' 14517 // statements, the result type as written must be exactly 'auto', and 14518 // the deduced result type is 'void'. 14519 if (!FD->getReturnType()->getAs<AutoType>()) { 14520 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14521 << FD->getReturnType(); 14522 FD->setInvalidDecl(); 14523 } else { 14524 // Substitute 'void' for the 'auto' in the type. 14525 TypeLoc ResultType = getReturnTypeLoc(FD); 14526 Context.adjustDeducedFunctionResultType( 14527 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14528 } 14529 } 14530 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14531 // In C++11, we don't use 'auto' deduction rules for lambda call 14532 // operators because we don't support return type deduction. 14533 auto *LSI = getCurLambda(); 14534 if (LSI->HasImplicitReturnType) { 14535 deduceClosureReturnType(*LSI); 14536 14537 // C++11 [expr.prim.lambda]p4: 14538 // [...] if there are no return statements in the compound-statement 14539 // [the deduced type is] the type void 14540 QualType RetType = 14541 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14542 14543 // Update the return type to the deduced type. 14544 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14545 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14546 Proto->getExtProtoInfo())); 14547 } 14548 } 14549 14550 // If the function implicitly returns zero (like 'main') or is naked, 14551 // don't complain about missing return statements. 14552 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14553 WP.disableCheckFallThrough(); 14554 14555 // MSVC permits the use of pure specifier (=0) on function definition, 14556 // defined at class scope, warn about this non-standard construct. 14557 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14558 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14559 14560 if (!FD->isInvalidDecl()) { 14561 // Don't diagnose unused parameters of defaulted or deleted functions. 14562 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14563 DiagnoseUnusedParameters(FD->parameters()); 14564 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14565 FD->getReturnType(), FD); 14566 14567 // If this is a structor, we need a vtable. 14568 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14569 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14570 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14571 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14572 14573 // Try to apply the named return value optimization. We have to check 14574 // if we can do this here because lambdas keep return statements around 14575 // to deduce an implicit return type. 14576 if (FD->getReturnType()->isRecordType() && 14577 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14578 computeNRVO(Body, FSI); 14579 } 14580 14581 // GNU warning -Wmissing-prototypes: 14582 // Warn if a global function is defined without a previous 14583 // prototype declaration. This warning is issued even if the 14584 // definition itself provides a prototype. The aim is to detect 14585 // global functions that fail to be declared in header files. 14586 const FunctionDecl *PossiblePrototype = nullptr; 14587 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14588 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14589 14590 if (PossiblePrototype) { 14591 // We found a declaration that is not a prototype, 14592 // but that could be a zero-parameter prototype 14593 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14594 TypeLoc TL = TI->getTypeLoc(); 14595 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14596 Diag(PossiblePrototype->getLocation(), 14597 diag::note_declaration_not_a_prototype) 14598 << (FD->getNumParams() != 0) 14599 << (FD->getNumParams() == 0 14600 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14601 : FixItHint{}); 14602 } 14603 } else { 14604 // Returns true if the token beginning at this Loc is `const`. 14605 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14606 const LangOptions &LangOpts) { 14607 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14608 if (LocInfo.first.isInvalid()) 14609 return false; 14610 14611 bool Invalid = false; 14612 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14613 if (Invalid) 14614 return false; 14615 14616 if (LocInfo.second > Buffer.size()) 14617 return false; 14618 14619 const char *LexStart = Buffer.data() + LocInfo.second; 14620 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14621 14622 return StartTok.consume_front("const") && 14623 (StartTok.empty() || isWhitespace(StartTok[0]) || 14624 StartTok.startswith("/*") || StartTok.startswith("//")); 14625 }; 14626 14627 auto findBeginLoc = [&]() { 14628 // If the return type has `const` qualifier, we want to insert 14629 // `static` before `const` (and not before the typename). 14630 if ((FD->getReturnType()->isAnyPointerType() && 14631 FD->getReturnType()->getPointeeType().isConstQualified()) || 14632 FD->getReturnType().isConstQualified()) { 14633 // But only do this if we can determine where the `const` is. 14634 14635 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14636 getLangOpts())) 14637 14638 return FD->getBeginLoc(); 14639 } 14640 return FD->getTypeSpecStartLoc(); 14641 }; 14642 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14643 << /* function */ 1 14644 << (FD->getStorageClass() == SC_None 14645 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14646 : FixItHint{}); 14647 } 14648 14649 // GNU warning -Wstrict-prototypes 14650 // Warn if K&R function is defined without a previous declaration. 14651 // This warning is issued only if the definition itself does not provide 14652 // a prototype. Only K&R definitions do not provide a prototype. 14653 if (!FD->hasWrittenPrototype()) { 14654 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14655 TypeLoc TL = TI->getTypeLoc(); 14656 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14657 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14658 } 14659 } 14660 14661 // Warn on CPUDispatch with an actual body. 14662 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14663 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14664 if (!CmpndBody->body_empty()) 14665 Diag(CmpndBody->body_front()->getBeginLoc(), 14666 diag::warn_dispatch_body_ignored); 14667 14668 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14669 const CXXMethodDecl *KeyFunction; 14670 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14671 MD->isVirtual() && 14672 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14673 MD == KeyFunction->getCanonicalDecl()) { 14674 // Update the key-function state if necessary for this ABI. 14675 if (FD->isInlined() && 14676 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14677 Context.setNonKeyFunction(MD); 14678 14679 // If the newly-chosen key function is already defined, then we 14680 // need to mark the vtable as used retroactively. 14681 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14682 const FunctionDecl *Definition; 14683 if (KeyFunction && KeyFunction->isDefined(Definition)) 14684 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14685 } else { 14686 // We just defined they key function; mark the vtable as used. 14687 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14688 } 14689 } 14690 } 14691 14692 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14693, __extension__ __PRETTY_FUNCTION__))
14693 "Function parsing confused")(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14693, __extension__ __PRETTY_FUNCTION__))
; 14694 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14695 assert(MD == getCurMethodDecl() && "Method parsing confused")(static_cast <bool> (MD == getCurMethodDecl() &&
"Method parsing confused") ? void (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14695, __extension__ __PRETTY_FUNCTION__))
; 14696 MD->setBody(Body); 14697 if (!MD->isInvalidDecl()) { 14698 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14699 MD->getReturnType(), MD); 14700 14701 if (Body) 14702 computeNRVO(Body, FSI); 14703 } 14704 if (FSI->ObjCShouldCallSuper) { 14705 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14706 << MD->getSelector().getAsString(); 14707 FSI->ObjCShouldCallSuper = false; 14708 } 14709 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14710 const ObjCMethodDecl *InitMethod = nullptr; 14711 bool isDesignated = 14712 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14713 assert(isDesignated && InitMethod)(static_cast <bool> (isDesignated && InitMethod
) ? void (0) : __assert_fail ("isDesignated && InitMethod"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14713, __extension__ __PRETTY_FUNCTION__))
; 14714 (void)isDesignated; 14715 14716 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14717 auto IFace = MD->getClassInterface(); 14718 if (!IFace) 14719 return false; 14720 auto SuperD = IFace->getSuperClass(); 14721 if (!SuperD) 14722 return false; 14723 return SuperD->getIdentifier() == 14724 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14725 }; 14726 // Don't issue this warning for unavailable inits or direct subclasses 14727 // of NSObject. 14728 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14729 Diag(MD->getLocation(), 14730 diag::warn_objc_designated_init_missing_super_call); 14731 Diag(InitMethod->getLocation(), 14732 diag::note_objc_designated_init_marked_here); 14733 } 14734 FSI->ObjCWarnForNoDesignatedInitChain = false; 14735 } 14736 if (FSI->ObjCWarnForNoInitDelegation) { 14737 // Don't issue this warning for unavaialable inits. 14738 if (!MD->isUnavailable()) 14739 Diag(MD->getLocation(), 14740 diag::warn_objc_secondary_init_missing_init_call); 14741 FSI->ObjCWarnForNoInitDelegation = false; 14742 } 14743 14744 diagnoseImplicitlyRetainedSelf(*this); 14745 } else { 14746 // Parsing the function declaration failed in some way. Pop the fake scope 14747 // we pushed on. 14748 PopFunctionScopeInfo(ActivePolicy, dcl); 14749 return nullptr; 14750 } 14751 14752 if (Body && FSI->HasPotentialAvailabilityViolations) 14753 DiagnoseUnguardedAvailabilityViolations(dcl); 14754 14755 assert(!FSI->ObjCShouldCallSuper &&(static_cast <bool> (!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14757, __extension__ __PRETTY_FUNCTION__))
14756 "This should only be set for ObjC methods, which should have been "(static_cast <bool> (!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14757, __extension__ __PRETTY_FUNCTION__))
14757 "handled in the block above.")(static_cast <bool> (!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14757, __extension__ __PRETTY_FUNCTION__))
; 14758 14759 // Verify and clean out per-function state. 14760 if (Body && (!FD || !FD->isDefaulted())) { 14761 // C++ constructors that have function-try-blocks can't have return 14762 // statements in the handlers of that block. (C++ [except.handle]p14) 14763 // Verify this. 14764 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14765 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14766 14767 // Verify that gotos and switch cases don't jump into scopes illegally. 14768 if (FSI->NeedsScopeChecking() && 14769 !PP.isCodeCompletionEnabled()) 14770 DiagnoseInvalidJumps(Body); 14771 14772 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14773 if (!Destructor->getParent()->isDependentType()) 14774 CheckDestructor(Destructor); 14775 14776 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14777 Destructor->getParent()); 14778 } 14779 14780 // If any errors have occurred, clear out any temporaries that may have 14781 // been leftover. This ensures that these temporaries won't be picked up for 14782 // deletion in some later function. 14783 if (hasUncompilableErrorOccurred() || 14784 getDiagnostics().getSuppressAllDiagnostics()) { 14785 DiscardCleanupsInEvaluationContext(); 14786 } 14787 if (!hasUncompilableErrorOccurred() && 14788 !isa<FunctionTemplateDecl>(dcl)) { 14789 // Since the body is valid, issue any analysis-based warnings that are 14790 // enabled. 14791 ActivePolicy = &WP; 14792 } 14793 14794 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14795 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14796 FD->setInvalidDecl(); 14797 14798 if (FD && FD->hasAttr<NakedAttr>()) { 14799 for (const Stmt *S : Body->children()) { 14800 // Allow local register variables without initializer as they don't 14801 // require prologue. 14802 bool RegisterVariables = false; 14803 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14804 for (const auto *Decl : DS->decls()) { 14805 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14806 RegisterVariables = 14807 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14808 if (!RegisterVariables) 14809 break; 14810 } 14811 } 14812 } 14813 if (RegisterVariables) 14814 continue; 14815 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14816 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14817 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14818 FD->setInvalidDecl(); 14819 break; 14820 } 14821 } 14822 } 14823 14824 assert(ExprCleanupObjects.size() ==(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14826, __extension__ __PRETTY_FUNCTION__))
14825 ExprEvalContexts.back().NumCleanupObjects &&(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14826, __extension__ __PRETTY_FUNCTION__))
14826 "Leftover temporaries in function")(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14826, __extension__ __PRETTY_FUNCTION__))
; 14827 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"Unaccounted cleanups in function") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14827, __extension__ __PRETTY_FUNCTION__))
; 14828 assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking") ? void (0) : __assert_fail
("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14829, __extension__ __PRETTY_FUNCTION__))
14829 "Leftover expressions for odr-use checking")(static_cast <bool> (MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking") ? void (0) : __assert_fail
("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14829, __extension__ __PRETTY_FUNCTION__))
; 14830 } 14831 14832 if (!IsInstantiation) 14833 PopDeclContext(); 14834 14835 PopFunctionScopeInfo(ActivePolicy, dcl); 14836 // If any errors have occurred, clear out any temporaries that may have 14837 // been leftover. This ensures that these temporaries won't be picked up for 14838 // deletion in some later function. 14839 if (hasUncompilableErrorOccurred()) { 14840 DiscardCleanupsInEvaluationContext(); 14841 } 14842 14843 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 14844 auto ES = getEmissionStatus(FD); 14845 if (ES == Sema::FunctionEmissionStatus::Emitted || 14846 ES == Sema::FunctionEmissionStatus::Unknown) 14847 DeclsToCheckForDeferredDiags.insert(FD); 14848 } 14849 14850 return dcl; 14851} 14852 14853/// When we finish delayed parsing of an attribute, we must attach it to the 14854/// relevant Decl. 14855void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14856 ParsedAttributes &Attrs) { 14857 // Always attach attributes to the underlying decl. 14858 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14859 D = TD->getTemplatedDecl(); 14860 ProcessDeclAttributeList(S, D, Attrs); 14861 14862 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14863 if (Method->isStatic()) 14864 checkThisInStaticMemberFunctionAttributes(Method); 14865} 14866 14867/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14868/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14869NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14870 IdentifierInfo &II, Scope *S) { 14871 // Find the scope in which the identifier is injected and the corresponding 14872 // DeclContext. 14873 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14874 // In that case, we inject the declaration into the translation unit scope 14875 // instead. 14876 Scope *BlockScope = S; 14877 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14878 BlockScope = BlockScope->getParent(); 14879 14880 Scope *ContextScope = BlockScope; 14881 while (!ContextScope->getEntity()) 14882 ContextScope = ContextScope->getParent(); 14883 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14884 14885 // Before we produce a declaration for an implicitly defined 14886 // function, see whether there was a locally-scoped declaration of 14887 // this name as a function or variable. If so, use that 14888 // (non-visible) declaration, and complain about it. 14889 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14890 if (ExternCPrev) { 14891 // We still need to inject the function into the enclosing block scope so 14892 // that later (non-call) uses can see it. 14893 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14894 14895 // C89 footnote 38: 14896 // If in fact it is not defined as having type "function returning int", 14897 // the behavior is undefined. 14898 if (!isa<FunctionDecl>(ExternCPrev) || 14899 !Context.typesAreCompatible( 14900 cast<FunctionDecl>(ExternCPrev)->getType(), 14901 Context.getFunctionNoProtoType(Context.IntTy))) { 14902 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14903 << ExternCPrev << !getLangOpts().C99; 14904 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14905 return ExternCPrev; 14906 } 14907 } 14908 14909 // Extension in C99. Legal in C90, but warn about it. 14910 unsigned diag_id; 14911 if (II.getName().startswith("__builtin_")) 14912 diag_id = diag::warn_builtin_unknown; 14913 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14914 else if (getLangOpts().OpenCL) 14915 diag_id = diag::err_opencl_implicit_function_decl; 14916 else if (getLangOpts().C99) 14917 diag_id = diag::ext_implicit_function_decl; 14918 else 14919 diag_id = diag::warn_implicit_function_decl; 14920 Diag(Loc, diag_id) << &II; 14921 14922 // If we found a prior declaration of this function, don't bother building 14923 // another one. We've already pushed that one into scope, so there's nothing 14924 // more to do. 14925 if (ExternCPrev) 14926 return ExternCPrev; 14927 14928 // Because typo correction is expensive, only do it if the implicit 14929 // function declaration is going to be treated as an error. 14930 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14931 TypoCorrection Corrected; 14932 DeclFilterCCC<FunctionDecl> CCC{}; 14933 if (S && (Corrected = 14934 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14935 S, nullptr, CCC, CTK_NonError))) 14936 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14937 /*ErrorRecovery*/false); 14938 } 14939 14940 // Set a Declarator for the implicit definition: int foo(); 14941 const char *Dummy; 14942 AttributeFactory attrFactory; 14943 DeclSpec DS(attrFactory); 14944 unsigned DiagID; 14945 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14946 Context.getPrintingPolicy()); 14947 (void)Error; // Silence warning. 14948 assert(!Error && "Error setting up implicit decl!")(static_cast <bool> (!Error && "Error setting up implicit decl!"
) ? void (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 14948, __extension__ __PRETTY_FUNCTION__))
; 14949 SourceLocation NoLoc; 14950 Declarator D(DS, DeclaratorContext::Block); 14951 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14952 /*IsAmbiguous=*/false, 14953 /*LParenLoc=*/NoLoc, 14954 /*Params=*/nullptr, 14955 /*NumParams=*/0, 14956 /*EllipsisLoc=*/NoLoc, 14957 /*RParenLoc=*/NoLoc, 14958 /*RefQualifierIsLvalueRef=*/true, 14959 /*RefQualifierLoc=*/NoLoc, 14960 /*MutableLoc=*/NoLoc, EST_None, 14961 /*ESpecRange=*/SourceRange(), 14962 /*Exceptions=*/nullptr, 14963 /*ExceptionRanges=*/nullptr, 14964 /*NumExceptions=*/0, 14965 /*NoexceptExpr=*/nullptr, 14966 /*ExceptionSpecTokens=*/nullptr, 14967 /*DeclsInPrototype=*/None, Loc, 14968 Loc, D), 14969 std::move(DS.getAttributes()), SourceLocation()); 14970 D.SetIdentifier(&II, Loc); 14971 14972 // Insert this function into the enclosing block scope. 14973 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14974 FD->setImplicit(); 14975 14976 AddKnownFunctionAttributes(FD); 14977 14978 return FD; 14979} 14980 14981/// If this function is a C++ replaceable global allocation function 14982/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14983/// adds any function attributes that we know a priori based on the standard. 14984/// 14985/// We need to check for duplicate attributes both here and where user-written 14986/// attributes are applied to declarations. 14987void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14988 FunctionDecl *FD) { 14989 if (FD->isInvalidDecl()) 14990 return; 14991 14992 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14993 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14994 return; 14995 14996 Optional<unsigned> AlignmentParam; 14997 bool IsNothrow = false; 14998 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14999 return; 15000 15001 // C++2a [basic.stc.dynamic.allocation]p4: 15002 // An allocation function that has a non-throwing exception specification 15003 // indicates failure by returning a null pointer value. Any other allocation 15004 // function never returns a null pointer value and indicates failure only by 15005 // throwing an exception [...] 15006 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15007 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15008 15009 // C++2a [basic.stc.dynamic.allocation]p2: 15010 // An allocation function attempts to allocate the requested amount of 15011 // storage. [...] If the request succeeds, the value returned by a 15012 // replaceable allocation function is a [...] pointer value p0 different 15013 // from any previously returned value p1 [...] 15014 // 15015 // However, this particular information is being added in codegen, 15016 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15017 15018 // C++2a [basic.stc.dynamic.allocation]p2: 15019 // An allocation function attempts to allocate the requested amount of 15020 // storage. If it is successful, it returns the address of the start of a 15021 // block of storage whose length in bytes is at least as large as the 15022 // requested size. 15023 if (!FD->hasAttr<AllocSizeAttr>()) { 15024 FD->addAttr(AllocSizeAttr::CreateImplicit( 15025 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15026 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15027 } 15028 15029 // C++2a [basic.stc.dynamic.allocation]p3: 15030 // For an allocation function [...], the pointer returned on a successful 15031 // call shall represent the address of storage that is aligned as follows: 15032 // (3.1) If the allocation function takes an argument of type 15033 // std​::​align_­val_­t, the storage will have the alignment 15034 // specified by the value of this argument. 15035 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15036 FD->addAttr(AllocAlignAttr::CreateImplicit( 15037 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15038 } 15039 15040 // FIXME: 15041 // C++2a [basic.stc.dynamic.allocation]p3: 15042 // For an allocation function [...], the pointer returned on a successful 15043 // call shall represent the address of storage that is aligned as follows: 15044 // (3.2) Otherwise, if the allocation function is named operator new[], 15045 // the storage is aligned for any object that does not have 15046 // new-extended alignment ([basic.align]) and is no larger than the 15047 // requested size. 15048 // (3.3) Otherwise, the storage is aligned for any object that does not 15049 // have new-extended alignment and is of the requested size. 15050} 15051 15052/// Adds any function attributes that we know a priori based on 15053/// the declaration of this function. 15054/// 15055/// These attributes can apply both to implicitly-declared builtins 15056/// (like __builtin___printf_chk) or to library-declared functions 15057/// like NSLog or printf. 15058/// 15059/// We need to check for duplicate attributes both here and where user-written 15060/// attributes are applied to declarations. 15061void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15062 if (FD->isInvalidDecl()) 15063 return; 15064 15065 // If this is a built-in function, map its builtin attributes to 15066 // actual attributes. 15067 if (unsigned BuiltinID = FD->getBuiltinID()) { 15068 // Handle printf-formatting attributes. 15069 unsigned FormatIdx; 15070 bool HasVAListArg; 15071 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15072 if (!FD->hasAttr<FormatAttr>()) { 15073 const char *fmt = "printf"; 15074 unsigned int NumParams = FD->getNumParams(); 15075 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15076 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15077 fmt = "NSString"; 15078 FD->addAttr(FormatAttr::CreateImplicit(Context, 15079 &Context.Idents.get(fmt), 15080 FormatIdx+1, 15081 HasVAListArg ? 0 : FormatIdx+2, 15082 FD->getLocation())); 15083 } 15084 } 15085 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15086 HasVAListArg)) { 15087 if (!FD->hasAttr<FormatAttr>()) 15088 FD->addAttr(FormatAttr::CreateImplicit(Context, 15089 &Context.Idents.get("scanf"), 15090 FormatIdx+1, 15091 HasVAListArg ? 0 : FormatIdx+2, 15092 FD->getLocation())); 15093 } 15094 15095 // Handle automatically recognized callbacks. 15096 SmallVector<int, 4> Encoding; 15097 if (!FD->hasAttr<CallbackAttr>() && 15098 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15099 FD->addAttr(CallbackAttr::CreateImplicit( 15100 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15101 15102 // Mark const if we don't care about errno and that is the only thing 15103 // preventing the function from being const. This allows IRgen to use LLVM 15104 // intrinsics for such functions. 15105 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15106 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15107 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15108 15109 // We make "fma" on some platforms const because we know it does not set 15110 // errno in those environments even though it could set errno based on the 15111 // C standard. 15112 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15113 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 15114 !FD->hasAttr<ConstAttr>()) { 15115 switch (BuiltinID) { 15116 case Builtin::BI__builtin_fma: 15117 case Builtin::BI__builtin_fmaf: 15118 case Builtin::BI__builtin_fmal: 15119 case Builtin::BIfma: 15120 case Builtin::BIfmaf: 15121 case Builtin::BIfmal: 15122 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15123 break; 15124 default: 15125 break; 15126 } 15127 } 15128 15129 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15130 !FD->hasAttr<ReturnsTwiceAttr>()) 15131 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15132 FD->getLocation())); 15133 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15134 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15135 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15136 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15137 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15138 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15139 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15140 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15141 // Add the appropriate attribute, depending on the CUDA compilation mode 15142 // and which target the builtin belongs to. For example, during host 15143 // compilation, aux builtins are __device__, while the rest are __host__. 15144 if (getLangOpts().CUDAIsDevice != 15145 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15146 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15147 else 15148 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15149 } 15150 } 15151 15152 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15153 15154 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15155 // throw, add an implicit nothrow attribute to any extern "C" function we come 15156 // across. 15157 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15158 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15159 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15160 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15161 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15162 } 15163 15164 IdentifierInfo *Name = FD->getIdentifier(); 15165 if (!Name) 15166 return; 15167 if ((!getLangOpts().CPlusPlus && 15168 FD->getDeclContext()->isTranslationUnit()) || 15169 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15170 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15171 LinkageSpecDecl::lang_c)) { 15172 // Okay: this could be a libc/libm/Objective-C function we know 15173 // about. 15174 } else 15175 return; 15176 15177 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15178 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15179 // target-specific builtins, perhaps? 15180 if (!FD->hasAttr<FormatAttr>()) 15181 FD->addAttr(FormatAttr::CreateImplicit(Context, 15182 &Context.Idents.get("printf"), 2, 15183 Name->isStr("vasprintf") ? 0 : 3, 15184 FD->getLocation())); 15185 } 15186 15187 if (Name->isStr("__CFStringMakeConstantString")) { 15188 // We already have a __builtin___CFStringMakeConstantString, 15189 // but builds that use -fno-constant-cfstrings don't go through that. 15190 if (!FD->hasAttr<FormatArgAttr>()) 15191 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15192 FD->getLocation())); 15193 } 15194} 15195 15196TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15197 TypeSourceInfo *TInfo) { 15198 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")(static_cast <bool> (D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? void (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15198, __extension__ __PRETTY_FUNCTION__))
; 15199 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")(static_cast <bool> (!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? void (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15199, __extension__ __PRETTY_FUNCTION__))
; 15200 15201 if (!TInfo) { 15202 assert(D.isInvalidType() && "no declarator info for valid type")(static_cast <bool> (D.isInvalidType() && "no declarator info for valid type"
) ? void (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15202, __extension__ __PRETTY_FUNCTION__))
; 15203 TInfo = Context.getTrivialTypeSourceInfo(T); 15204 } 15205 15206 // Scope manipulation handled by caller. 15207 TypedefDecl *NewTD = 15208 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15209 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15210 15211 // Bail out immediately if we have an invalid declaration. 15212 if (D.isInvalidType()) { 15213 NewTD->setInvalidDecl(); 15214 return NewTD; 15215 } 15216 15217 if (D.getDeclSpec().isModulePrivateSpecified()) { 15218 if (CurContext->isFunctionOrMethod()) 15219 Diag(NewTD->getLocation(), diag::err_module_private_local) 15220 << 2 << NewTD 15221 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15222 << FixItHint::CreateRemoval( 15223 D.getDeclSpec().getModulePrivateSpecLoc()); 15224 else 15225 NewTD->setModulePrivate(); 15226 } 15227 15228 // C++ [dcl.typedef]p8: 15229 // If the typedef declaration defines an unnamed class (or 15230 // enum), the first typedef-name declared by the declaration 15231 // to be that class type (or enum type) is used to denote the 15232 // class type (or enum type) for linkage purposes only. 15233 // We need to check whether the type was declared in the declaration. 15234 switch (D.getDeclSpec().getTypeSpecType()) { 15235 case TST_enum: 15236 case TST_struct: 15237 case TST_interface: 15238 case TST_union: 15239 case TST_class: { 15240 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15241 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15242 break; 15243 } 15244 15245 default: 15246 break; 15247 } 15248 15249 return NewTD; 15250} 15251 15252/// Check that this is a valid underlying type for an enum declaration. 15253bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15254 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15255 QualType T = TI->getType(); 15256 15257 if (T->isDependentType()) 15258 return false; 15259 15260 // This doesn't use 'isIntegralType' despite the error message mentioning 15261 // integral type because isIntegralType would also allow enum types in C. 15262 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15263 if (BT->isInteger()) 15264 return false; 15265 15266 if (T->isExtIntType()) 15267 return false; 15268 15269 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15270} 15271 15272/// Check whether this is a valid redeclaration of a previous enumeration. 15273/// \return true if the redeclaration was invalid. 15274bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15275 QualType EnumUnderlyingTy, bool IsFixed, 15276 const EnumDecl *Prev) { 15277 if (IsScoped != Prev->isScoped()) { 15278 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15279 << Prev->isScoped(); 15280 Diag(Prev->getLocation(), diag::note_previous_declaration); 15281 return true; 15282 } 15283 15284 if (IsFixed && Prev->isFixed()) { 15285 if (!EnumUnderlyingTy->isDependentType() && 15286 !Prev->getIntegerType()->isDependentType() && 15287 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15288 Prev->getIntegerType())) { 15289 // TODO: Highlight the underlying type of the redeclaration. 15290 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15291 << EnumUnderlyingTy << Prev->getIntegerType(); 15292 Diag(Prev->getLocation(), diag::note_previous_declaration) 15293 << Prev->getIntegerTypeRange(); 15294 return true; 15295 } 15296 } else if (IsFixed != Prev->isFixed()) { 15297 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15298 << Prev->isFixed(); 15299 Diag(Prev->getLocation(), diag::note_previous_declaration); 15300 return true; 15301 } 15302 15303 return false; 15304} 15305 15306/// Get diagnostic %select index for tag kind for 15307/// redeclaration diagnostic message. 15308/// WARNING: Indexes apply to particular diagnostics only! 15309/// 15310/// \returns diagnostic %select index. 15311static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15312 switch (Tag) { 15313 case TTK_Struct: return 0; 15314 case TTK_Interface: return 1; 15315 case TTK_Class: return 2; 15316 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15316)
; 15317 } 15318} 15319 15320/// Determine if tag kind is a class-key compatible with 15321/// class for redeclaration (class, struct, or __interface). 15322/// 15323/// \returns true iff the tag kind is compatible. 15324static bool isClassCompatTagKind(TagTypeKind Tag) 15325{ 15326 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15327} 15328 15329Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15330 TagTypeKind TTK) { 15331 if (isa<TypedefDecl>(PrevDecl)) 15332 return NTK_Typedef; 15333 else if (isa<TypeAliasDecl>(PrevDecl)) 15334 return NTK_TypeAlias; 15335 else if (isa<ClassTemplateDecl>(PrevDecl)) 15336 return NTK_Template; 15337 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15338 return NTK_TypeAliasTemplate; 15339 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15340 return NTK_TemplateTemplateArgument; 15341 switch (TTK) { 15342 case TTK_Struct: 15343 case TTK_Interface: 15344 case TTK_Class: 15345 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15346 case TTK_Union: 15347 return NTK_NonUnion; 15348 case TTK_Enum: 15349 return NTK_NonEnum; 15350 } 15351 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15351)
; 15352} 15353 15354/// Determine whether a tag with a given kind is acceptable 15355/// as a redeclaration of the given tag declaration. 15356/// 15357/// \returns true if the new tag kind is acceptable, false otherwise. 15358bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15359 TagTypeKind NewTag, bool isDefinition, 15360 SourceLocation NewTagLoc, 15361 const IdentifierInfo *Name) { 15362 // C++ [dcl.type.elab]p3: 15363 // The class-key or enum keyword present in the 15364 // elaborated-type-specifier shall agree in kind with the 15365 // declaration to which the name in the elaborated-type-specifier 15366 // refers. This rule also applies to the form of 15367 // elaborated-type-specifier that declares a class-name or 15368 // friend class since it can be construed as referring to the 15369 // definition of the class. Thus, in any 15370 // elaborated-type-specifier, the enum keyword shall be used to 15371 // refer to an enumeration (7.2), the union class-key shall be 15372 // used to refer to a union (clause 9), and either the class or 15373 // struct class-key shall be used to refer to a class (clause 9) 15374 // declared using the class or struct class-key. 15375 TagTypeKind OldTag = Previous->getTagKind(); 15376 if (OldTag != NewTag && 15377 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15378 return false; 15379 15380 // Tags are compatible, but we might still want to warn on mismatched tags. 15381 // Non-class tags can't be mismatched at this point. 15382 if (!isClassCompatTagKind(NewTag)) 15383 return true; 15384 15385 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15386 // by our warning analysis. We don't want to warn about mismatches with (eg) 15387 // declarations in system headers that are designed to be specialized, but if 15388 // a user asks us to warn, we should warn if their code contains mismatched 15389 // declarations. 15390 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15391 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15392 Loc); 15393 }; 15394 if (IsIgnoredLoc(NewTagLoc)) 15395 return true; 15396 15397 auto IsIgnored = [&](const TagDecl *Tag) { 15398 return IsIgnoredLoc(Tag->getLocation()); 15399 }; 15400 while (IsIgnored(Previous)) { 15401 Previous = Previous->getPreviousDecl(); 15402 if (!Previous) 15403 return true; 15404 OldTag = Previous->getTagKind(); 15405 } 15406 15407 bool isTemplate = false; 15408 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15409 isTemplate = Record->getDescribedClassTemplate(); 15410 15411 if (inTemplateInstantiation()) { 15412 if (OldTag != NewTag) { 15413 // In a template instantiation, do not offer fix-its for tag mismatches 15414 // since they usually mess up the template instead of fixing the problem. 15415 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15416 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15417 << getRedeclDiagFromTagKind(OldTag); 15418 // FIXME: Note previous location? 15419 } 15420 return true; 15421 } 15422 15423 if (isDefinition) { 15424 // On definitions, check all previous tags and issue a fix-it for each 15425 // one that doesn't match the current tag. 15426 if (Previous->getDefinition()) { 15427 // Don't suggest fix-its for redefinitions. 15428 return true; 15429 } 15430 15431 bool previousMismatch = false; 15432 for (const TagDecl *I : Previous->redecls()) { 15433 if (I->getTagKind() != NewTag) { 15434 // Ignore previous declarations for which the warning was disabled. 15435 if (IsIgnored(I)) 15436 continue; 15437 15438 if (!previousMismatch) { 15439 previousMismatch = true; 15440 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15441 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15442 << getRedeclDiagFromTagKind(I->getTagKind()); 15443 } 15444 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15445 << getRedeclDiagFromTagKind(NewTag) 15446 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15447 TypeWithKeyword::getTagTypeKindName(NewTag)); 15448 } 15449 } 15450 return true; 15451 } 15452 15453 // Identify the prevailing tag kind: this is the kind of the definition (if 15454 // there is a non-ignored definition), or otherwise the kind of the prior 15455 // (non-ignored) declaration. 15456 const TagDecl *PrevDef = Previous->getDefinition(); 15457 if (PrevDef && IsIgnored(PrevDef)) 15458 PrevDef = nullptr; 15459 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15460 if (Redecl->getTagKind() != NewTag) { 15461 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15462 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15463 << getRedeclDiagFromTagKind(OldTag); 15464 Diag(Redecl->getLocation(), diag::note_previous_use); 15465 15466 // If there is a previous definition, suggest a fix-it. 15467 if (PrevDef) { 15468 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15469 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15470 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15471 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15472 } 15473 } 15474 15475 return true; 15476} 15477 15478/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15479/// from an outer enclosing namespace or file scope inside a friend declaration. 15480/// This should provide the commented out code in the following snippet: 15481/// namespace N { 15482/// struct X; 15483/// namespace M { 15484/// struct Y { friend struct /*N::*/ X; }; 15485/// } 15486/// } 15487static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15488 SourceLocation NameLoc) { 15489 // While the decl is in a namespace, do repeated lookup of that name and see 15490 // if we get the same namespace back. If we do not, continue until 15491 // translation unit scope, at which point we have a fully qualified NNS. 15492 SmallVector<IdentifierInfo *, 4> Namespaces; 15493 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15494 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15495 // This tag should be declared in a namespace, which can only be enclosed by 15496 // other namespaces. Bail if there's an anonymous namespace in the chain. 15497 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15498 if (!Namespace || Namespace->isAnonymousNamespace()) 15499 return FixItHint(); 15500 IdentifierInfo *II = Namespace->getIdentifier(); 15501 Namespaces.push_back(II); 15502 NamedDecl *Lookup = SemaRef.LookupSingleName( 15503 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15504 if (Lookup == Namespace) 15505 break; 15506 } 15507 15508 // Once we have all the namespaces, reverse them to go outermost first, and 15509 // build an NNS. 15510 SmallString<64> Insertion; 15511 llvm::raw_svector_ostream OS(Insertion); 15512 if (DC->isTranslationUnit()) 15513 OS << "::"; 15514 std::reverse(Namespaces.begin(), Namespaces.end()); 15515 for (auto *II : Namespaces) 15516 OS << II->getName() << "::"; 15517 return FixItHint::CreateInsertion(NameLoc, Insertion); 15518} 15519 15520/// Determine whether a tag originally declared in context \p OldDC can 15521/// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15522/// found a declaration in \p OldDC as a previous decl, perhaps through a 15523/// using-declaration). 15524static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15525 DeclContext *NewDC) { 15526 OldDC = OldDC->getRedeclContext(); 15527 NewDC = NewDC->getRedeclContext(); 15528 15529 if (OldDC->Equals(NewDC)) 15530 return true; 15531 15532 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15533 // encloses the other). 15534 if (S.getLangOpts().MSVCCompat && 15535 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15536 return true; 15537 15538 return false; 15539} 15540 15541/// This is invoked when we see 'struct foo' or 'struct {'. In the 15542/// former case, Name will be non-null. In the later case, Name will be null. 15543/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15544/// reference/declaration/definition of a tag. 15545/// 15546/// \param IsTypeSpecifier \c true if this is a type-specifier (or 15547/// trailing-type-specifier) other than one in an alias-declaration. 15548/// 15549/// \param SkipBody If non-null, will be set to indicate if the caller should 15550/// skip the definition of this tag and treat it as if it were a declaration. 15551Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15552 SourceLocation KWLoc, CXXScopeSpec &SS, 15553 IdentifierInfo *Name, SourceLocation NameLoc, 15554 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15555 SourceLocation ModulePrivateLoc, 15556 MultiTemplateParamsArg TemplateParameterLists, 15557 bool &OwnedDecl, bool &IsDependent, 15558 SourceLocation ScopedEnumKWLoc, 15559 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15560 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15561 SkipBodyInfo *SkipBody) { 15562 // If this is not a definition, it must have a name. 15563 IdentifierInfo *OrigName = Name; 15564 assert((Name != nullptr || TUK == TUK_Definition) &&(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition
) && "Nameless record must be a definition!") ? void (
0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15565, __extension__ __PRETTY_FUNCTION__))
15565 "Nameless record must be a definition!")(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition
) && "Nameless record must be a definition!") ? void (
0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15565, __extension__ __PRETTY_FUNCTION__))
; 15566 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)(static_cast <bool> (TemplateParameterLists.size() == 0
|| TUK != TUK_Reference) ? void (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15566, __extension__ __PRETTY_FUNCTION__))
; 15567 15568 OwnedDecl = false; 15569 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15570 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15571 15572 // FIXME: Check member specializations more carefully. 15573 bool isMemberSpecialization = false; 15574 bool Invalid = false; 15575 15576 // We only need to do this matching if we have template parameters 15577 // or a scope specifier, which also conveniently avoids this work 15578 // for non-C++ cases. 15579 if (TemplateParameterLists.size() > 0 || 15580 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15581 if (TemplateParameterList *TemplateParams = 15582 MatchTemplateParametersToScopeSpecifier( 15583 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15584 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15585 if (Kind == TTK_Enum) { 15586 Diag(KWLoc, diag::err_enum_template); 15587 return nullptr; 15588 } 15589 15590 if (TemplateParams->size() > 0) { 15591 // This is a declaration or definition of a class template (which may 15592 // be a member of another template). 15593 15594 if (Invalid) 15595 return nullptr; 15596 15597 OwnedDecl = false; 15598 DeclResult Result = CheckClassTemplate( 15599 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15600 AS, ModulePrivateLoc, 15601 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15602 TemplateParameterLists.data(), SkipBody); 15603 return Result.get(); 15604 } else { 15605 // The "template<>" header is extraneous. 15606 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15607 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15608 isMemberSpecialization = true; 15609 } 15610 } 15611 15612 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15613 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15614 return nullptr; 15615 } 15616 15617 // Figure out the underlying type if this a enum declaration. We need to do 15618 // this early, because it's needed to detect if this is an incompatible 15619 // redeclaration. 15620 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15621 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15622 15623 if (Kind == TTK_Enum) { 15624 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15625 // No underlying type explicitly specified, or we failed to parse the 15626 // type, default to int. 15627 EnumUnderlying = Context.IntTy.getTypePtr(); 15628 } else if (UnderlyingType.get()) { 15629 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15630 // integral type; any cv-qualification is ignored. 15631 TypeSourceInfo *TI = nullptr; 15632 GetTypeFromParser(UnderlyingType.get(), &TI); 15633 EnumUnderlying = TI; 15634 15635 if (CheckEnumUnderlyingType(TI)) 15636 // Recover by falling back to int. 15637 EnumUnderlying = Context.IntTy.getTypePtr(); 15638 15639 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15640 UPPC_FixedUnderlyingType)) 15641 EnumUnderlying = Context.IntTy.getTypePtr(); 15642 15643 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15644 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15645 // of 'int'. However, if this is an unfixed forward declaration, don't set 15646 // the underlying type unless the user enables -fms-compatibility. This 15647 // makes unfixed forward declared enums incomplete and is more conforming. 15648 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15649 EnumUnderlying = Context.IntTy.getTypePtr(); 15650 } 15651 } 15652 15653 DeclContext *SearchDC = CurContext; 15654 DeclContext *DC = CurContext; 15655 bool isStdBadAlloc = false; 15656 bool isStdAlignValT = false; 15657 15658 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15659 if (TUK == TUK_Friend || TUK == TUK_Reference) 15660 Redecl = NotForRedeclaration; 15661 15662 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15663 /// implemented asks for structural equivalence checking, the returned decl 15664 /// here is passed back to the parser, allowing the tag body to be parsed. 15665 auto createTagFromNewDecl = [&]() -> TagDecl * { 15666 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")(static_cast <bool> (!getLangOpts().CPlusPlus &&
"not meant for C++ usage") ? void (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15666, __extension__ __PRETTY_FUNCTION__))
; 15667 // If there is an identifier, use the location of the identifier as the 15668 // location of the decl, otherwise use the location of the struct/union 15669 // keyword. 15670 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15671 TagDecl *New = nullptr; 15672 15673 if (Kind == TTK_Enum) { 15674 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15675 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15676 // If this is an undefined enum, bail. 15677 if (TUK != TUK_Definition && !Invalid) 15678 return nullptr; 15679 if (EnumUnderlying) { 15680 EnumDecl *ED = cast<EnumDecl>(New); 15681 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15682 ED->setIntegerTypeSourceInfo(TI); 15683 else 15684 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15685 ED->setPromotionType(ED->getIntegerType()); 15686 } 15687 } else { // struct/union 15688 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15689 nullptr); 15690 } 15691 15692 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15693 // Add alignment attributes if necessary; these attributes are checked 15694 // when the ASTContext lays out the structure. 15695 // 15696 // It is important for implementing the correct semantics that this 15697 // happen here (in ActOnTag). The #pragma pack stack is 15698 // maintained as a result of parser callbacks which can occur at 15699 // many points during the parsing of a struct declaration (because 15700 // the #pragma tokens are effectively skipped over during the 15701 // parsing of the struct). 15702 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15703 AddAlignmentAttributesForRecord(RD); 15704 AddMsStructLayoutForRecord(RD); 15705 } 15706 } 15707 New->setLexicalDeclContext(CurContext); 15708 return New; 15709 }; 15710 15711 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15712 if (Name && SS.isNotEmpty()) { 15713 // We have a nested-name tag ('struct foo::bar'). 15714 15715 // Check for invalid 'foo::'. 15716 if (SS.isInvalid()) { 15717 Name = nullptr; 15718 goto CreateNewDecl; 15719 } 15720 15721 // If this is a friend or a reference to a class in a dependent 15722 // context, don't try to make a decl for it. 15723 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15724 DC = computeDeclContext(SS, false); 15725 if (!DC) { 15726 IsDependent = true; 15727 return nullptr; 15728 } 15729 } else { 15730 DC = computeDeclContext(SS, true); 15731 if (!DC) { 15732 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15733 << SS.getRange(); 15734 return nullptr; 15735 } 15736 } 15737 15738 if (RequireCompleteDeclContext(SS, DC)) 15739 return nullptr; 15740 15741 SearchDC = DC; 15742 // Look-up name inside 'foo::'. 15743 LookupQualifiedName(Previous, DC); 15744 15745 if (Previous.isAmbiguous()) 15746 return nullptr; 15747 15748 if (Previous.empty()) { 15749 // Name lookup did not find anything. However, if the 15750 // nested-name-specifier refers to the current instantiation, 15751 // and that current instantiation has any dependent base 15752 // classes, we might find something at instantiation time: treat 15753 // this as a dependent elaborated-type-specifier. 15754 // But this only makes any sense for reference-like lookups. 15755 if (Previous.wasNotFoundInCurrentInstantiation() && 15756 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15757 IsDependent = true; 15758 return nullptr; 15759 } 15760 15761 // A tag 'foo::bar' must already exist. 15762 Diag(NameLoc, diag::err_not_tag_in_scope) 15763 << Kind << Name << DC << SS.getRange(); 15764 Name = nullptr; 15765 Invalid = true; 15766 goto CreateNewDecl; 15767 } 15768 } else if (Name) { 15769 // C++14 [class.mem]p14: 15770 // If T is the name of a class, then each of the following shall have a 15771 // name different from T: 15772 // -- every member of class T that is itself a type 15773 if (TUK != TUK_Reference && TUK != TUK_Friend && 15774 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15775 return nullptr; 15776 15777 // If this is a named struct, check to see if there was a previous forward 15778 // declaration or definition. 15779 // FIXME: We're looking into outer scopes here, even when we 15780 // shouldn't be. Doing so can result in ambiguities that we 15781 // shouldn't be diagnosing. 15782 LookupName(Previous, S); 15783 15784 // When declaring or defining a tag, ignore ambiguities introduced 15785 // by types using'ed into this scope. 15786 if (Previous.isAmbiguous() && 15787 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15788 LookupResult::Filter F = Previous.makeFilter(); 15789 while (F.hasNext()) { 15790 NamedDecl *ND = F.next(); 15791 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15792 SearchDC->getRedeclContext())) 15793 F.erase(); 15794 } 15795 F.done(); 15796 } 15797 15798 // C++11 [namespace.memdef]p3: 15799 // If the name in a friend declaration is neither qualified nor 15800 // a template-id and the declaration is a function or an 15801 // elaborated-type-specifier, the lookup to determine whether 15802 // the entity has been previously declared shall not consider 15803 // any scopes outside the innermost enclosing namespace. 15804 // 15805 // MSVC doesn't implement the above rule for types, so a friend tag 15806 // declaration may be a redeclaration of a type declared in an enclosing 15807 // scope. They do implement this rule for friend functions. 15808 // 15809 // Does it matter that this should be by scope instead of by 15810 // semantic context? 15811 if (!Previous.empty() && TUK == TUK_Friend) { 15812 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15813 LookupResult::Filter F = Previous.makeFilter(); 15814 bool FriendSawTagOutsideEnclosingNamespace = false; 15815 while (F.hasNext()) { 15816 NamedDecl *ND = F.next(); 15817 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15818 if (DC->isFileContext() && 15819 !EnclosingNS->Encloses(ND->getDeclContext())) { 15820 if (getLangOpts().MSVCCompat) 15821 FriendSawTagOutsideEnclosingNamespace = true; 15822 else 15823 F.erase(); 15824 } 15825 } 15826 F.done(); 15827 15828 // Diagnose this MSVC extension in the easy case where lookup would have 15829 // unambiguously found something outside the enclosing namespace. 15830 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15831 NamedDecl *ND = Previous.getFoundDecl(); 15832 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15833 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15834 } 15835 } 15836 15837 // Note: there used to be some attempt at recovery here. 15838 if (Previous.isAmbiguous()) 15839 return nullptr; 15840 15841 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15842 // FIXME: This makes sure that we ignore the contexts associated 15843 // with C structs, unions, and enums when looking for a matching 15844 // tag declaration or definition. See the similar lookup tweak 15845 // in Sema::LookupName; is there a better way to deal with this? 15846 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15847 SearchDC = SearchDC->getParent(); 15848 } 15849 } 15850 15851 if (Previous.isSingleResult() && 15852 Previous.getFoundDecl()->isTemplateParameter()) { 15853 // Maybe we will complain about the shadowed template parameter. 15854 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15855 // Just pretend that we didn't see the previous declaration. 15856 Previous.clear(); 15857 } 15858 15859 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15860 DC->Equals(getStdNamespace())) { 15861 if (Name->isStr("bad_alloc")) { 15862 // This is a declaration of or a reference to "std::bad_alloc". 15863 isStdBadAlloc = true; 15864 15865 // If std::bad_alloc has been implicitly declared (but made invisible to 15866 // name lookup), fill in this implicit declaration as the previous 15867 // declaration, so that the declarations get chained appropriately. 15868 if (Previous.empty() && StdBadAlloc) 15869 Previous.addDecl(getStdBadAlloc()); 15870 } else if (Name->isStr("align_val_t")) { 15871 isStdAlignValT = true; 15872 if (Previous.empty() && StdAlignValT) 15873 Previous.addDecl(getStdAlignValT()); 15874 } 15875 } 15876 15877 // If we didn't find a previous declaration, and this is a reference 15878 // (or friend reference), move to the correct scope. In C++, we 15879 // also need to do a redeclaration lookup there, just in case 15880 // there's a shadow friend decl. 15881 if (Name && Previous.empty() && 15882 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15883 if (Invalid) goto CreateNewDecl; 15884 assert(SS.isEmpty())(static_cast <bool> (SS.isEmpty()) ? void (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15884, __extension__ __PRETTY_FUNCTION__))
; 15885 15886 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15887 // C++ [basic.scope.pdecl]p5: 15888 // -- for an elaborated-type-specifier of the form 15889 // 15890 // class-key identifier 15891 // 15892 // if the elaborated-type-specifier is used in the 15893 // decl-specifier-seq or parameter-declaration-clause of a 15894 // function defined in namespace scope, the identifier is 15895 // declared as a class-name in the namespace that contains 15896 // the declaration; otherwise, except as a friend 15897 // declaration, the identifier is declared in the smallest 15898 // non-class, non-function-prototype scope that contains the 15899 // declaration. 15900 // 15901 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15902 // C structs and unions. 15903 // 15904 // It is an error in C++ to declare (rather than define) an enum 15905 // type, including via an elaborated type specifier. We'll 15906 // diagnose that later; for now, declare the enum in the same 15907 // scope as we would have picked for any other tag type. 15908 // 15909 // GNU C also supports this behavior as part of its incomplete 15910 // enum types extension, while GNU C++ does not. 15911 // 15912 // Find the context where we'll be declaring the tag. 15913 // FIXME: We would like to maintain the current DeclContext as the 15914 // lexical context, 15915 SearchDC = getTagInjectionContext(SearchDC); 15916 15917 // Find the scope where we'll be declaring the tag. 15918 S = getTagInjectionScope(S, getLangOpts()); 15919 } else { 15920 assert(TUK == TUK_Friend)(static_cast <bool> (TUK == TUK_Friend) ? void (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 15920, __extension__ __PRETTY_FUNCTION__))
; 15921 // C++ [namespace.memdef]p3: 15922 // If a friend declaration in a non-local class first declares a 15923 // class or function, the friend class or function is a member of 15924 // the innermost enclosing namespace. 15925 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15926 } 15927 15928 // In C++, we need to do a redeclaration lookup to properly 15929 // diagnose some problems. 15930 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15931 // hidden declaration so that we don't get ambiguity errors when using a 15932 // type declared by an elaborated-type-specifier. In C that is not correct 15933 // and we should instead merge compatible types found by lookup. 15934 if (getLangOpts().CPlusPlus) { 15935 // FIXME: This can perform qualified lookups into function contexts, 15936 // which are meaningless. 15937 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15938 LookupQualifiedName(Previous, SearchDC); 15939 } else { 15940 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15941 LookupName(Previous, S); 15942 } 15943 } 15944 15945 // If we have a known previous declaration to use, then use it. 15946 if (Previous.empty() && SkipBody && SkipBody->Previous) 15947 Previous.addDecl(SkipBody->Previous); 15948 15949 if (!Previous.empty()) { 15950 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15951 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15952 15953 // It's okay to have a tag decl in the same scope as a typedef 15954 // which hides a tag decl in the same scope. Finding this 15955 // insanity with a redeclaration lookup can only actually happen 15956 // in C++. 15957 // 15958 // This is also okay for elaborated-type-specifiers, which is 15959 // technically forbidden by the current standard but which is 15960 // okay according to the likely resolution of an open issue; 15961 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15962 if (getLangOpts().CPlusPlus) { 15963 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15964 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15965 TagDecl *Tag = TT->getDecl(); 15966 if (Tag->getDeclName() == Name && 15967 Tag->getDeclContext()->getRedeclContext() 15968 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15969 PrevDecl = Tag; 15970 Previous.clear(); 15971 Previous.addDecl(Tag); 15972 Previous.resolveKind(); 15973 } 15974 } 15975 } 15976 } 15977 15978 // If this is a redeclaration of a using shadow declaration, it must 15979 // declare a tag in the same context. In MSVC mode, we allow a 15980 // redefinition if either context is within the other. 15981 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15982 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15983 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15984 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15985 !(OldTag && isAcceptableTagRedeclContext( 15986 *this, OldTag->getDeclContext(), SearchDC))) { 15987 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15988 Diag(Shadow->getTargetDecl()->getLocation(), 15989 diag::note_using_decl_target); 15990 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 15991 << 0; 15992 // Recover by ignoring the old declaration. 15993 Previous.clear(); 15994 goto CreateNewDecl; 15995 } 15996 } 15997 15998 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15999 // If this is a use of a previous tag, or if the tag is already declared 16000 // in the same scope (so that the definition/declaration completes or 16001 // rementions the tag), reuse the decl. 16002 if (TUK == TUK_Reference || TUK == TUK_Friend || 16003 isDeclInScope(DirectPrevDecl, SearchDC, S, 16004 SS.isNotEmpty() || isMemberSpecialization)) { 16005 // Make sure that this wasn't declared as an enum and now used as a 16006 // struct or something similar. 16007 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16008 TUK == TUK_Definition, KWLoc, 16009 Name)) { 16010 bool SafeToContinue 16011 = (PrevTagDecl->getTagKind() != TTK_Enum && 16012 Kind != TTK_Enum); 16013 if (SafeToContinue) 16014 Diag(KWLoc, diag::err_use_with_wrong_tag) 16015 << Name 16016 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16017 PrevTagDecl->getKindName()); 16018 else 16019 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16020 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16021 16022 if (SafeToContinue) 16023 Kind = PrevTagDecl->getTagKind(); 16024 else { 16025 // Recover by making this an anonymous redefinition. 16026 Name = nullptr; 16027 Previous.clear(); 16028 Invalid = true; 16029 } 16030 } 16031 16032 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16033 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16034 if (TUK == TUK_Reference || TUK == TUK_Friend) 16035 return PrevTagDecl; 16036 16037 QualType EnumUnderlyingTy; 16038 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16039 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16040 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16041 EnumUnderlyingTy = QualType(T, 0); 16042 16043 // All conflicts with previous declarations are recovered by 16044 // returning the previous declaration, unless this is a definition, 16045 // in which case we want the caller to bail out. 16046 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16047 ScopedEnum, EnumUnderlyingTy, 16048 IsFixed, PrevEnum)) 16049 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16050 } 16051 16052 // C++11 [class.mem]p1: 16053 // A member shall not be declared twice in the member-specification, 16054 // except that a nested class or member class template can be declared 16055 // and then later defined. 16056 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16057 S->isDeclScope(PrevDecl)) { 16058 Diag(NameLoc, diag::ext_member_redeclared); 16059 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16060 } 16061 16062 if (!Invalid) { 16063 // If this is a use, just return the declaration we found, unless 16064 // we have attributes. 16065 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16066 if (!Attrs.empty()) { 16067 // FIXME: Diagnose these attributes. For now, we create a new 16068 // declaration to hold them. 16069 } else if (TUK == TUK_Reference && 16070 (PrevTagDecl->getFriendObjectKind() == 16071 Decl::FOK_Undeclared || 16072 PrevDecl->getOwningModule() != getCurrentModule()) && 16073 SS.isEmpty()) { 16074 // This declaration is a reference to an existing entity, but 16075 // has different visibility from that entity: it either makes 16076 // a friend visible or it makes a type visible in a new module. 16077 // In either case, create a new declaration. We only do this if 16078 // the declaration would have meant the same thing if no prior 16079 // declaration were found, that is, if it was found in the same 16080 // scope where we would have injected a declaration. 16081 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16082 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16083 return PrevTagDecl; 16084 // This is in the injected scope, create a new declaration in 16085 // that scope. 16086 S = getTagInjectionScope(S, getLangOpts()); 16087 } else { 16088 return PrevTagDecl; 16089 } 16090 } 16091 16092 // Diagnose attempts to redefine a tag. 16093 if (TUK == TUK_Definition) { 16094 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16095 // If we're defining a specialization and the previous definition 16096 // is from an implicit instantiation, don't emit an error 16097 // here; we'll catch this in the general case below. 16098 bool IsExplicitSpecializationAfterInstantiation = false; 16099 if (isMemberSpecialization) { 16100 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16101 IsExplicitSpecializationAfterInstantiation = 16102 RD->getTemplateSpecializationKind() != 16103 TSK_ExplicitSpecialization; 16104 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16105 IsExplicitSpecializationAfterInstantiation = 16106 ED->getTemplateSpecializationKind() != 16107 TSK_ExplicitSpecialization; 16108 } 16109 16110 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16111 // not keep more that one definition around (merge them). However, 16112 // ensure the decl passes the structural compatibility check in 16113 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16114 NamedDecl *Hidden = nullptr; 16115 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16116 // There is a definition of this tag, but it is not visible. We 16117 // explicitly make use of C++'s one definition rule here, and 16118 // assume that this definition is identical to the hidden one 16119 // we already have. Make the existing definition visible and 16120 // use it in place of this one. 16121 if (!getLangOpts().CPlusPlus) { 16122 // Postpone making the old definition visible until after we 16123 // complete parsing the new one and do the structural 16124 // comparison. 16125 SkipBody->CheckSameAsPrevious = true; 16126 SkipBody->New = createTagFromNewDecl(); 16127 SkipBody->Previous = Def; 16128 return Def; 16129 } else { 16130 SkipBody->ShouldSkip = true; 16131 SkipBody->Previous = Def; 16132 makeMergedDefinitionVisible(Hidden); 16133 // Carry on and handle it like a normal definition. We'll 16134 // skip starting the definitiion later. 16135 } 16136 } else if (!IsExplicitSpecializationAfterInstantiation) { 16137 // A redeclaration in function prototype scope in C isn't 16138 // visible elsewhere, so merely issue a warning. 16139 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16140 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16141 else 16142 Diag(NameLoc, diag::err_redefinition) << Name; 16143 notePreviousDefinition(Def, 16144 NameLoc.isValid() ? NameLoc : KWLoc); 16145 // If this is a redefinition, recover by making this 16146 // struct be anonymous, which will make any later 16147 // references get the previous definition. 16148 Name = nullptr; 16149 Previous.clear(); 16150 Invalid = true; 16151 } 16152 } else { 16153 // If the type is currently being defined, complain 16154 // about a nested redefinition. 16155 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16156 if (TD->isBeingDefined()) { 16157 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16158 Diag(PrevTagDecl->getLocation(), 16159 diag::note_previous_definition); 16160 Name = nullptr; 16161 Previous.clear(); 16162 Invalid = true; 16163 } 16164 } 16165 16166 // Okay, this is definition of a previously declared or referenced 16167 // tag. We're going to create a new Decl for it. 16168 } 16169 16170 // Okay, we're going to make a redeclaration. If this is some kind 16171 // of reference, make sure we build the redeclaration in the same DC 16172 // as the original, and ignore the current access specifier. 16173 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16174 SearchDC = PrevTagDecl->getDeclContext(); 16175 AS = AS_none; 16176 } 16177 } 16178 // If we get here we have (another) forward declaration or we 16179 // have a definition. Just create a new decl. 16180 16181 } else { 16182 // If we get here, this is a definition of a new tag type in a nested 16183 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16184 // new decl/type. We set PrevDecl to NULL so that the entities 16185 // have distinct types. 16186 Previous.clear(); 16187 } 16188 // If we get here, we're going to create a new Decl. If PrevDecl 16189 // is non-NULL, it's a definition of the tag declared by 16190 // PrevDecl. If it's NULL, we have a new definition. 16191 16192 // Otherwise, PrevDecl is not a tag, but was found with tag 16193 // lookup. This is only actually possible in C++, where a few 16194 // things like templates still live in the tag namespace. 16195 } else { 16196 // Use a better diagnostic if an elaborated-type-specifier 16197 // found the wrong kind of type on the first 16198 // (non-redeclaration) lookup. 16199 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16200 !Previous.isForRedeclaration()) { 16201 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16202 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16203 << Kind; 16204 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16205 Invalid = true; 16206 16207 // Otherwise, only diagnose if the declaration is in scope. 16208 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16209 SS.isNotEmpty() || isMemberSpecialization)) { 16210 // do nothing 16211 16212 // Diagnose implicit declarations introduced by elaborated types. 16213 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16214 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16215 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16216 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16217 Invalid = true; 16218 16219 // Otherwise it's a declaration. Call out a particularly common 16220 // case here. 16221 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16222 unsigned Kind = 0; 16223 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16224 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16225 << Name << Kind << TND->getUnderlyingType(); 16226 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16227 Invalid = true; 16228 16229 // Otherwise, diagnose. 16230 } else { 16231 // The tag name clashes with something else in the target scope, 16232 // issue an error and recover by making this tag be anonymous. 16233 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16234 notePreviousDefinition(PrevDecl, NameLoc); 16235 Name = nullptr; 16236 Invalid = true; 16237 } 16238 16239 // The existing declaration isn't relevant to us; we're in a 16240 // new scope, so clear out the previous declaration. 16241 Previous.clear(); 16242 } 16243 } 16244 16245CreateNewDecl: 16246 16247 TagDecl *PrevDecl = nullptr; 16248 if (Previous.isSingleResult()) 16249 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16250 16251 // If there is an identifier, use the location of the identifier as the 16252 // location of the decl, otherwise use the location of the struct/union 16253 // keyword. 16254 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16255 16256 // Otherwise, create a new declaration. If there is a previous 16257 // declaration of the same entity, the two will be linked via 16258 // PrevDecl. 16259 TagDecl *New; 16260 16261 if (Kind == TTK_Enum) { 16262 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16263 // enum X { A, B, C } D; D should chain to X. 16264 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16265 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16266 ScopedEnumUsesClassTag, IsFixed); 16267 16268 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16269 StdAlignValT = cast<EnumDecl>(New); 16270 16271 // If this is an undefined enum, warn. 16272 if (TUK != TUK_Definition && !Invalid) { 16273 TagDecl *Def; 16274 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16275 // C++0x: 7.2p2: opaque-enum-declaration. 16276 // Conflicts are diagnosed above. Do nothing. 16277 } 16278 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16279 Diag(Loc, diag::ext_forward_ref_enum_def) 16280 << New; 16281 Diag(Def->getLocation(), diag::note_previous_definition); 16282 } else { 16283 unsigned DiagID = diag::ext_forward_ref_enum; 16284 if (getLangOpts().MSVCCompat) 16285 DiagID = diag::ext_ms_forward_ref_enum; 16286 else if (getLangOpts().CPlusPlus) 16287 DiagID = diag::err_forward_ref_enum; 16288 Diag(Loc, DiagID); 16289 } 16290 } 16291 16292 if (EnumUnderlying) { 16293 EnumDecl *ED = cast<EnumDecl>(New); 16294 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16295 ED->setIntegerTypeSourceInfo(TI); 16296 else 16297 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16298 ED->setPromotionType(ED->getIntegerType()); 16299 assert(ED->isComplete() && "enum with type should be complete")(static_cast <bool> (ED->isComplete() && "enum with type should be complete"
) ? void (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16299, __extension__ __PRETTY_FUNCTION__))
; 16300 } 16301 } else { 16302 // struct/union/class 16303 16304 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16305 // struct X { int A; } D; D should chain to X. 16306 if (getLangOpts().CPlusPlus) { 16307 // FIXME: Look for a way to use RecordDecl for simple structs. 16308 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16309 cast_or_null<CXXRecordDecl>(PrevDecl)); 16310 16311 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16312 StdBadAlloc = cast<CXXRecordDecl>(New); 16313 } else 16314 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16315 cast_or_null<RecordDecl>(PrevDecl)); 16316 } 16317 16318 // C++11 [dcl.type]p3: 16319 // A type-specifier-seq shall not define a class or enumeration [...]. 16320 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16321 TUK == TUK_Definition) { 16322 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16323 << Context.getTagDeclType(New); 16324 Invalid = true; 16325 } 16326 16327 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16328 DC->getDeclKind() == Decl::Enum) { 16329 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16330 << Context.getTagDeclType(New); 16331 Invalid = true; 16332 } 16333 16334 // Maybe add qualifier info. 16335 if (SS.isNotEmpty()) { 16336 if (SS.isSet()) { 16337 // If this is either a declaration or a definition, check the 16338 // nested-name-specifier against the current context. 16339 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16340 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16341 isMemberSpecialization)) 16342 Invalid = true; 16343 16344 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16345 if (TemplateParameterLists.size() > 0) { 16346 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16347 } 16348 } 16349 else 16350 Invalid = true; 16351 } 16352 16353 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16354 // Add alignment attributes if necessary; these attributes are checked when 16355 // the ASTContext lays out the structure. 16356 // 16357 // It is important for implementing the correct semantics that this 16358 // happen here (in ActOnTag). The #pragma pack stack is 16359 // maintained as a result of parser callbacks which can occur at 16360 // many points during the parsing of a struct declaration (because 16361 // the #pragma tokens are effectively skipped over during the 16362 // parsing of the struct). 16363 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16364 AddAlignmentAttributesForRecord(RD); 16365 AddMsStructLayoutForRecord(RD); 16366 } 16367 } 16368 16369 if (ModulePrivateLoc.isValid()) { 16370 if (isMemberSpecialization) 16371 Diag(New->getLocation(), diag::err_module_private_specialization) 16372 << 2 16373 << FixItHint::CreateRemoval(ModulePrivateLoc); 16374 // __module_private__ does not apply to local classes. However, we only 16375 // diagnose this as an error when the declaration specifiers are 16376 // freestanding. Here, we just ignore the __module_private__. 16377 else if (!SearchDC->isFunctionOrMethod()) 16378 New->setModulePrivate(); 16379 } 16380 16381 // If this is a specialization of a member class (of a class template), 16382 // check the specialization. 16383 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16384 Invalid = true; 16385 16386 // If we're declaring or defining a tag in function prototype scope in C, 16387 // note that this type can only be used within the function and add it to 16388 // the list of decls to inject into the function definition scope. 16389 if ((Name || Kind == TTK_Enum) && 16390 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16391 if (getLangOpts().CPlusPlus) { 16392 // C++ [dcl.fct]p6: 16393 // Types shall not be defined in return or parameter types. 16394 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16395 Diag(Loc, diag::err_type_defined_in_param_type) 16396 << Name; 16397 Invalid = true; 16398 } 16399 } else if (!PrevDecl) { 16400 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16401 } 16402 } 16403 16404 if (Invalid) 16405 New->setInvalidDecl(); 16406 16407 // Set the lexical context. If the tag has a C++ scope specifier, the 16408 // lexical context will be different from the semantic context. 16409 New->setLexicalDeclContext(CurContext); 16410 16411 // Mark this as a friend decl if applicable. 16412 // In Microsoft mode, a friend declaration also acts as a forward 16413 // declaration so we always pass true to setObjectOfFriendDecl to make 16414 // the tag name visible. 16415 if (TUK == TUK_Friend) 16416 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16417 16418 // Set the access specifier. 16419 if (!Invalid && SearchDC->isRecord()) 16420 SetMemberAccessSpecifier(New, PrevDecl, AS); 16421 16422 if (PrevDecl) 16423 CheckRedeclarationModuleOwnership(New, PrevDecl); 16424 16425 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16426 New->startDefinition(); 16427 16428 ProcessDeclAttributeList(S, New, Attrs); 16429 AddPragmaAttributes(S, New); 16430 16431 // If this has an identifier, add it to the scope stack. 16432 if (TUK == TUK_Friend) { 16433 // We might be replacing an existing declaration in the lookup tables; 16434 // if so, borrow its access specifier. 16435 if (PrevDecl) 16436 New->setAccess(PrevDecl->getAccess()); 16437 16438 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16439 DC->makeDeclVisibleInContext(New); 16440 if (Name) // can be null along some error paths 16441 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16442 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16443 } else if (Name) { 16444 S = getNonFieldDeclScope(S); 16445 PushOnScopeChains(New, S, true); 16446 } else { 16447 CurContext->addDecl(New); 16448 } 16449 16450 // If this is the C FILE type, notify the AST context. 16451 if (IdentifierInfo *II = New->getIdentifier()) 16452 if (!New->isInvalidDecl() && 16453 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16454 II->isStr("FILE")) 16455 Context.setFILEDecl(New); 16456 16457 if (PrevDecl) 16458 mergeDeclAttributes(New, PrevDecl); 16459 16460 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16461 inferGslOwnerPointerAttribute(CXXRD); 16462 16463 // If there's a #pragma GCC visibility in scope, set the visibility of this 16464 // record. 16465 AddPushedVisibilityAttribute(New); 16466 16467 if (isMemberSpecialization && !New->isInvalidDecl()) 16468 CompleteMemberSpecialization(New, Previous); 16469 16470 OwnedDecl = true; 16471 // In C++, don't return an invalid declaration. We can't recover well from 16472 // the cases where we make the type anonymous. 16473 if (Invalid && getLangOpts().CPlusPlus) { 16474 if (New->isBeingDefined()) 16475 if (auto RD = dyn_cast<RecordDecl>(New)) 16476 RD->completeDefinition(); 16477 return nullptr; 16478 } else if (SkipBody && SkipBody->ShouldSkip) { 16479 return SkipBody->Previous; 16480 } else { 16481 return New; 16482 } 16483} 16484 16485void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16486 AdjustDeclIfTemplate(TagD); 16487 TagDecl *Tag = cast<TagDecl>(TagD); 16488 16489 // Enter the tag context. 16490 PushDeclContext(S, Tag); 16491 16492 ActOnDocumentableDecl(TagD); 16493 16494 // If there's a #pragma GCC visibility in scope, set the visibility of this 16495 // record. 16496 AddPushedVisibilityAttribute(Tag); 16497} 16498 16499bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16500 SkipBodyInfo &SkipBody) { 16501 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16502 return false; 16503 16504 // Make the previous decl visible. 16505 makeMergedDefinitionVisible(SkipBody.Previous); 16506 return true; 16507} 16508 16509Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16510 assert(isa<ObjCContainerDecl>(IDecl) &&(static_cast <bool> (isa<ObjCContainerDecl>(IDecl
) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16511, __extension__ __PRETTY_FUNCTION__))
16511 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")(static_cast <bool> (isa<ObjCContainerDecl>(IDecl
) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16511, __extension__ __PRETTY_FUNCTION__))
; 16512 DeclContext *OCD = cast<DeclContext>(IDecl); 16513 assert(OCD->getLexicalParent() == CurContext &&(static_cast <bool> (OCD->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16514, __extension__ __PRETTY_FUNCTION__))
16514 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (OCD->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16514, __extension__ __PRETTY_FUNCTION__))
; 16515 CurContext = OCD; 16516 return IDecl; 16517} 16518 16519void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16520 SourceLocation FinalLoc, 16521 bool IsFinalSpelledSealed, 16522 bool IsAbstract, 16523 SourceLocation LBraceLoc) { 16524 AdjustDeclIfTemplate(TagD); 16525 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16526 16527 FieldCollector->StartClass(); 16528 16529 if (!Record->getIdentifier()) 16530 return; 16531 16532 if (IsAbstract) 16533 Record->markAbstract(); 16534 16535 if (FinalLoc.isValid()) { 16536 Record->addAttr(FinalAttr::Create( 16537 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16538 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16539 } 16540 // C++ [class]p2: 16541 // [...] The class-name is also inserted into the scope of the 16542 // class itself; this is known as the injected-class-name. For 16543 // purposes of access checking, the injected-class-name is treated 16544 // as if it were a public member name. 16545 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16546 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16547 Record->getLocation(), Record->getIdentifier(), 16548 /*PrevDecl=*/nullptr, 16549 /*DelayTypeCreation=*/true); 16550 Context.getTypeDeclType(InjectedClassName, Record); 16551 InjectedClassName->setImplicit(); 16552 InjectedClassName->setAccess(AS_public); 16553 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16554 InjectedClassName->setDescribedClassTemplate(Template); 16555 PushOnScopeChains(InjectedClassName, S); 16556 assert(InjectedClassName->isInjectedClassName() &&(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16557, __extension__ __PRETTY_FUNCTION__))
16557 "Broken injected-class-name")(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16557, __extension__ __PRETTY_FUNCTION__))
; 16558} 16559 16560void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16561 SourceRange BraceRange) { 16562 AdjustDeclIfTemplate(TagD); 16563 TagDecl *Tag = cast<TagDecl>(TagD); 16564 Tag->setBraceRange(BraceRange); 16565 16566 // Make sure we "complete" the definition even it is invalid. 16567 if (Tag->isBeingDefined()) { 16568 assert(Tag->isInvalidDecl() && "We should already have completed it")(static_cast <bool> (Tag->isInvalidDecl() &&
"We should already have completed it") ? void (0) : __assert_fail
("Tag->isInvalidDecl() && \"We should already have completed it\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16568, __extension__ __PRETTY_FUNCTION__))
; 16569 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16570 RD->completeDefinition(); 16571 } 16572 16573 if (isa<CXXRecordDecl>(Tag)) { 16574 FieldCollector->FinishClass(); 16575 } 16576 16577 // Exit this scope of this tag's definition. 16578 PopDeclContext(); 16579 16580 if (getCurLexicalContext()->isObjCContainer() && 16581 Tag->getDeclContext()->isFileContext()) 16582 Tag->setTopLevelDeclInObjCContainer(); 16583 16584 // Notify the consumer that we've defined a tag. 16585 if (!Tag->isInvalidDecl()) 16586 Consumer.HandleTagDeclDefinition(Tag); 16587} 16588 16589void Sema::ActOnObjCContainerFinishDefinition() { 16590 // Exit this scope of this interface definition. 16591 PopDeclContext(); 16592} 16593 16594void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16595 assert(DC == CurContext && "Mismatch of container contexts")(static_cast <bool> (DC == CurContext && "Mismatch of container contexts"
) ? void (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16595, __extension__ __PRETTY_FUNCTION__))
; 16596 OriginalLexicalContext = DC; 16597 ActOnObjCContainerFinishDefinition(); 16598} 16599 16600void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16601 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16602 OriginalLexicalContext = nullptr; 16603} 16604 16605void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16606 AdjustDeclIfTemplate(TagD); 16607 TagDecl *Tag = cast<TagDecl>(TagD); 16608 Tag->setInvalidDecl(); 16609 16610 // Make sure we "complete" the definition even it is invalid. 16611 if (Tag->isBeingDefined()) { 16612 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16613 RD->completeDefinition(); 16614 } 16615 16616 // We're undoing ActOnTagStartDefinition here, not 16617 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16618 // the FieldCollector. 16619 16620 PopDeclContext(); 16621} 16622 16623// Note that FieldName may be null for anonymous bitfields. 16624ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16625 IdentifierInfo *FieldName, 16626 QualType FieldTy, bool IsMsStruct, 16627 Expr *BitWidth, bool *ZeroWidth) { 16628 assert(BitWidth)(static_cast <bool> (BitWidth) ? void (0) : __assert_fail
("BitWidth", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 16628, __extension__ __PRETTY_FUNCTION__))
; 16629 if (BitWidth->containsErrors()) 16630 return ExprError(); 16631 16632 // Default to true; that shouldn't confuse checks for emptiness 16633 if (ZeroWidth) 16634 *ZeroWidth = true; 16635 16636 // C99 6.7.2.1p4 - verify the field type. 16637 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16638 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16639 // Handle incomplete and sizeless types with a specific error. 16640 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16641 diag::err_field_incomplete_or_sizeless)) 16642 return ExprError(); 16643 if (FieldName) 16644 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16645 << FieldName << FieldTy << BitWidth->getSourceRange(); 16646 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16647 << FieldTy << BitWidth->getSourceRange(); 16648 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16649 UPPC_BitFieldWidth)) 16650 return ExprError(); 16651 16652 // If the bit-width is type- or value-dependent, don't try to check 16653 // it now. 16654 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16655 return BitWidth; 16656 16657 llvm::APSInt Value; 16658 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16659 if (ICE.isInvalid()) 16660 return ICE; 16661 BitWidth = ICE.get(); 16662 16663 if (Value != 0 && ZeroWidth) 16664 *ZeroWidth = false; 16665 16666 // Zero-width bitfield is ok for anonymous field. 16667 if (Value == 0 && FieldName) 16668 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16669 16670 if (Value.isSigned() && Value.isNegative()) { 16671 if (FieldName) 16672 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16673 << FieldName << toString(Value, 10); 16674 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16675 << toString(Value, 10); 16676 } 16677 16678 // The size of the bit-field must not exceed our maximum permitted object 16679 // size. 16680 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16681 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16682 << !FieldName << FieldName << toString(Value, 10); 16683 } 16684 16685 if (!FieldTy->isDependentType()) { 16686 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16687 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16688 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16689 16690 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16691 // ABI. 16692 bool CStdConstraintViolation = 16693 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16694 bool MSBitfieldViolation = 16695 Value.ugt(TypeStorageSize) && 16696 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16697 if (CStdConstraintViolation || MSBitfieldViolation) { 16698 unsigned DiagWidth = 16699 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16700 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16701 << (bool)FieldName << FieldName << toString(Value, 10) 16702 << !CStdConstraintViolation << DiagWidth; 16703 } 16704 16705 // Warn on types where the user might conceivably expect to get all 16706 // specified bits as value bits: that's all integral types other than 16707 // 'bool'. 16708 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16709 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16710 << FieldName << toString(Value, 10) 16711 << (unsigned)TypeWidth; 16712 } 16713 } 16714 16715 return BitWidth; 16716} 16717 16718/// ActOnField - Each field of a C struct/union is passed into this in order 16719/// to create a FieldDecl object for it. 16720Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16721 Declarator &D, Expr *BitfieldWidth) { 16722 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16723 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16724 /*InitStyle=*/ICIS_NoInit, AS_public); 16725 return Res; 16726} 16727 16728/// HandleField - Analyze a field of a C struct or a C++ data member. 16729/// 16730FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16731 SourceLocation DeclStart, 16732 Declarator &D, Expr *BitWidth, 16733 InClassInitStyle InitStyle, 16734 AccessSpecifier AS) { 16735 if (D.isDecompositionDeclarator()) { 16736 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16737 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16738 << Decomp.getSourceRange(); 16739 return nullptr; 16740 } 16741 16742 IdentifierInfo *II = D.getIdentifier(); 16743 SourceLocation Loc = DeclStart; 16744 if (II) Loc = D.getIdentifierLoc(); 16745 16746 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16747 QualType T = TInfo->getType(); 16748 if (getLangOpts().CPlusPlus) { 16749 CheckExtraCXXDefaultArguments(D); 16750 16751 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16752 UPPC_DataMemberType)) { 16753 D.setInvalidType(); 16754 T = Context.IntTy; 16755 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16756 } 16757 } 16758 16759 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16760 16761 if (D.getDeclSpec().isInlineSpecified()) 16762 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16763 << getLangOpts().CPlusPlus17; 16764 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16765 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16766 diag::err_invalid_thread) 16767 << DeclSpec::getSpecifierName(TSCS); 16768 16769 // Check to see if this name was declared as a member previously 16770 NamedDecl *PrevDecl = nullptr; 16771 LookupResult Previous(*this, II, Loc, LookupMemberName, 16772 ForVisibleRedeclaration); 16773 LookupName(Previous, S); 16774 switch (Previous.getResultKind()) { 16775 case LookupResult::Found: 16776 case LookupResult::FoundUnresolvedValue: 16777 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16778 break; 16779 16780 case LookupResult::FoundOverloaded: 16781 PrevDecl = Previous.getRepresentativeDecl(); 16782 break; 16783 16784 case LookupResult::NotFound: 16785 case LookupResult::NotFoundInCurrentInstantiation: 16786 case LookupResult::Ambiguous: 16787 break; 16788 } 16789 Previous.suppressDiagnostics(); 16790 16791 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16792 // Maybe we will complain about the shadowed template parameter. 16793 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16794 // Just pretend that we didn't see the previous declaration. 16795 PrevDecl = nullptr; 16796 } 16797 16798 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16799 PrevDecl = nullptr; 16800 16801 bool Mutable 16802 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16803 SourceLocation TSSL = D.getBeginLoc(); 16804 FieldDecl *NewFD 16805 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16806 TSSL, AS, PrevDecl, &D); 16807 16808 if (NewFD->isInvalidDecl()) 16809 Record->setInvalidDecl(); 16810 16811 if (D.getDeclSpec().isModulePrivateSpecified()) 16812 NewFD->setModulePrivate(); 16813 16814 if (NewFD->isInvalidDecl() && PrevDecl) { 16815 // Don't introduce NewFD into scope; there's already something 16816 // with the same name in the same scope. 16817 } else if (II) { 16818 PushOnScopeChains(NewFD, S); 16819 } else 16820 Record->addDecl(NewFD); 16821 16822 return NewFD; 16823} 16824 16825/// Build a new FieldDecl and check its well-formedness. 16826/// 16827/// This routine builds a new FieldDecl given the fields name, type, 16828/// record, etc. \p PrevDecl should refer to any previous declaration 16829/// with the same name and in the same scope as the field to be 16830/// created. 16831/// 16832/// \returns a new FieldDecl. 16833/// 16834/// \todo The Declarator argument is a hack. It will be removed once 16835FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16836 TypeSourceInfo *TInfo, 16837 RecordDecl *Record, SourceLocation Loc, 16838 bool Mutable, Expr *BitWidth, 16839 InClassInitStyle InitStyle, 16840 SourceLocation TSSL, 16841 AccessSpecifier AS, NamedDecl *PrevDecl, 16842 Declarator *D) { 16843 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16844 bool InvalidDecl = false; 16845 if (D) InvalidDecl = D->isInvalidType(); 16846 16847 // If we receive a broken type, recover by assuming 'int' and 16848 // marking this declaration as invalid. 16849 if (T.isNull() || T->containsErrors()) { 16850 InvalidDecl = true; 16851 T = Context.IntTy; 16852 } 16853 16854 QualType EltTy = Context.getBaseElementType(T); 16855 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16856 if (RequireCompleteSizedType(Loc, EltTy, 16857 diag::err_field_incomplete_or_sizeless)) { 16858 // Fields of incomplete type force their record to be invalid. 16859 Record->setInvalidDecl(); 16860 InvalidDecl = true; 16861 } else { 16862 NamedDecl *Def; 16863 EltTy->isIncompleteType(&Def); 16864 if (Def && Def->isInvalidDecl()) { 16865 Record->setInvalidDecl(); 16866 InvalidDecl = true; 16867 } 16868 } 16869 } 16870 16871 // TR 18037 does not allow fields to be declared with address space 16872 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16873 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16874 Diag(Loc, diag::err_field_with_address_space); 16875 Record->setInvalidDecl(); 16876 InvalidDecl = true; 16877 } 16878 16879 if (LangOpts.OpenCL) { 16880 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16881 // used as structure or union field: image, sampler, event or block types. 16882 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16883 T->isBlockPointerType()) { 16884 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16885 Record->setInvalidDecl(); 16886 InvalidDecl = true; 16887 } 16888 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 16889 // is enabled. 16890 if (BitWidth && !getOpenCLOptions().isAvailableOption( 16891 "__cl_clang_bitfields", LangOpts)) { 16892 Diag(Loc, diag::err_opencl_bitfields); 16893 InvalidDecl = true; 16894 } 16895 } 16896 16897 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16898 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16899 T.hasQualifiers()) { 16900 InvalidDecl = true; 16901 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16902 } 16903 16904 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16905 // than a variably modified type. 16906 if (!InvalidDecl && T->isVariablyModifiedType()) { 16907 if (!tryToFixVariablyModifiedVarType( 16908 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 16909 InvalidDecl = true; 16910 } 16911 16912 // Fields can not have abstract class types 16913 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16914 diag::err_abstract_type_in_decl, 16915 AbstractFieldType)) 16916 InvalidDecl = true; 16917 16918 bool ZeroWidth = false; 16919 if (InvalidDecl) 16920 BitWidth = nullptr; 16921 // If this is declared as a bit-field, check the bit-field. 16922 if (BitWidth) { 16923 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16924 &ZeroWidth).get(); 16925 if (!BitWidth) { 16926 InvalidDecl = true; 16927 BitWidth = nullptr; 16928 ZeroWidth = false; 16929 } 16930 } 16931 16932 // Check that 'mutable' is consistent with the type of the declaration. 16933 if (!InvalidDecl && Mutable) { 16934 unsigned DiagID = 0; 16935 if (T->isReferenceType()) 16936 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16937 : diag::err_mutable_reference; 16938 else if (T.isConstQualified()) 16939 DiagID = diag::err_mutable_const; 16940 16941 if (DiagID) { 16942 SourceLocation ErrLoc = Loc; 16943 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16944 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16945 Diag(ErrLoc, DiagID); 16946 if (DiagID != diag::ext_mutable_reference) { 16947 Mutable = false; 16948 InvalidDecl = true; 16949 } 16950 } 16951 } 16952 16953 // C++11 [class.union]p8 (DR1460): 16954 // At most one variant member of a union may have a 16955 // brace-or-equal-initializer. 16956 if (InitStyle != ICIS_NoInit) 16957 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16958 16959 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16960 BitWidth, Mutable, InitStyle); 16961 if (InvalidDecl) 16962 NewFD->setInvalidDecl(); 16963 16964 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16965 Diag(Loc, diag::err_duplicate_member) << II; 16966 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16967 NewFD->setInvalidDecl(); 16968 } 16969 16970 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16971 if (Record->isUnion()) { 16972 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16973 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16974 if (RDecl->getDefinition()) { 16975 // C++ [class.union]p1: An object of a class with a non-trivial 16976 // constructor, a non-trivial copy constructor, a non-trivial 16977 // destructor, or a non-trivial copy assignment operator 16978 // cannot be a member of a union, nor can an array of such 16979 // objects. 16980 if (CheckNontrivialField(NewFD)) 16981 NewFD->setInvalidDecl(); 16982 } 16983 } 16984 16985 // C++ [class.union]p1: If a union contains a member of reference type, 16986 // the program is ill-formed, except when compiling with MSVC extensions 16987 // enabled. 16988 if (EltTy->isReferenceType()) { 16989 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16990 diag::ext_union_member_of_reference_type : 16991 diag::err_union_member_of_reference_type) 16992 << NewFD->getDeclName() << EltTy; 16993 if (!getLangOpts().MicrosoftExt) 16994 NewFD->setInvalidDecl(); 16995 } 16996 } 16997 } 16998 16999 // FIXME: We need to pass in the attributes given an AST 17000 // representation, not a parser representation. 17001 if (D) { 17002 // FIXME: The current scope is almost... but not entirely... correct here. 17003 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17004 17005 if (NewFD->hasAttrs()) 17006 CheckAlignasUnderalignment(NewFD); 17007 } 17008 17009 // In auto-retain/release, infer strong retension for fields of 17010 // retainable type. 17011 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17012 NewFD->setInvalidDecl(); 17013 17014 if (T.isObjCGCWeak()) 17015 Diag(Loc, diag::warn_attribute_weak_on_field); 17016 17017 // PPC MMA non-pointer types are not allowed as field types. 17018 if (Context.getTargetInfo().getTriple().isPPC64() && 17019 CheckPPCMMAType(T, NewFD->getLocation())) 17020 NewFD->setInvalidDecl(); 17021 17022 NewFD->setAccess(AS); 17023 return NewFD; 17024} 17025 17026bool Sema::CheckNontrivialField(FieldDecl *FD) { 17027 assert(FD)(static_cast <bool> (FD) ? void (0) : __assert_fail ("FD"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17027, __extension__ __PRETTY_FUNCTION__))
; 17028 assert(getLangOpts().CPlusPlus && "valid check only for C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"valid check only for C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17028, __extension__ __PRETTY_FUNCTION__))
; 17029 17030 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17031 return false; 17032 17033 QualType EltTy = Context.getBaseElementType(FD->getType()); 17034 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17035 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17036 if (RDecl->getDefinition()) { 17037 // We check for copy constructors before constructors 17038 // because otherwise we'll never get complaints about 17039 // copy constructors. 17040 17041 CXXSpecialMember member = CXXInvalid; 17042 // We're required to check for any non-trivial constructors. Since the 17043 // implicit default constructor is suppressed if there are any 17044 // user-declared constructors, we just need to check that there is a 17045 // trivial default constructor and a trivial copy constructor. (We don't 17046 // worry about move constructors here, since this is a C++98 check.) 17047 if (RDecl->hasNonTrivialCopyConstructor()) 17048 member = CXXCopyConstructor; 17049 else if (!RDecl->hasTrivialDefaultConstructor()) 17050 member = CXXDefaultConstructor; 17051 else if (RDecl->hasNonTrivialCopyAssignment()) 17052 member = CXXCopyAssignment; 17053 else if (RDecl->hasNonTrivialDestructor()) 17054 member = CXXDestructor; 17055 17056 if (member != CXXInvalid) { 17057 if (!getLangOpts().CPlusPlus11 && 17058 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17059 // Objective-C++ ARC: it is an error to have a non-trivial field of 17060 // a union. However, system headers in Objective-C programs 17061 // occasionally have Objective-C lifetime objects within unions, 17062 // and rather than cause the program to fail, we make those 17063 // members unavailable. 17064 SourceLocation Loc = FD->getLocation(); 17065 if (getSourceManager().isInSystemHeader(Loc)) { 17066 if (!FD->hasAttr<UnavailableAttr>()) 17067 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17068 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17069 return false; 17070 } 17071 } 17072 17073 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17074 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17075 diag::err_illegal_union_or_anon_struct_member) 17076 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17077 DiagnoseNontrivial(RDecl, member); 17078 return !getLangOpts().CPlusPlus11; 17079 } 17080 } 17081 } 17082 17083 return false; 17084} 17085 17086/// TranslateIvarVisibility - Translate visibility from a token ID to an 17087/// AST enum value. 17088static ObjCIvarDecl::AccessControl 17089TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17090 switch (ivarVisibility) { 17091 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17091)
; 17092 case tok::objc_private: return ObjCIvarDecl::Private; 17093 case tok::objc_public: return ObjCIvarDecl::Public; 17094 case tok::objc_protected: return ObjCIvarDecl::Protected; 17095 case tok::objc_package: return ObjCIvarDecl::Package; 17096 } 17097} 17098 17099/// ActOnIvar - Each ivar field of an objective-c class is passed into this 17100/// in order to create an IvarDecl object for it. 17101Decl *Sema::ActOnIvar(Scope *S, 17102 SourceLocation DeclStart, 17103 Declarator &D, Expr *BitfieldWidth, 17104 tok::ObjCKeywordKind Visibility) { 17105 17106 IdentifierInfo *II = D.getIdentifier(); 17107 Expr *BitWidth = (Expr*)BitfieldWidth; 17108 SourceLocation Loc = DeclStart; 17109 if (II) Loc = D.getIdentifierLoc(); 17110 17111 // FIXME: Unnamed fields can be handled in various different ways, for 17112 // example, unnamed unions inject all members into the struct namespace! 17113 17114 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17115 QualType T = TInfo->getType(); 17116 17117 if (BitWidth) { 17118 // 6.7.2.1p3, 6.7.2.1p4 17119 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17120 if (!BitWidth) 17121 D.setInvalidType(); 17122 } else { 17123 // Not a bitfield. 17124 17125 // validate II. 17126 17127 } 17128 if (T->isReferenceType()) { 17129 Diag(Loc, diag::err_ivar_reference_type); 17130 D.setInvalidType(); 17131 } 17132 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17133 // than a variably modified type. 17134 else if (T->isVariablyModifiedType()) { 17135 if (!tryToFixVariablyModifiedVarType( 17136 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17137 D.setInvalidType(); 17138 } 17139 17140 // Get the visibility (access control) for this ivar. 17141 ObjCIvarDecl::AccessControl ac = 17142 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17143 : ObjCIvarDecl::None; 17144 // Must set ivar's DeclContext to its enclosing interface. 17145 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17146 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17147 return nullptr; 17148 ObjCContainerDecl *EnclosingContext; 17149 if (ObjCImplementationDecl *IMPDecl = 17150 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17151 if (LangOpts.ObjCRuntime.isFragile()) { 17152 // Case of ivar declared in an implementation. Context is that of its class. 17153 EnclosingContext = IMPDecl->getClassInterface(); 17154 assert(EnclosingContext && "Implementation has no class interface!")(static_cast <bool> (EnclosingContext && "Implementation has no class interface!"
) ? void (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17154, __extension__ __PRETTY_FUNCTION__))
; 17155 } 17156 else 17157 EnclosingContext = EnclosingDecl; 17158 } else { 17159 if (ObjCCategoryDecl *CDecl = 17160 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17161 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17162 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17163 return nullptr; 17164 } 17165 } 17166 EnclosingContext = EnclosingDecl; 17167 } 17168 17169 // Construct the decl. 17170 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17171 DeclStart, Loc, II, T, 17172 TInfo, ac, (Expr *)BitfieldWidth); 17173 17174 if (II) { 17175 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17176 ForVisibleRedeclaration); 17177 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17178 && !isa<TagDecl>(PrevDecl)) { 17179 Diag(Loc, diag::err_duplicate_member) << II; 17180 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17181 NewID->setInvalidDecl(); 17182 } 17183 } 17184 17185 // Process attributes attached to the ivar. 17186 ProcessDeclAttributes(S, NewID, D); 17187 17188 if (D.isInvalidType()) 17189 NewID->setInvalidDecl(); 17190 17191 // In ARC, infer 'retaining' for ivars of retainable type. 17192 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17193 NewID->setInvalidDecl(); 17194 17195 if (D.getDeclSpec().isModulePrivateSpecified()) 17196 NewID->setModulePrivate(); 17197 17198 if (II) { 17199 // FIXME: When interfaces are DeclContexts, we'll need to add 17200 // these to the interface. 17201 S->AddDecl(NewID); 17202 IdResolver.AddDecl(NewID); 17203 } 17204 17205 if (LangOpts.ObjCRuntime.isNonFragile() && 17206 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17207 Diag(Loc, diag::warn_ivars_in_interface); 17208 17209 return NewID; 17210} 17211 17212/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17213/// class and class extensions. For every class \@interface and class 17214/// extension \@interface, if the last ivar is a bitfield of any type, 17215/// then add an implicit `char :0` ivar to the end of that interface. 17216void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17217 SmallVectorImpl<Decl *> &AllIvarDecls) { 17218 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17219 return; 17220 17221 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17222 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17223 17224 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17225 return; 17226 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17227 if (!ID) { 17228 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17229 if (!CD->IsClassExtension()) 17230 return; 17231 } 17232 // No need to add this to end of @implementation. 17233 else 17234 return; 17235 } 17236 // All conditions are met. Add a new bitfield to the tail end of ivars. 17237 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17238 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17239 17240 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17241 DeclLoc, DeclLoc, nullptr, 17242 Context.CharTy, 17243 Context.getTrivialTypeSourceInfo(Context.CharTy, 17244 DeclLoc), 17245 ObjCIvarDecl::Private, BW, 17246 true); 17247 AllIvarDecls.push_back(Ivar); 17248} 17249 17250void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17251 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17252 SourceLocation RBrac, 17253 const ParsedAttributesView &Attrs) { 17254 assert(EnclosingDecl && "missing record or interface decl")(static_cast <bool> (EnclosingDecl && "missing record or interface decl"
) ? void (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17254, __extension__ __PRETTY_FUNCTION__))
; 17255 17256 // If this is an Objective-C @implementation or category and we have 17257 // new fields here we should reset the layout of the interface since 17258 // it will now change. 17259 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17260 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17261 switch (DC->getKind()) { 17262 default: break; 17263 case Decl::ObjCCategory: 17264 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17265 break; 17266 case Decl::ObjCImplementation: 17267 Context. 17268 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17269 break; 17270 } 17271 } 17272 17273 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17274 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17275 17276 // Start counting up the number of named members; make sure to include 17277 // members of anonymous structs and unions in the total. 17278 unsigned NumNamedMembers = 0; 17279 if (Record) { 17280 for (const auto *I : Record->decls()) { 17281 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17282 if (IFD->getDeclName()) 17283 ++NumNamedMembers; 17284 } 17285 } 17286 17287 // Verify that all the fields are okay. 17288 SmallVector<FieldDecl*, 32> RecFields; 17289 17290 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17291 i != end; ++i) { 17292 FieldDecl *FD = cast<FieldDecl>(*i); 17293 17294 // Get the type for the field. 17295 const Type *FDTy = FD->getType().getTypePtr(); 17296 17297 if (!FD->isAnonymousStructOrUnion()) { 17298 // Remember all fields written by the user. 17299 RecFields.push_back(FD); 17300 } 17301 17302 // If the field is already invalid for some reason, don't emit more 17303 // diagnostics about it. 17304 if (FD->isInvalidDecl()) { 17305 EnclosingDecl->setInvalidDecl(); 17306 continue; 17307 } 17308 17309 // C99 6.7.2.1p2: 17310 // A structure or union shall not contain a member with 17311 // incomplete or function type (hence, a structure shall not 17312 // contain an instance of itself, but may contain a pointer to 17313 // an instance of itself), except that the last member of a 17314 // structure with more than one named member may have incomplete 17315 // array type; such a structure (and any union containing, 17316 // possibly recursively, a member that is such a structure) 17317 // shall not be a member of a structure or an element of an 17318 // array. 17319 bool IsLastField = (i + 1 == Fields.end()); 17320 if (FDTy->isFunctionType()) { 17321 // Field declared as a function. 17322 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17323 << FD->getDeclName(); 17324 FD->setInvalidDecl(); 17325 EnclosingDecl->setInvalidDecl(); 17326 continue; 17327 } else if (FDTy->isIncompleteArrayType() && 17328 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17329 if (Record) { 17330 // Flexible array member. 17331 // Microsoft and g++ is more permissive regarding flexible array. 17332 // It will accept flexible array in union and also 17333 // as the sole element of a struct/class. 17334 unsigned DiagID = 0; 17335 if (!Record->isUnion() && !IsLastField) { 17336 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17337 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17338 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17339 FD->setInvalidDecl(); 17340 EnclosingDecl->setInvalidDecl(); 17341 continue; 17342 } else if (Record->isUnion()) 17343 DiagID = getLangOpts().MicrosoftExt 17344 ? diag::ext_flexible_array_union_ms 17345 : getLangOpts().CPlusPlus 17346 ? diag::ext_flexible_array_union_gnu 17347 : diag::err_flexible_array_union; 17348 else if (NumNamedMembers < 1) 17349 DiagID = getLangOpts().MicrosoftExt 17350 ? diag::ext_flexible_array_empty_aggregate_ms 17351 : getLangOpts().CPlusPlus 17352 ? diag::ext_flexible_array_empty_aggregate_gnu 17353 : diag::err_flexible_array_empty_aggregate; 17354 17355 if (DiagID) 17356 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17357 << Record->getTagKind(); 17358 // While the layout of types that contain virtual bases is not specified 17359 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17360 // virtual bases after the derived members. This would make a flexible 17361 // array member declared at the end of an object not adjacent to the end 17362 // of the type. 17363 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17364 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17365 << FD->getDeclName() << Record->getTagKind(); 17366 if (!getLangOpts().C99) 17367 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17368 << FD->getDeclName() << Record->getTagKind(); 17369 17370 // If the element type has a non-trivial destructor, we would not 17371 // implicitly destroy the elements, so disallow it for now. 17372 // 17373 // FIXME: GCC allows this. We should probably either implicitly delete 17374 // the destructor of the containing class, or just allow this. 17375 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17376 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17377 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17378 << FD->getDeclName() << FD->getType(); 17379 FD->setInvalidDecl(); 17380 EnclosingDecl->setInvalidDecl(); 17381 continue; 17382 } 17383 // Okay, we have a legal flexible array member at the end of the struct. 17384 Record->setHasFlexibleArrayMember(true); 17385 } else { 17386 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17387 // unless they are followed by another ivar. That check is done 17388 // elsewhere, after synthesized ivars are known. 17389 } 17390 } else if (!FDTy->isDependentType() && 17391 RequireCompleteSizedType( 17392 FD->getLocation(), FD->getType(), 17393 diag::err_field_incomplete_or_sizeless)) { 17394 // Incomplete type 17395 FD->setInvalidDecl(); 17396 EnclosingDecl->setInvalidDecl(); 17397 continue; 17398 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17399 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17400 // A type which contains a flexible array member is considered to be a 17401 // flexible array member. 17402 Record->setHasFlexibleArrayMember(true); 17403 if (!Record->isUnion()) { 17404 // If this is a struct/class and this is not the last element, reject 17405 // it. Note that GCC supports variable sized arrays in the middle of 17406 // structures. 17407 if (!IsLastField) 17408 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17409 << FD->getDeclName() << FD->getType(); 17410 else { 17411 // We support flexible arrays at the end of structs in 17412 // other structs as an extension. 17413 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17414 << FD->getDeclName(); 17415 } 17416 } 17417 } 17418 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17419 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17420 diag::err_abstract_type_in_decl, 17421 AbstractIvarType)) { 17422 // Ivars can not have abstract class types 17423 FD->setInvalidDecl(); 17424 } 17425 if (Record && FDTTy->getDecl()->hasObjectMember()) 17426 Record->setHasObjectMember(true); 17427 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17428 Record->setHasVolatileMember(true); 17429 } else if (FDTy->isObjCObjectType()) { 17430 /// A field cannot be an Objective-c object 17431 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17432 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17433 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17434 FD->setType(T); 17435 } else if (Record && Record->isUnion() && 17436 FD->getType().hasNonTrivialObjCLifetime() && 17437 getSourceManager().isInSystemHeader(FD->getLocation()) && 17438 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17439 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17440 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17441 // For backward compatibility, fields of C unions declared in system 17442 // headers that have non-trivial ObjC ownership qualifications are marked 17443 // as unavailable unless the qualifier is explicit and __strong. This can 17444 // break ABI compatibility between programs compiled with ARC and MRR, but 17445 // is a better option than rejecting programs using those unions under 17446 // ARC. 17447 FD->addAttr(UnavailableAttr::CreateImplicit( 17448 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17449 FD->getLocation())); 17450 } else if (getLangOpts().ObjC && 17451 getLangOpts().getGC() != LangOptions::NonGC && Record && 17452 !Record->hasObjectMember()) { 17453 if (FD->getType()->isObjCObjectPointerType() || 17454 FD->getType().isObjCGCStrong()) 17455 Record->setHasObjectMember(true); 17456 else if (Context.getAsArrayType(FD->getType())) { 17457 QualType BaseType = Context.getBaseElementType(FD->getType()); 17458 if (BaseType->isRecordType() && 17459 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17460 Record->setHasObjectMember(true); 17461 else if (BaseType->isObjCObjectPointerType() || 17462 BaseType.isObjCGCStrong()) 17463 Record->setHasObjectMember(true); 17464 } 17465 } 17466 17467 if (Record && !getLangOpts().CPlusPlus && 17468 !shouldIgnoreForRecordTriviality(FD)) { 17469 QualType FT = FD->getType(); 17470 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17471 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17472 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17473 Record->isUnion()) 17474 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17475 } 17476 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17477 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17478 Record->setNonTrivialToPrimitiveCopy(true); 17479 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17480 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17481 } 17482 if (FT.isDestructedType()) { 17483 Record->setNonTrivialToPrimitiveDestroy(true); 17484 Record->setParamDestroyedInCallee(true); 17485 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17486 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17487 } 17488 17489 if (const auto *RT = FT->getAs<RecordType>()) { 17490 if (RT->getDecl()->getArgPassingRestrictions() == 17491 RecordDecl::APK_CanNeverPassInRegs) 17492 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17493 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17494 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17495 } 17496 17497 if (Record && FD->getType().isVolatileQualified()) 17498 Record->setHasVolatileMember(true); 17499 // Keep track of the number of named members. 17500 if (FD->getIdentifier()) 17501 ++NumNamedMembers; 17502 } 17503 17504 // Okay, we successfully defined 'Record'. 17505 if (Record) { 17506 bool Completed = false; 17507 if (CXXRecord) { 17508 if (!CXXRecord->isInvalidDecl()) { 17509 // Set access bits correctly on the directly-declared conversions. 17510 for (CXXRecordDecl::conversion_iterator 17511 I = CXXRecord->conversion_begin(), 17512 E = CXXRecord->conversion_end(); I != E; ++I) 17513 I.setAccess((*I)->getAccess()); 17514 } 17515 17516 // Add any implicitly-declared members to this class. 17517 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17518 17519 if (!CXXRecord->isDependentType()) { 17520 if (!CXXRecord->isInvalidDecl()) { 17521 // If we have virtual base classes, we may end up finding multiple 17522 // final overriders for a given virtual function. Check for this 17523 // problem now. 17524 if (CXXRecord->getNumVBases()) { 17525 CXXFinalOverriderMap FinalOverriders; 17526 CXXRecord->getFinalOverriders(FinalOverriders); 17527 17528 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17529 MEnd = FinalOverriders.end(); 17530 M != MEnd; ++M) { 17531 for (OverridingMethods::iterator SO = M->second.begin(), 17532 SOEnd = M->second.end(); 17533 SO != SOEnd; ++SO) { 17534 assert(SO->second.size() > 0 &&(static_cast <bool> (SO->second.size() > 0 &&
"Virtual function without overriding functions?") ? void (0)
: __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17535, __extension__ __PRETTY_FUNCTION__))
17535 "Virtual function without overriding functions?")(static_cast <bool> (SO->second.size() > 0 &&
"Virtual function without overriding functions?") ? void (0)
: __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17535, __extension__ __PRETTY_FUNCTION__))
; 17536 if (SO->second.size() == 1) 17537 continue; 17538 17539 // C++ [class.virtual]p2: 17540 // In a derived class, if a virtual member function of a base 17541 // class subobject has more than one final overrider the 17542 // program is ill-formed. 17543 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17544 << (const NamedDecl *)M->first << Record; 17545 Diag(M->first->getLocation(), 17546 diag::note_overridden_virtual_function); 17547 for (OverridingMethods::overriding_iterator 17548 OM = SO->second.begin(), 17549 OMEnd = SO->second.end(); 17550 OM != OMEnd; ++OM) 17551 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17552 << (const NamedDecl *)M->first << OM->Method->getParent(); 17553 17554 Record->setInvalidDecl(); 17555 } 17556 } 17557 CXXRecord->completeDefinition(&FinalOverriders); 17558 Completed = true; 17559 } 17560 } 17561 } 17562 } 17563 17564 if (!Completed) 17565 Record->completeDefinition(); 17566 17567 // Handle attributes before checking the layout. 17568 ProcessDeclAttributeList(S, Record, Attrs); 17569 17570 // We may have deferred checking for a deleted destructor. Check now. 17571 if (CXXRecord) { 17572 auto *Dtor = CXXRecord->getDestructor(); 17573 if (Dtor && Dtor->isImplicit() && 17574 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17575 CXXRecord->setImplicitDestructorIsDeleted(); 17576 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17577 } 17578 } 17579 17580 if (Record->hasAttrs()) { 17581 CheckAlignasUnderalignment(Record); 17582 17583 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17584 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17585 IA->getRange(), IA->getBestCase(), 17586 IA->getInheritanceModel()); 17587 } 17588 17589 // Check if the structure/union declaration is a type that can have zero 17590 // size in C. For C this is a language extension, for C++ it may cause 17591 // compatibility problems. 17592 bool CheckForZeroSize; 17593 if (!getLangOpts().CPlusPlus) { 17594 CheckForZeroSize = true; 17595 } else { 17596 // For C++ filter out types that cannot be referenced in C code. 17597 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17598 CheckForZeroSize = 17599 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17600 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17601 CXXRecord->isCLike(); 17602 } 17603 if (CheckForZeroSize) { 17604 bool ZeroSize = true; 17605 bool IsEmpty = true; 17606 unsigned NonBitFields = 0; 17607 for (RecordDecl::field_iterator I = Record->field_begin(), 17608 E = Record->field_end(); 17609 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17610 IsEmpty = false; 17611 if (I->isUnnamedBitfield()) { 17612 if (!I->isZeroLengthBitField(Context)) 17613 ZeroSize = false; 17614 } else { 17615 ++NonBitFields; 17616 QualType FieldType = I->getType(); 17617 if (FieldType->isIncompleteType() || 17618 !Context.getTypeSizeInChars(FieldType).isZero()) 17619 ZeroSize = false; 17620 } 17621 } 17622 17623 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17624 // allowed in C++, but warn if its declaration is inside 17625 // extern "C" block. 17626 if (ZeroSize) { 17627 Diag(RecLoc, getLangOpts().CPlusPlus ? 17628 diag::warn_zero_size_struct_union_in_extern_c : 17629 diag::warn_zero_size_struct_union_compat) 17630 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17631 } 17632 17633 // Structs without named members are extension in C (C99 6.7.2.1p7), 17634 // but are accepted by GCC. 17635 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17636 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17637 diag::ext_no_named_members_in_struct_union) 17638 << Record->isUnion(); 17639 } 17640 } 17641 } else { 17642 ObjCIvarDecl **ClsFields = 17643 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17644 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17645 ID->setEndOfDefinitionLoc(RBrac); 17646 // Add ivar's to class's DeclContext. 17647 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17648 ClsFields[i]->setLexicalDeclContext(ID); 17649 ID->addDecl(ClsFields[i]); 17650 } 17651 // Must enforce the rule that ivars in the base classes may not be 17652 // duplicates. 17653 if (ID->getSuperClass()) 17654 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17655 } else if (ObjCImplementationDecl *IMPDecl = 17656 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17657 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")(static_cast <bool> (IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? void (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17657, __extension__ __PRETTY_FUNCTION__))
; 17658 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17659 // Ivar declared in @implementation never belongs to the implementation. 17660 // Only it is in implementation's lexical context. 17661 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17662 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17663 IMPDecl->setIvarLBraceLoc(LBrac); 17664 IMPDecl->setIvarRBraceLoc(RBrac); 17665 } else if (ObjCCategoryDecl *CDecl = 17666 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17667 // case of ivars in class extension; all other cases have been 17668 // reported as errors elsewhere. 17669 // FIXME. Class extension does not have a LocEnd field. 17670 // CDecl->setLocEnd(RBrac); 17671 // Add ivar's to class extension's DeclContext. 17672 // Diagnose redeclaration of private ivars. 17673 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17674 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17675 if (IDecl) { 17676 if (const ObjCIvarDecl *ClsIvar = 17677 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17678 Diag(ClsFields[i]->getLocation(), 17679 diag::err_duplicate_ivar_declaration); 17680 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17681 continue; 17682 } 17683 for (const auto *Ext : IDecl->known_extensions()) { 17684 if (const ObjCIvarDecl *ClsExtIvar 17685 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17686 Diag(ClsFields[i]->getLocation(), 17687 diag::err_duplicate_ivar_declaration); 17688 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17689 continue; 17690 } 17691 } 17692 } 17693 ClsFields[i]->setLexicalDeclContext(CDecl); 17694 CDecl->addDecl(ClsFields[i]); 17695 } 17696 CDecl->setIvarLBraceLoc(LBrac); 17697 CDecl->setIvarRBraceLoc(RBrac); 17698 } 17699 } 17700} 17701 17702/// Determine whether the given integral value is representable within 17703/// the given type T. 17704static bool isRepresentableIntegerValue(ASTContext &Context, 17705 llvm::APSInt &Value, 17706 QualType T) { 17707 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17708, __extension__ __PRETTY_FUNCTION__))
17708 "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17708, __extension__ __PRETTY_FUNCTION__))
; 17709 unsigned BitWidth = Context.getIntWidth(T); 17710 17711 if (Value.isUnsigned() || Value.isNonNegative()) { 17712 if (T->isSignedIntegerOrEnumerationType()) 17713 --BitWidth; 17714 return Value.getActiveBits() <= BitWidth; 17715 } 17716 return Value.getMinSignedBits() <= BitWidth; 17717} 17718 17719// Given an integral type, return the next larger integral type 17720// (or a NULL type of no such type exists). 17721static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17722 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17723 // enum checking below. 17724 assert((T->isIntegralType(Context) ||(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17725, __extension__ __PRETTY_FUNCTION__))
17725 T->isEnumeralType()) && "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17725, __extension__ __PRETTY_FUNCTION__))
; 17726 const unsigned NumTypes = 4; 17727 QualType SignedIntegralTypes[NumTypes] = { 17728 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17729 }; 17730 QualType UnsignedIntegralTypes[NumTypes] = { 17731 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17732 Context.UnsignedLongLongTy 17733 }; 17734 17735 unsigned BitWidth = Context.getTypeSize(T); 17736 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17737 : UnsignedIntegralTypes; 17738 for (unsigned I = 0; I != NumTypes; ++I) 17739 if (Context.getTypeSize(Types[I]) > BitWidth) 17740 return Types[I]; 17741 17742 return QualType(); 17743} 17744 17745EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17746 EnumConstantDecl *LastEnumConst, 17747 SourceLocation IdLoc, 17748 IdentifierInfo *Id, 17749 Expr *Val) { 17750 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17751 llvm::APSInt EnumVal(IntWidth); 17752 QualType EltTy; 17753 17754 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17755 Val = nullptr; 17756 17757 if (Val) 17758 Val = DefaultLvalueConversion(Val).get(); 17759 17760 if (Val) { 17761 if (Enum->isDependentType() || Val->isTypeDependent()) 17762 EltTy = Context.DependentTy; 17763 else { 17764 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17765 // underlying type, but do allow it in all other contexts. 17766 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17767 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17768 // constant-expression in the enumerator-definition shall be a converted 17769 // constant expression of the underlying type. 17770 EltTy = Enum->getIntegerType(); 17771 ExprResult Converted = 17772 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17773 CCEK_Enumerator); 17774 if (Converted.isInvalid()) 17775 Val = nullptr; 17776 else 17777 Val = Converted.get(); 17778 } else if (!Val->isValueDependent() && 17779 !(Val = 17780 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 17781 .get())) { 17782 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17783 } else { 17784 if (Enum->isComplete()) { 17785 EltTy = Enum->getIntegerType(); 17786 17787 // In Obj-C and Microsoft mode, require the enumeration value to be 17788 // representable in the underlying type of the enumeration. In C++11, 17789 // we perform a non-narrowing conversion as part of converted constant 17790 // expression checking. 17791 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17792 if (Context.getTargetInfo() 17793 .getTriple() 17794 .isWindowsMSVCEnvironment()) { 17795 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17796 } else { 17797 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17798 } 17799 } 17800 17801 // Cast to the underlying type. 17802 Val = ImpCastExprToType(Val, EltTy, 17803 EltTy->isBooleanType() ? CK_IntegralToBoolean 17804 : CK_IntegralCast) 17805 .get(); 17806 } else if (getLangOpts().CPlusPlus) { 17807 // C++11 [dcl.enum]p5: 17808 // If the underlying type is not fixed, the type of each enumerator 17809 // is the type of its initializing value: 17810 // - If an initializer is specified for an enumerator, the 17811 // initializing value has the same type as the expression. 17812 EltTy = Val->getType(); 17813 } else { 17814 // C99 6.7.2.2p2: 17815 // The expression that defines the value of an enumeration constant 17816 // shall be an integer constant expression that has a value 17817 // representable as an int. 17818 17819 // Complain if the value is not representable in an int. 17820 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17821 Diag(IdLoc, diag::ext_enum_value_not_int) 17822 << toString(EnumVal, 10) << Val->getSourceRange() 17823 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17824 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17825 // Force the type of the expression to 'int'. 17826 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17827 } 17828 EltTy = Val->getType(); 17829 } 17830 } 17831 } 17832 } 17833 17834 if (!Val) { 17835 if (Enum->isDependentType()) 17836 EltTy = Context.DependentTy; 17837 else if (!LastEnumConst) { 17838 // C++0x [dcl.enum]p5: 17839 // If the underlying type is not fixed, the type of each enumerator 17840 // is the type of its initializing value: 17841 // - If no initializer is specified for the first enumerator, the 17842 // initializing value has an unspecified integral type. 17843 // 17844 // GCC uses 'int' for its unspecified integral type, as does 17845 // C99 6.7.2.2p3. 17846 if (Enum->isFixed()) { 17847 EltTy = Enum->getIntegerType(); 17848 } 17849 else { 17850 EltTy = Context.IntTy; 17851 } 17852 } else { 17853 // Assign the last value + 1. 17854 EnumVal = LastEnumConst->getInitVal(); 17855 ++EnumVal; 17856 EltTy = LastEnumConst->getType(); 17857 17858 // Check for overflow on increment. 17859 if (EnumVal < LastEnumConst->getInitVal()) { 17860 // C++0x [dcl.enum]p5: 17861 // If the underlying type is not fixed, the type of each enumerator 17862 // is the type of its initializing value: 17863 // 17864 // - Otherwise the type of the initializing value is the same as 17865 // the type of the initializing value of the preceding enumerator 17866 // unless the incremented value is not representable in that type, 17867 // in which case the type is an unspecified integral type 17868 // sufficient to contain the incremented value. If no such type 17869 // exists, the program is ill-formed. 17870 QualType T = getNextLargerIntegralType(Context, EltTy); 17871 if (T.isNull() || Enum->isFixed()) { 17872 // There is no integral type larger enough to represent this 17873 // value. Complain, then allow the value to wrap around. 17874 EnumVal = LastEnumConst->getInitVal(); 17875 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17876 ++EnumVal; 17877 if (Enum->isFixed()) 17878 // When the underlying type is fixed, this is ill-formed. 17879 Diag(IdLoc, diag::err_enumerator_wrapped) 17880 << toString(EnumVal, 10) 17881 << EltTy; 17882 else 17883 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17884 << toString(EnumVal, 10); 17885 } else { 17886 EltTy = T; 17887 } 17888 17889 // Retrieve the last enumerator's value, extent that type to the 17890 // type that is supposed to be large enough to represent the incremented 17891 // value, then increment. 17892 EnumVal = LastEnumConst->getInitVal(); 17893 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17894 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17895 ++EnumVal; 17896 17897 // If we're not in C++, diagnose the overflow of enumerator values, 17898 // which in C99 means that the enumerator value is not representable in 17899 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17900 // permits enumerator values that are representable in some larger 17901 // integral type. 17902 if (!getLangOpts().CPlusPlus && !T.isNull()) 17903 Diag(IdLoc, diag::warn_enum_value_overflow); 17904 } else if (!getLangOpts().CPlusPlus && 17905 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17906 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17907 Diag(IdLoc, diag::ext_enum_value_not_int) 17908 << toString(EnumVal, 10) << 1; 17909 } 17910 } 17911 } 17912 17913 if (!EltTy->isDependentType()) { 17914 // Make the enumerator value match the signedness and size of the 17915 // enumerator's type. 17916 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17917 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17918 } 17919 17920 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17921 Val, EnumVal); 17922} 17923 17924Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17925 SourceLocation IILoc) { 17926 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17927 !getLangOpts().CPlusPlus) 17928 return SkipBodyInfo(); 17929 17930 // We have an anonymous enum definition. Look up the first enumerator to 17931 // determine if we should merge the definition with an existing one and 17932 // skip the body. 17933 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17934 forRedeclarationInCurContext()); 17935 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17936 if (!PrevECD) 17937 return SkipBodyInfo(); 17938 17939 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17940 NamedDecl *Hidden; 17941 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17942 SkipBodyInfo Skip; 17943 Skip.Previous = Hidden; 17944 return Skip; 17945 } 17946 17947 return SkipBodyInfo(); 17948} 17949 17950Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17951 SourceLocation IdLoc, IdentifierInfo *Id, 17952 const ParsedAttributesView &Attrs, 17953 SourceLocation EqualLoc, Expr *Val) { 17954 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17955 EnumConstantDecl *LastEnumConst = 17956 cast_or_null<EnumConstantDecl>(lastEnumConst); 17957 17958 // The scope passed in may not be a decl scope. Zip up the scope tree until 17959 // we find one that is. 17960 S = getNonFieldDeclScope(S); 17961 17962 // Verify that there isn't already something declared with this name in this 17963 // scope. 17964 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17965 LookupName(R, S); 17966 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17967 17968 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17969 // Maybe we will complain about the shadowed template parameter. 17970 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17971 // Just pretend that we didn't see the previous declaration. 17972 PrevDecl = nullptr; 17973 } 17974 17975 // C++ [class.mem]p15: 17976 // If T is the name of a class, then each of the following shall have a name 17977 // different from T: 17978 // - every enumerator of every member of class T that is an unscoped 17979 // enumerated type 17980 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17981 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17982 DeclarationNameInfo(Id, IdLoc)); 17983 17984 EnumConstantDecl *New = 17985 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17986 if (!New) 17987 return nullptr; 17988 17989 if (PrevDecl) { 17990 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17991 // Check for other kinds of shadowing not already handled. 17992 CheckShadow(New, PrevDecl, R); 17993 } 17994 17995 // When in C++, we may get a TagDecl with the same name; in this case the 17996 // enum constant will 'hide' the tag. 17997 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(static_cast <bool> ((getLangOpts().CPlusPlus || !isa<
TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!"
) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17998, __extension__ __PRETTY_FUNCTION__))
17998 "Received TagDecl when not in C++!")(static_cast <bool> ((getLangOpts().CPlusPlus || !isa<
TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!"
) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 17998, __extension__ __PRETTY_FUNCTION__))
; 17999 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18000 if (isa<EnumConstantDecl>(PrevDecl)) 18001 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18002 else 18003 Diag(IdLoc, diag::err_redefinition) << Id; 18004 notePreviousDefinition(PrevDecl, IdLoc); 18005 return nullptr; 18006 } 18007 } 18008 18009 // Process attributes. 18010 ProcessDeclAttributeList(S, New, Attrs); 18011 AddPragmaAttributes(S, New); 18012 18013 // Register this decl in the current scope stack. 18014 New->setAccess(TheEnumDecl->getAccess()); 18015 PushOnScopeChains(New, S); 18016 18017 ActOnDocumentableDecl(New); 18018 18019 return New; 18020} 18021 18022// Returns true when the enum initial expression does not trigger the 18023// duplicate enum warning. A few common cases are exempted as follows: 18024// Element2 = Element1 18025// Element2 = Element1 + 1 18026// Element2 = Element1 - 1 18027// Where Element2 and Element1 are from the same enum. 18028static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18029 Expr *InitExpr = ECD->getInitExpr(); 18030 if (!InitExpr) 18031 return true; 18032 InitExpr = InitExpr->IgnoreImpCasts(); 18033 18034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18035 if (!BO->isAdditiveOp()) 18036 return true; 18037 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18038 if (!IL) 18039 return true; 18040 if (IL->getValue() != 1) 18041 return true; 18042 18043 InitExpr = BO->getLHS(); 18044 } 18045 18046 // This checks if the elements are from the same enum. 18047 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18048 if (!DRE) 18049 return true; 18050 18051 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18052 if (!EnumConstant) 18053 return true; 18054 18055 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18056 Enum) 18057 return true; 18058 18059 return false; 18060} 18061 18062// Emits a warning when an element is implicitly set a value that 18063// a previous element has already been set to. 18064static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18065 EnumDecl *Enum, QualType EnumType) { 18066 // Avoid anonymous enums 18067 if (!Enum->getIdentifier()) 18068 return; 18069 18070 // Only check for small enums. 18071 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18072 return; 18073 18074 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18075 return; 18076 18077 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18078 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18079 18080 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18081 18082 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18083 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18084 18085 // Use int64_t as a key to avoid needing special handling for map keys. 18086 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18087 llvm::APSInt Val = D->getInitVal(); 18088 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18089 }; 18090 18091 DuplicatesVector DupVector; 18092 ValueToVectorMap EnumMap; 18093 18094 // Populate the EnumMap with all values represented by enum constants without 18095 // an initializer. 18096 for (auto *Element : Elements) { 18097 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18098 18099 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18100 // this constant. Skip this enum since it may be ill-formed. 18101 if (!ECD) { 18102 return; 18103 } 18104 18105 // Constants with initalizers are handled in the next loop. 18106 if (ECD->getInitExpr()) 18107 continue; 18108 18109 // Duplicate values are handled in the next loop. 18110 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18111 } 18112 18113 if (EnumMap.size() == 0) 18114 return; 18115 18116 // Create vectors for any values that has duplicates. 18117 for (auto *Element : Elements) { 18118 // The last loop returned if any constant was null. 18119 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18120 if (!ValidDuplicateEnum(ECD, Enum)) 18121 continue; 18122 18123 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18124 if (Iter == EnumMap.end()) 18125 continue; 18126 18127 DeclOrVector& Entry = Iter->second; 18128 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18129 // Ensure constants are different. 18130 if (D == ECD) 18131 continue; 18132 18133 // Create new vector and push values onto it. 18134 auto Vec = std::make_unique<ECDVector>(); 18135 Vec->push_back(D); 18136 Vec->push_back(ECD); 18137 18138 // Update entry to point to the duplicates vector. 18139 Entry = Vec.get(); 18140 18141 // Store the vector somewhere we can consult later for quick emission of 18142 // diagnostics. 18143 DupVector.emplace_back(std::move(Vec)); 18144 continue; 18145 } 18146 18147 ECDVector *Vec = Entry.get<ECDVector*>(); 18148 // Make sure constants are not added more than once. 18149 if (*Vec->begin() == ECD) 18150 continue; 18151 18152 Vec->push_back(ECD); 18153 } 18154 18155 // Emit diagnostics. 18156 for (const auto &Vec : DupVector) { 18157 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")(static_cast <bool> (Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? void (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 18157, __extension__ __PRETTY_FUNCTION__))
; 18158 18159 // Emit warning for one enum constant. 18160 auto *FirstECD = Vec->front(); 18161 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18162 << FirstECD << toString(FirstECD->getInitVal(), 10) 18163 << FirstECD->getSourceRange(); 18164 18165 // Emit one note for each of the remaining enum constants with 18166 // the same value. 18167 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 18168 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18169 << ECD << toString(ECD->getInitVal(), 10) 18170 << ECD->getSourceRange(); 18171 } 18172} 18173 18174bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18175 bool AllowMask) const { 18176 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")(static_cast <bool> (ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? void (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 18176, __extension__ __PRETTY_FUNCTION__))
; 18177 assert(ED->isCompleteDefinition() && "expected enum definition")(static_cast <bool> (ED->isCompleteDefinition() &&
"expected enum definition") ? void (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 18177, __extension__ __PRETTY_FUNCTION__))
; 18178 18179 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18180 llvm::APInt &FlagBits = R.first->second; 18181 18182 if (R.second) { 18183 for (auto *E : ED->enumerators()) { 18184 const auto &EVal = E->getInitVal(); 18185 // Only single-bit enumerators introduce new flag values. 18186 if (EVal.isPowerOf2()) 18187 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18188 } 18189 } 18190 18191 // A value is in a flag enum if either its bits are a subset of the enum's 18192 // flag bits (the first condition) or we are allowing masks and the same is 18193 // true of its complement (the second condition). When masks are allowed, we 18194 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18195 // 18196 // While it's true that any value could be used as a mask, the assumption is 18197 // that a mask will have all of the insignificant bits set. Anything else is 18198 // likely a logic error. 18199 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18200 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18201} 18202 18203void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18204 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18205 const ParsedAttributesView &Attrs) { 18206 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18207 QualType EnumType = Context.getTypeDeclType(Enum); 18208 18209 ProcessDeclAttributeList(S, Enum, Attrs); 18210 18211 if (Enum->isDependentType()) { 18212 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18213 EnumConstantDecl *ECD = 18214 cast_or_null<EnumConstantDecl>(Elements[i]); 18215 if (!ECD) continue; 18216 18217 ECD->setType(EnumType); 18218 } 18219 18220 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18221 return; 18222 } 18223 18224 // TODO: If the result value doesn't fit in an int, it must be a long or long 18225 // long value. ISO C does not support this, but GCC does as an extension, 18226 // emit a warning. 18227 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18228 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18229 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18230 18231 // Verify that all the values are okay, compute the size of the values, and 18232 // reverse the list. 18233 unsigned NumNegativeBits = 0; 18234 unsigned NumPositiveBits = 0; 18235 18236 // Keep track of whether all elements have type int. 18237 bool AllElementsInt = true; 18238 18239 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18240 EnumConstantDecl *ECD = 18241 cast_or_null<EnumConstantDecl>(Elements[i]); 18242 if (!ECD) continue; // Already issued a diagnostic. 18243 18244 const llvm::APSInt &InitVal = ECD->getInitVal(); 18245 18246 // Keep track of the size of positive and negative values. 18247 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18248 NumPositiveBits = std::max(NumPositiveBits, 18249 (unsigned)InitVal.getActiveBits()); 18250 else 18251 NumNegativeBits = std::max(NumNegativeBits, 18252 (unsigned)InitVal.getMinSignedBits()); 18253 18254 // Keep track of whether every enum element has type int (very common). 18255 if (AllElementsInt) 18256 AllElementsInt = ECD->getType() == Context.IntTy; 18257 } 18258 18259 // Figure out the type that should be used for this enum. 18260 QualType BestType; 18261 unsigned BestWidth; 18262 18263 // C++0x N3000 [conv.prom]p3: 18264 // An rvalue of an unscoped enumeration type whose underlying 18265 // type is not fixed can be converted to an rvalue of the first 18266 // of the following types that can represent all the values of 18267 // the enumeration: int, unsigned int, long int, unsigned long 18268 // int, long long int, or unsigned long long int. 18269 // C99 6.4.4.3p2: 18270 // An identifier declared as an enumeration constant has type int. 18271 // The C99 rule is modified by a gcc extension 18272 QualType BestPromotionType; 18273 18274 bool Packed = Enum->hasAttr<PackedAttr>(); 18275 // -fshort-enums is the equivalent to specifying the packed attribute on all 18276 // enum definitions. 18277 if (LangOpts.ShortEnums) 18278 Packed = true; 18279 18280 // If the enum already has a type because it is fixed or dictated by the 18281 // target, promote that type instead of analyzing the enumerators. 18282 if (Enum->isComplete()) { 18283 BestType = Enum->getIntegerType(); 18284 if (BestType->isPromotableIntegerType()) 18285 BestPromotionType = Context.getPromotedIntegerType(BestType); 18286 else 18287 BestPromotionType = BestType; 18288 18289 BestWidth = Context.getIntWidth(BestType); 18290 } 18291 else if (NumNegativeBits) { 18292 // If there is a negative value, figure out the smallest integer type (of 18293 // int/long/longlong) that fits. 18294 // If it's packed, check also if it fits a char or a short. 18295 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18296 BestType = Context.SignedCharTy; 18297 BestWidth = CharWidth; 18298 } else if (Packed && NumNegativeBits <= ShortWidth && 18299 NumPositiveBits < ShortWidth) { 18300 BestType = Context.ShortTy; 18301 BestWidth = ShortWidth; 18302 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18303 BestType = Context.IntTy; 18304 BestWidth = IntWidth; 18305 } else { 18306 BestWidth = Context.getTargetInfo().getLongWidth(); 18307 18308 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18309 BestType = Context.LongTy; 18310 } else { 18311 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18312 18313 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18314 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18315 BestType = Context.LongLongTy; 18316 } 18317 } 18318 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18319 } else { 18320 // If there is no negative value, figure out the smallest type that fits 18321 // all of the enumerator values. 18322 // If it's packed, check also if it fits a char or a short. 18323 if (Packed && NumPositiveBits <= CharWidth) { 18324 BestType = Context.UnsignedCharTy; 18325 BestPromotionType = Context.IntTy; 18326 BestWidth = CharWidth; 18327 } else if (Packed && NumPositiveBits <= ShortWidth) { 18328 BestType = Context.UnsignedShortTy; 18329 BestPromotionType = Context.IntTy; 18330 BestWidth = ShortWidth; 18331 } else if (NumPositiveBits <= IntWidth) { 18332 BestType = Context.UnsignedIntTy; 18333 BestWidth = IntWidth; 18334 BestPromotionType 18335 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18336 ? Context.UnsignedIntTy : Context.IntTy; 18337 } else if (NumPositiveBits <= 18338 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18339 BestType = Context.UnsignedLongTy; 18340 BestPromotionType 18341 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18342 ? Context.UnsignedLongTy : Context.LongTy; 18343 } else { 18344 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18345 assert(NumPositiveBits <= BestWidth &&(static_cast <bool> (NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?") ? void (0) :
__assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 18346, __extension__ __PRETTY_FUNCTION__))
18346 "How could an initializer get larger than ULL?")(static_cast <bool> (NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?") ? void (0) :
__assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 18346, __extension__ __PRETTY_FUNCTION__))
; 18347 BestType = Context.UnsignedLongLongTy; 18348 BestPromotionType 18349 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18350 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18351 } 18352 } 18353 18354 // Loop over all of the enumerator constants, changing their types to match 18355 // the type of the enum if needed. 18356 for (auto *D : Elements) { 18357 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18358 if (!ECD) continue; // Already issued a diagnostic. 18359 18360 // Standard C says the enumerators have int type, but we allow, as an 18361 // extension, the enumerators to be larger than int size. If each 18362 // enumerator value fits in an int, type it as an int, otherwise type it the 18363 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18364 // that X has type 'int', not 'unsigned'. 18365 18366 // Determine whether the value fits into an int. 18367 llvm::APSInt InitVal = ECD->getInitVal(); 18368 18369 // If it fits into an integer type, force it. Otherwise force it to match 18370 // the enum decl type. 18371 QualType NewTy; 18372 unsigned NewWidth; 18373 bool NewSign; 18374 if (!getLangOpts().CPlusPlus && 18375 !Enum->isFixed() && 18376 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18377 NewTy = Context.IntTy; 18378 NewWidth = IntWidth; 18379 NewSign = true; 18380 } else if (ECD->getType() == BestType) { 18381 // Already the right type! 18382 if (getLangOpts().CPlusPlus) 18383 // C++ [dcl.enum]p4: Following the closing brace of an 18384 // enum-specifier, each enumerator has the type of its 18385 // enumeration. 18386 ECD->setType(EnumType); 18387 continue; 18388 } else { 18389 NewTy = BestType; 18390 NewWidth = BestWidth; 18391 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18392 } 18393 18394 // Adjust the APSInt value. 18395 InitVal = InitVal.extOrTrunc(NewWidth); 18396 InitVal.setIsSigned(NewSign); 18397 ECD->setInitVal(InitVal); 18398 18399 // Adjust the Expr initializer and type. 18400 if (ECD->getInitExpr() && 18401 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18402 ECD->setInitExpr(ImplicitCastExpr::Create( 18403 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18404 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18405 if (getLangOpts().CPlusPlus) 18406 // C++ [dcl.enum]p4: Following the closing brace of an 18407 // enum-specifier, each enumerator has the type of its 18408 // enumeration. 18409 ECD->setType(EnumType); 18410 else 18411 ECD->setType(NewTy); 18412 } 18413 18414 Enum->completeDefinition(BestType, BestPromotionType, 18415 NumPositiveBits, NumNegativeBits); 18416 18417 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18418 18419 if (Enum->isClosedFlag()) { 18420 for (Decl *D : Elements) { 18421 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18422 if (!ECD) continue; // Already issued a diagnostic. 18423 18424 llvm::APSInt InitVal = ECD->getInitVal(); 18425 if (InitVal != 0 && !InitVal.isPowerOf2() && 18426 !IsValueInFlagEnum(Enum, InitVal, true)) 18427 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18428 << ECD << Enum; 18429 } 18430 } 18431 18432 // Now that the enum type is defined, ensure it's not been underaligned. 18433 if (Enum->hasAttrs()) 18434 CheckAlignasUnderalignment(Enum); 18435} 18436 18437Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18438 SourceLocation StartLoc, 18439 SourceLocation EndLoc) { 18440 StringLiteral *AsmString = cast<StringLiteral>(expr); 18441 18442 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18443 AsmString, StartLoc, 18444 EndLoc); 18445 CurContext->addDecl(New); 18446 return New; 18447} 18448 18449void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18450 IdentifierInfo* AliasName, 18451 SourceLocation PragmaLoc, 18452 SourceLocation NameLoc, 18453 SourceLocation AliasNameLoc) { 18454 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18455 LookupOrdinaryName); 18456 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18457 AttributeCommonInfo::AS_Pragma); 18458 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18459 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18460 18461 // If a declaration that: 18462 // 1) declares a function or a variable 18463 // 2) has external linkage 18464 // already exists, add a label attribute to it. 18465 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18466 if (isDeclExternC(PrevDecl)) 18467 PrevDecl->addAttr(Attr); 18468 else 18469 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18470 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18471 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18472 } else 18473 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18474} 18475 18476void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18477 SourceLocation PragmaLoc, 18478 SourceLocation NameLoc) { 18479 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18480 18481 if (PrevDecl) { 18482 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18483 } else { 18484 (void)WeakUndeclaredIdentifiers.insert( 18485 std::pair<IdentifierInfo*,WeakInfo> 18486 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18487 } 18488} 18489 18490void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18491 IdentifierInfo* AliasName, 18492 SourceLocation PragmaLoc, 18493 SourceLocation NameLoc, 18494 SourceLocation AliasNameLoc) { 18495 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18496 LookupOrdinaryName); 18497 WeakInfo W = WeakInfo(Name, NameLoc); 18498 18499 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18500 if (!PrevDecl->hasAttr<AliasAttr>()) 18501 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18502 DeclApplyPragmaWeak(TUScope, ND, W); 18503 } else { 18504 (void)WeakUndeclaredIdentifiers.insert( 18505 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18506 } 18507} 18508 18509Decl *Sema::getObjCDeclContext() const { 18510 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18511} 18512 18513Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18514 bool Final) { 18515 assert(FD && "Expected non-null FunctionDecl")(static_cast <bool> (FD && "Expected non-null FunctionDecl"
) ? void (0) : __assert_fail ("FD && \"Expected non-null FunctionDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 18515, __extension__ __PRETTY_FUNCTION__))
; 18516 18517 // SYCL functions can be template, so we check if they have appropriate 18518 // attribute prior to checking if it is a template. 18519 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18520 return FunctionEmissionStatus::Emitted; 18521 18522 // Templates are emitted when they're instantiated. 18523 if (FD->isDependentContext()) 18524 return FunctionEmissionStatus::TemplateDiscarded; 18525 18526 // Check whether this function is an externally visible definition. 18527 auto IsEmittedForExternalSymbol = [this, FD]() { 18528 // We have to check the GVA linkage of the function's *definition* -- if we 18529 // only have a declaration, we don't know whether or not the function will 18530 // be emitted, because (say) the definition could include "inline". 18531 FunctionDecl *Def = FD->getDefinition(); 18532 18533 return Def && !isDiscardableGVALinkage( 18534 getASTContext().GetGVALinkageForFunction(Def)); 18535 }; 18536 18537 if (LangOpts.OpenMPIsDevice) { 18538 // In OpenMP device mode we will not emit host only functions, or functions 18539 // we don't need due to their linkage. 18540 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18541 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18542 // DevTy may be changed later by 18543 // #pragma omp declare target to(*) device_type(*). 18544 // Therefore DevTy having no value does not imply host. The emission status 18545 // will be checked again at the end of compilation unit with Final = true. 18546 if (DevTy.hasValue()) 18547 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18548 return FunctionEmissionStatus::OMPDiscarded; 18549 // If we have an explicit value for the device type, or we are in a target 18550 // declare context, we need to emit all extern and used symbols. 18551 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18552 if (IsEmittedForExternalSymbol()) 18553 return FunctionEmissionStatus::Emitted; 18554 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18555 // we'll omit it. 18556 if (Final) 18557 return FunctionEmissionStatus::OMPDiscarded; 18558 } else if (LangOpts.OpenMP > 45) { 18559 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18560 // function. In 5.0, no_host was introduced which might cause a function to 18561 // be ommitted. 18562 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18563 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18564 if (DevTy.hasValue()) 18565 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18566 return FunctionEmissionStatus::OMPDiscarded; 18567 } 18568 18569 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18570 return FunctionEmissionStatus::Emitted; 18571 18572 if (LangOpts.CUDA) { 18573 // When compiling for device, host functions are never emitted. Similarly, 18574 // when compiling for host, device and global functions are never emitted. 18575 // (Technically, we do emit a host-side stub for global functions, but this 18576 // doesn't count for our purposes here.) 18577 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18578 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18579 return FunctionEmissionStatus::CUDADiscarded; 18580 if (!LangOpts.CUDAIsDevice && 18581 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18582 return FunctionEmissionStatus::CUDADiscarded; 18583 18584 if (IsEmittedForExternalSymbol()) 18585 return FunctionEmissionStatus::Emitted; 18586 } 18587 18588 // Otherwise, the function is known-emitted if it's in our set of 18589 // known-emitted functions. 18590 return FunctionEmissionStatus::Unknown; 18591} 18592 18593bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18594 // Host-side references to a __global__ function refer to the stub, so the 18595 // function itself is never emitted and therefore should not be marked. 18596 // If we have host fn calls kernel fn calls host+device, the HD function 18597 // does not get instantiated on the host. We model this by omitting at the 18598 // call to the kernel from the callgraph. This ensures that, when compiling 18599 // for host, only HD functions actually called from the host get marked as 18600 // known-emitted. 18601 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18602 IdentifyCUDATarget(Callee) == CFT_Global; 18603}

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
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 defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 475, __extension__ __PRETTY_FUNCTION__))
;
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 479, __extension__ __PRETTY_FUNCTION__))
;
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast <bool> (isFromASTFile() && "Only works on a deserialized declaration"
) ? void (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 645, __extension__ __PRETTY_FUNCTION__))
;
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 757, __extension__ __PRETTY_FUNCTION__))
757 "owned local decl but no local module storage")(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 757, __extension__ __PRETTY_FUNCTION__))
;
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
762 hasLocalOwningModuleStorage() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
763 "should not have a cached owning module")(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
;
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
809 !hasLocalOwningModuleStorage()) &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
810 "no storage available for owning module for this declaration")(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
;
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end"
) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 945, __extension__ __PRETTY_FUNCTION__))
;
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")(static_cast <bool> (Next && "Should return next redeclaration or itself, never null!"
) ? void (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 948, __extension__ __PRETTY_FUNCTION__))
;
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1082, __extension__ __PRETTY_FUNCTION__))
1082 "namespace is not ordinary")(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1082, __extension__ __PRETTY_FUNCTION__))
;
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1108 "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
;
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1112 "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
;
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind()
== FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1153, __extension__ __PRETTY_FUNCTION__))
;
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1155, __extension__ __PRETTY_FUNCTION__))
1155 "visible non-member operators should be in ordinary namespace")(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1155, __extension__ __PRETTY_FUNCTION__))
;
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223} // namespace clang
1224
1225// Required to determine the layout of the PointerUnion<NamedDecl*> before
1226// seeing the NamedDecl definition being first used in DeclListNode::operator*.
1227namespace llvm {
1228 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1229 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1230 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1231 return static_cast<::clang::NamedDecl *>(P);
1232 }
1233 static constexpr int NumLowBitsAvailable = 3;
1234 };
1235}
1236
1237namespace clang {
1238/// A list storing NamedDecls in the lookup tables.
1239class DeclListNode {
1240 friend class ASTContext; // allocate, deallocate nodes.
1241 friend class StoredDeclsList;
1242public:
1243 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1244 class iterator {
1245 friend class DeclContextLookupResult;
1246 friend class StoredDeclsList;
1247
1248 Decls Ptr;
1249 iterator(Decls Node) : Ptr(Node) { }
1250 public:
1251 using difference_type = ptrdiff_t;
1252 using value_type = NamedDecl*;
1253 using pointer = void;
1254 using reference = value_type;
1255 using iterator_category = std::forward_iterator_tag;
1256
1257 iterator() = default;
1258
1259 reference operator*() const {
1260 assert(Ptr && "dereferencing end() iterator")(static_cast <bool> (Ptr && "dereferencing end() iterator"
) ? void (0) : __assert_fail ("Ptr && \"dereferencing end() iterator\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1260, __extension__ __PRETTY_FUNCTION__))
;
1261 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1262 return CurNode->D;
1263 return Ptr.get<NamedDecl*>();
1264 }
1265 void operator->() const { } // Unsupported.
1266 bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1267 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1268 inline iterator &operator++() { // ++It
1269 assert(!Ptr.isNull() && "Advancing empty iterator")(static_cast <bool> (!Ptr.isNull() && "Advancing empty iterator"
) ? void (0) : __assert_fail ("!Ptr.isNull() && \"Advancing empty iterator\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1269, __extension__ __PRETTY_FUNCTION__))
;
1270
1271 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1272 Ptr = CurNode->Rest;
1273 else
1274 Ptr = nullptr;
1275 return *this;
1276 }
1277 iterator operator++(int) { // It++
1278 iterator temp = *this;
1279 ++(*this);
1280 return temp;
1281 }
1282 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1283 iterator end() { return iterator(); }
1284 };
1285private:
1286 NamedDecl *D = nullptr;
1287 Decls Rest = nullptr;
1288 DeclListNode(NamedDecl *ND) : D(ND) {}
1289};
1290
1291/// The results of name lookup within a DeclContext.
1292class DeclContextLookupResult {
1293 using Decls = DeclListNode::Decls;
1294
1295 /// When in collection form, this is what the Data pointer points to.
1296 Decls Result;
1297
1298public:
1299 DeclContextLookupResult() = default;
1300 DeclContextLookupResult(Decls Result) : Result(Result) {}
1301
1302 using iterator = DeclListNode::iterator;
1303 using const_iterator = iterator;
1304 using reference = iterator::reference;
1305
1306 iterator begin() { return iterator(Result); }
1307 iterator end() { return iterator(); }
1308 const_iterator begin() const {
1309 return const_cast<DeclContextLookupResult*>(this)->begin();
1310 }
1311 const_iterator end() const { return iterator(); }
1312
1313 bool empty() const { return Result.isNull(); }
1314 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
1315 reference front() const { return *begin(); }
1316
1317 // Find the first declaration of the given type in the list. Note that this
1318 // is not in general the earliest-declared declaration, and should only be
1319 // used when it's not possible for there to be more than one match or where
1320 // it doesn't matter which one is found.
1321 template<class T> T *find_first() const {
1322 for (auto *D : *this)
1323 if (T *Decl = dyn_cast<T>(D))
1324 return Decl;
1325
1326 return nullptr;
1327 }
1328};
1329
1330/// DeclContext - This is used only as base class of specific decl types that
1331/// can act as declaration contexts. These decls are (only the top classes
1332/// that directly derive from DeclContext are mentioned, not their subclasses):
1333///
1334/// TranslationUnitDecl
1335/// ExternCContext
1336/// NamespaceDecl
1337/// TagDecl
1338/// OMPDeclareReductionDecl
1339/// OMPDeclareMapperDecl
1340/// FunctionDecl
1341/// ObjCMethodDecl
1342/// ObjCContainerDecl
1343/// LinkageSpecDecl
1344/// ExportDecl
1345/// BlockDecl
1346/// CapturedDecl
1347class DeclContext {
1348 /// For makeDeclVisibleInContextImpl
1349 friend class ASTDeclReader;
1350 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1351 /// hasNeedToReconcileExternalVisibleStorage
1352 friend class ExternalASTSource;
1353 /// For CreateStoredDeclsMap
1354 friend class DependentDiagnostic;
1355 /// For hasNeedToReconcileExternalVisibleStorage,
1356 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1357 friend class ASTWriter;
1358
1359 // We use uint64_t in the bit-fields below since some bit-fields
1360 // cross the unsigned boundary and this breaks the packing.
1361
1362 /// Stores the bits used by DeclContext.
1363 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1364 /// methods in DeclContext should be updated appropriately.
1365 class DeclContextBitfields {
1366 friend class DeclContext;
1367 /// DeclKind - This indicates which class this is.
1368 uint64_t DeclKind : 7;
1369
1370 /// Whether this declaration context also has some external
1371 /// storage that contains additional declarations that are lexically
1372 /// part of this context.
1373 mutable uint64_t ExternalLexicalStorage : 1;
1374
1375 /// Whether this declaration context also has some external
1376 /// storage that contains additional declarations that are visible
1377 /// in this context.
1378 mutable uint64_t ExternalVisibleStorage : 1;
1379
1380 /// Whether this declaration context has had externally visible
1381 /// storage added since the last lookup. In this case, \c LookupPtr's
1382 /// invariant may not hold and needs to be fixed before we perform
1383 /// another lookup.
1384 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1385
1386 /// If \c true, this context may have local lexical declarations
1387 /// that are missing from the lookup table.
1388 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1389
1390 /// If \c true, the external source may have lexical declarations
1391 /// that are missing from the lookup table.
1392 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1393
1394 /// If \c true, lookups should only return identifier from
1395 /// DeclContext scope (for example TranslationUnit). Used in
1396 /// LookupQualifiedName()
1397 mutable uint64_t UseQualifiedLookup : 1;
1398 };
1399
1400 /// Number of bits in DeclContextBitfields.
1401 enum { NumDeclContextBits = 13 };
1402
1403 /// Stores the bits used by TagDecl.
1404 /// If modified NumTagDeclBits and the accessor
1405 /// methods in TagDecl should be updated appropriately.
1406 class TagDeclBitfields {
1407 friend class TagDecl;
1408 /// For the bits in DeclContextBitfields
1409 uint64_t : NumDeclContextBits;
1410
1411 /// The TagKind enum.
1412 uint64_t TagDeclKind : 3;
1413
1414 /// True if this is a definition ("struct foo {};"), false if it is a
1415 /// declaration ("struct foo;"). It is not considered a definition
1416 /// until the definition has been fully processed.
1417 uint64_t IsCompleteDefinition : 1;
1418
1419 /// True if this is currently being defined.
1420 uint64_t IsBeingDefined : 1;
1421
1422 /// True if this tag declaration is "embedded" (i.e., defined or declared
1423 /// for the very first time) in the syntax of a declarator.
1424 uint64_t IsEmbeddedInDeclarator : 1;
1425
1426 /// True if this tag is free standing, e.g. "struct foo;".
1427 uint64_t IsFreeStanding : 1;
1428
1429 /// Indicates whether it is possible for declarations of this kind
1430 /// to have an out-of-date definition.
1431 ///
1432 /// This option is only enabled when modules are enabled.
1433 uint64_t MayHaveOutOfDateDef : 1;
1434
1435 /// Has the full definition of this type been required by a use somewhere in
1436 /// the TU.
1437 uint64_t IsCompleteDefinitionRequired : 1;
1438 };
1439
1440 /// Number of non-inherited bits in TagDeclBitfields.
1441 enum { NumTagDeclBits = 9 };
1442
1443 /// Stores the bits used by EnumDecl.
1444 /// If modified NumEnumDeclBit and the accessor
1445 /// methods in EnumDecl should be updated appropriately.
1446 class EnumDeclBitfields {
1447 friend class EnumDecl;
1448 /// For the bits in DeclContextBitfields.
1449 uint64_t : NumDeclContextBits;
1450 /// For the bits in TagDeclBitfields.
1451 uint64_t : NumTagDeclBits;
1452
1453 /// Width in bits required to store all the non-negative
1454 /// enumerators of this enum.
1455 uint64_t NumPositiveBits : 8;
1456
1457 /// Width in bits required to store all the negative
1458 /// enumerators of this enum.
1459 uint64_t NumNegativeBits : 8;
1460
1461 /// True if this tag declaration is a scoped enumeration. Only
1462 /// possible in C++11 mode.
1463 uint64_t IsScoped : 1;
1464
1465 /// If this tag declaration is a scoped enum,
1466 /// then this is true if the scoped enum was declared using the class
1467 /// tag, false if it was declared with the struct tag. No meaning is
1468 /// associated if this tag declaration is not a scoped enum.
1469 uint64_t IsScopedUsingClassTag : 1;
1470
1471 /// True if this is an enumeration with fixed underlying type. Only
1472 /// possible in C++11, Microsoft extensions, or Objective C mode.
1473 uint64_t IsFixed : 1;
1474
1475 /// True if a valid hash is stored in ODRHash.
1476 uint64_t HasODRHash : 1;
1477 };
1478
1479 /// Number of non-inherited bits in EnumDeclBitfields.
1480 enum { NumEnumDeclBits = 20 };
1481
1482 /// Stores the bits used by RecordDecl.
1483 /// If modified NumRecordDeclBits and the accessor
1484 /// methods in RecordDecl should be updated appropriately.
1485 class RecordDeclBitfields {
1486 friend class RecordDecl;
1487 /// For the bits in DeclContextBitfields.
1488 uint64_t : NumDeclContextBits;
1489 /// For the bits in TagDeclBitfields.
1490 uint64_t : NumTagDeclBits;
1491
1492 /// This is true if this struct ends with a flexible
1493 /// array member (e.g. int X[]) or if this union contains a struct that does.
1494 /// If so, this cannot be contained in arrays or other structs as a member.
1495 uint64_t HasFlexibleArrayMember : 1;
1496
1497 /// Whether this is the type of an anonymous struct or union.
1498 uint64_t AnonymousStructOrUnion : 1;
1499
1500 /// This is true if this struct has at least one member
1501 /// containing an Objective-C object pointer type.
1502 uint64_t HasObjectMember : 1;
1503
1504 /// This is true if struct has at least one member of
1505 /// 'volatile' type.
1506 uint64_t HasVolatileMember : 1;
1507
1508 /// Whether the field declarations of this record have been loaded
1509 /// from external storage. To avoid unnecessary deserialization of
1510 /// methods/nested types we allow deserialization of just the fields
1511 /// when needed.
1512 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1513
1514 /// Basic properties of non-trivial C structs.
1515 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1516 uint64_t NonTrivialToPrimitiveCopy : 1;
1517 uint64_t NonTrivialToPrimitiveDestroy : 1;
1518
1519 /// The following bits indicate whether this is or contains a C union that
1520 /// is non-trivial to default-initialize, destruct, or copy. These bits
1521 /// imply the associated basic non-triviality predicates declared above.
1522 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1523 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1524 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1525
1526 /// Indicates whether this struct is destroyed in the callee.
1527 uint64_t ParamDestroyedInCallee : 1;
1528
1529 /// Represents the way this type is passed to a function.
1530 uint64_t ArgPassingRestrictions : 2;
1531 };
1532
1533 /// Number of non-inherited bits in RecordDeclBitfields.
1534 enum { NumRecordDeclBits = 14 };
1535
1536 /// Stores the bits used by OMPDeclareReductionDecl.
1537 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1538 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1539 class OMPDeclareReductionDeclBitfields {
1540 friend class OMPDeclareReductionDecl;
1541 /// For the bits in DeclContextBitfields
1542 uint64_t : NumDeclContextBits;
1543
1544 /// Kind of initializer,
1545 /// function call or omp_priv<init_expr> initializtion.
1546 uint64_t InitializerKind : 2;
1547 };
1548
1549 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1550 enum { NumOMPDeclareReductionDeclBits = 2 };
1551
1552 /// Stores the bits used by FunctionDecl.
1553 /// If modified NumFunctionDeclBits and the accessor
1554 /// methods in FunctionDecl and CXXDeductionGuideDecl
1555 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1556 class FunctionDeclBitfields {
1557 friend class FunctionDecl;
1558 /// For IsCopyDeductionCandidate
1559 friend class CXXDeductionGuideDecl;
1560 /// For the bits in DeclContextBitfields.
1561 uint64_t : NumDeclContextBits;
1562
1563 uint64_t SClass : 3;
1564 uint64_t IsInline : 1;
1565 uint64_t IsInlineSpecified : 1;
1566
1567 uint64_t IsVirtualAsWritten : 1;
1568 uint64_t IsPure : 1;
1569 uint64_t HasInheritedPrototype : 1;
1570 uint64_t HasWrittenPrototype : 1;
1571 uint64_t IsDeleted : 1;
1572 /// Used by CXXMethodDecl
1573 uint64_t IsTrivial : 1;
1574
1575 /// This flag indicates whether this function is trivial for the purpose of
1576 /// calls. This is meaningful only when this function is a copy/move
1577 /// constructor or a destructor.
1578 uint64_t IsTrivialForCall : 1;
1579
1580 uint64_t IsDefaulted : 1;
1581 uint64_t IsExplicitlyDefaulted : 1;
1582 uint64_t HasDefaultedFunctionInfo : 1;
1583 uint64_t HasImplicitReturnZero : 1;
1584 uint64_t IsLateTemplateParsed : 1;
1585
1586 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1587 uint64_t ConstexprKind : 2;
1588 uint64_t InstantiationIsPending : 1;
1589
1590 /// Indicates if the function uses __try.
1591 uint64_t UsesSEHTry : 1;
1592
1593 /// Indicates if the function was a definition
1594 /// but its body was skipped.
1595 uint64_t HasSkippedBody : 1;
1596
1597 /// Indicates if the function declaration will
1598 /// have a body, once we're done parsing it.
1599 uint64_t WillHaveBody : 1;
1600
1601 /// Indicates that this function is a multiversioned
1602 /// function using attribute 'target'.
1603 uint64_t IsMultiVersion : 1;
1604
1605 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1606 /// the Deduction Guide is the implicitly generated 'copy
1607 /// deduction candidate' (is used during overload resolution).
1608 uint64_t IsCopyDeductionCandidate : 1;
1609
1610 /// Store the ODRHash after first calculation.
1611 uint64_t HasODRHash : 1;
1612
1613 /// Indicates if the function uses Floating Point Constrained Intrinsics
1614 uint64_t UsesFPIntrin : 1;
1615 };
1616
1617 /// Number of non-inherited bits in FunctionDeclBitfields.
1618 enum { NumFunctionDeclBits = 27 };
1619
1620 /// Stores the bits used by CXXConstructorDecl. If modified
1621 /// NumCXXConstructorDeclBits and the accessor
1622 /// methods in CXXConstructorDecl should be updated appropriately.
1623 class CXXConstructorDeclBitfields {
1624 friend class CXXConstructorDecl;
1625 /// For the bits in DeclContextBitfields.
1626 uint64_t : NumDeclContextBits;
1627 /// For the bits in FunctionDeclBitfields.
1628 uint64_t : NumFunctionDeclBits;
1629
1630 /// 24 bits to fit in the remaining available space.
1631 /// Note that this makes CXXConstructorDeclBitfields take
1632 /// exactly 64 bits and thus the width of NumCtorInitializers
1633 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1634 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1635 uint64_t NumCtorInitializers : 21;
1636 uint64_t IsInheritingConstructor : 1;
1637
1638 /// Whether this constructor has a trail-allocated explicit specifier.
1639 uint64_t HasTrailingExplicitSpecifier : 1;
1640 /// If this constructor does't have a trail-allocated explicit specifier.
1641 /// Whether this constructor is explicit specified.
1642 uint64_t IsSimpleExplicit : 1;
1643 };
1644
1645 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1646 enum {
1647 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1648 };
1649
1650 /// Stores the bits used by ObjCMethodDecl.
1651 /// If modified NumObjCMethodDeclBits and the accessor
1652 /// methods in ObjCMethodDecl should be updated appropriately.
1653 class ObjCMethodDeclBitfields {
1654 friend class ObjCMethodDecl;
1655
1656 /// For the bits in DeclContextBitfields.
1657 uint64_t : NumDeclContextBits;
1658
1659 /// The conventional meaning of this method; an ObjCMethodFamily.
1660 /// This is not serialized; instead, it is computed on demand and
1661 /// cached.
1662 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1663
1664 /// instance (true) or class (false) method.
1665 uint64_t IsInstance : 1;
1666 uint64_t IsVariadic : 1;
1667
1668 /// True if this method is the getter or setter for an explicit property.
1669 uint64_t IsPropertyAccessor : 1;
1670
1671 /// True if this method is a synthesized property accessor stub.
1672 uint64_t IsSynthesizedAccessorStub : 1;
1673
1674 /// Method has a definition.
1675 uint64_t IsDefined : 1;
1676
1677 /// Method redeclaration in the same interface.
1678 uint64_t IsRedeclaration : 1;
1679
1680 /// Is redeclared in the same interface.
1681 mutable uint64_t HasRedeclaration : 1;
1682
1683 /// \@required/\@optional
1684 uint64_t DeclImplementation : 2;
1685
1686 /// in, inout, etc.
1687 uint64_t objcDeclQualifier : 7;
1688
1689 /// Indicates whether this method has a related result type.
1690 uint64_t RelatedResultType : 1;
1691
1692 /// Whether the locations of the selector identifiers are in a
1693 /// "standard" position, a enum SelectorLocationsKind.
1694 uint64_t SelLocsKind : 2;
1695
1696 /// Whether this method overrides any other in the class hierarchy.
1697 ///
1698 /// A method is said to override any method in the class's
1699 /// base classes, its protocols, or its categories' protocols, that has
1700 /// the same selector and is of the same kind (class or instance).
1701 /// A method in an implementation is not considered as overriding the same
1702 /// method in the interface or its categories.
1703 uint64_t IsOverriding : 1;
1704
1705 /// Indicates if the method was a definition but its body was skipped.
1706 uint64_t HasSkippedBody : 1;
1707 };
1708
1709 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1710 enum { NumObjCMethodDeclBits = 24 };
1711
1712 /// Stores the bits used by ObjCContainerDecl.
1713 /// If modified NumObjCContainerDeclBits and the accessor
1714 /// methods in ObjCContainerDecl should be updated appropriately.
1715 class ObjCContainerDeclBitfields {
1716 friend class ObjCContainerDecl;
1717 /// For the bits in DeclContextBitfields
1718 uint32_t : NumDeclContextBits;
1719
1720 // Not a bitfield but this saves space.
1721 // Note that ObjCContainerDeclBitfields is full.
1722 SourceLocation AtStart;
1723 };
1724
1725 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1726 /// Note that here we rely on the fact that SourceLocation is 32 bits
1727 /// wide. We check this with the static_assert in the ctor of DeclContext.
1728 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1729
1730 /// Stores the bits used by LinkageSpecDecl.
1731 /// If modified NumLinkageSpecDeclBits and the accessor
1732 /// methods in LinkageSpecDecl should be updated appropriately.
1733 class LinkageSpecDeclBitfields {
1734 friend class LinkageSpecDecl;
1735 /// For the bits in DeclContextBitfields.
1736 uint64_t : NumDeclContextBits;
1737
1738 /// The language for this linkage specification with values
1739 /// in the enum LinkageSpecDecl::LanguageIDs.
1740 uint64_t Language : 3;
1741
1742 /// True if this linkage spec has braces.
1743 /// This is needed so that hasBraces() returns the correct result while the
1744 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1745 /// not used, so it doesn't need to be serialized.
1746 uint64_t HasBraces : 1;
1747 };
1748
1749 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1750 enum { NumLinkageSpecDeclBits = 4 };
1751
1752 /// Stores the bits used by BlockDecl.
1753 /// If modified NumBlockDeclBits and the accessor
1754 /// methods in BlockDecl should be updated appropriately.
1755 class BlockDeclBitfields {
1756 friend class BlockDecl;
1757 /// For the bits in DeclContextBitfields.
1758 uint64_t : NumDeclContextBits;
1759
1760 uint64_t IsVariadic : 1;
1761 uint64_t CapturesCXXThis : 1;
1762 uint64_t BlockMissingReturnType : 1;
1763 uint64_t IsConversionFromLambda : 1;
1764
1765 /// A bit that indicates this block is passed directly to a function as a
1766 /// non-escaping parameter.
1767 uint64_t DoesNotEscape : 1;
1768
1769 /// A bit that indicates whether it's possible to avoid coying this block to
1770 /// the heap when it initializes or is assigned to a local variable with
1771 /// automatic storage.
1772 uint64_t CanAvoidCopyToHeap : 1;
1773 };
1774
1775 /// Number of non-inherited bits in BlockDeclBitfields.
1776 enum { NumBlockDeclBits = 5 };
1777
1778 /// Pointer to the data structure used to lookup declarations
1779 /// within this context (or a DependentStoredDeclsMap if this is a
1780 /// dependent context). We maintain the invariant that, if the map
1781 /// contains an entry for a DeclarationName (and we haven't lazily
1782 /// omitted anything), then it contains all relevant entries for that
1783 /// name (modulo the hasExternalDecls() flag).
1784 mutable StoredDeclsMap *LookupPtr = nullptr;
1785
1786protected:
1787 /// This anonymous union stores the bits belonging to DeclContext and classes
1788 /// deriving from it. The goal is to use otherwise wasted
1789 /// space in DeclContext to store data belonging to derived classes.
1790 /// The space saved is especially significient when pointers are aligned
1791 /// to 8 bytes. In this case due to alignment requirements we have a
1792 /// little less than 8 bytes free in DeclContext which we can use.
1793 /// We check that none of the classes in this union is larger than
1794 /// 8 bytes with static_asserts in the ctor of DeclContext.
1795 union {
1796 DeclContextBitfields DeclContextBits;
1797 TagDeclBitfields TagDeclBits;
1798 EnumDeclBitfields EnumDeclBits;
1799 RecordDeclBitfields RecordDeclBits;
1800 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1801 FunctionDeclBitfields FunctionDeclBits;
1802 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1803 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1804 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1805 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1806 BlockDeclBitfields BlockDeclBits;
1807
1808 static_assert(sizeof(DeclContextBitfields) <= 8,
1809 "DeclContextBitfields is larger than 8 bytes!");
1810 static_assert(sizeof(TagDeclBitfields) <= 8,
1811 "TagDeclBitfields is larger than 8 bytes!");
1812 static_assert(sizeof(EnumDeclBitfields) <= 8,
1813 "EnumDeclBitfields is larger than 8 bytes!");
1814 static_assert(sizeof(RecordDeclBitfields) <= 8,
1815 "RecordDeclBitfields is larger than 8 bytes!");
1816 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1817 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1818 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1819 "FunctionDeclBitfields is larger than 8 bytes!");
1820 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1821 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1822 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1823 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1824 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1825 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1826 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1827 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1828 static_assert(sizeof(BlockDeclBitfields) <= 8,
1829 "BlockDeclBitfields is larger than 8 bytes!");
1830 };
1831
1832 /// FirstDecl - The first declaration stored within this declaration
1833 /// context.
1834 mutable Decl *FirstDecl = nullptr;
1835
1836 /// LastDecl - The last declaration stored within this declaration
1837 /// context. FIXME: We could probably cache this value somewhere
1838 /// outside of the DeclContext, to reduce the size of DeclContext by
1839 /// another pointer.
1840 mutable Decl *LastDecl = nullptr;
1841
1842 /// Build up a chain of declarations.
1843 ///
1844 /// \returns the first/last pair of declarations.
1845 static std::pair<Decl *, Decl *>
1846 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1847
1848 DeclContext(Decl::Kind K);
1849
1850public:
1851 ~DeclContext();
1852
1853 Decl::Kind getDeclKind() const {
1854 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1855 }
1856
1857 const char *getDeclKindName() const;
1858
1859 /// getParent - Returns the containing DeclContext.
1860 DeclContext *getParent() {
1861 return cast<Decl>(this)->getDeclContext();
1862 }
1863 const DeclContext *getParent() const {
1864 return const_cast<DeclContext*>(this)->getParent();
1865 }
1866
1867 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1868 /// different from getParent, e.g.:
1869 ///
1870 /// namespace A {
1871 /// struct S;
1872 /// }
1873 /// struct A::S {}; // getParent() == namespace 'A'
1874 /// // getLexicalParent() == translation unit
1875 ///
1876 DeclContext *getLexicalParent() {
1877 return cast<Decl>(this)->getLexicalDeclContext();
1878 }
1879 const DeclContext *getLexicalParent() const {
1880 return const_cast<DeclContext*>(this)->getLexicalParent();
1881 }
1882
1883 DeclContext *getLookupParent();
1884
1885 const DeclContext *getLookupParent() const {
1886 return const_cast<DeclContext*>(this)->getLookupParent();
1887 }
1888
1889 ASTContext &getParentASTContext() const {
1890 return cast<Decl>(this)->getASTContext();
1891 }
1892
1893 bool isClosure() const { return getDeclKind() == Decl::Block; }
1894
1895 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1896 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1897 const BlockDecl *getInnermostBlockDecl() const;
1898
1899 bool isObjCContainer() const {
1900 switch (getDeclKind()) {
1901 case Decl::ObjCCategory:
1902 case Decl::ObjCCategoryImpl:
1903 case Decl::ObjCImplementation:
1904 case Decl::ObjCInterface:
1905 case Decl::ObjCProtocol:
1906 return true;
1907 default:
1908 return false;
1909 }
1910 }
1911
1912 bool isFunctionOrMethod() const {
1913 switch (getDeclKind()) {
1914 case Decl::Block:
1915 case Decl::Captured:
1916 case Decl::ObjCMethod:
1917 return true;
1918 default:
1919 return getDeclKind() >= Decl::firstFunction &&
1920 getDeclKind() <= Decl::lastFunction;
1921 }
1922 }
1923
1924 /// Test whether the context supports looking up names.
1925 bool isLookupContext() const {
1926 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1927 getDeclKind() != Decl::Export;
1928 }
1929
1930 bool isFileContext() const {
1931 return getDeclKind() == Decl::TranslationUnit ||
1932 getDeclKind() == Decl::Namespace;
1933 }
1934
1935 bool isTranslationUnit() const {
1936 return getDeclKind() == Decl::TranslationUnit;
1937 }
1938
1939 bool isRecord() const {
1940 return getDeclKind() >= Decl::firstRecord &&
35
Returning zero, which participates in a condition later
39
Assuming the condition is false
40
Returning zero, which participates in a condition later
1941 getDeclKind() <= Decl::lastRecord;
1942 }
1943
1944 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1945
1946 bool isStdNamespace() const;
1947
1948 bool isInlineNamespace() const;
1949
1950 /// Determines whether this context is dependent on a
1951 /// template parameter.
1952 bool isDependentContext() const;
1953
1954 /// isTransparentContext - Determines whether this context is a
1955 /// "transparent" context, meaning that the members declared in this
1956 /// context are semantically declared in the nearest enclosing
1957 /// non-transparent (opaque) context but are lexically declared in
1958 /// this context. For example, consider the enumerators of an
1959 /// enumeration type:
1960 /// @code
1961 /// enum E {
1962 /// Val1
1963 /// };
1964 /// @endcode
1965 /// Here, E is a transparent context, so its enumerator (Val1) will
1966 /// appear (semantically) that it is in the same context of E.
1967 /// Examples of transparent contexts include: enumerations (except for
1968 /// C++0x scoped enums), and C++ linkage specifications.
1969 bool isTransparentContext() const;
1970
1971 /// Determines whether this context or some of its ancestors is a
1972 /// linkage specification context that specifies C linkage.
1973 bool isExternCContext() const;
1974
1975 /// Retrieve the nearest enclosing C linkage specification context.
1976 const LinkageSpecDecl *getExternCContext() const;
1977
1978 /// Determines whether this context or some of its ancestors is a
1979 /// linkage specification context that specifies C++ linkage.
1980 bool isExternCXXContext() const;
1981
1982 /// Determine whether this declaration context is equivalent
1983 /// to the declaration context DC.
1984 bool Equals(const DeclContext *DC) const {
1985 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1986 }
1987
1988 /// Determine whether this declaration context encloses the
1989 /// declaration context DC.
1990 bool Encloses(const DeclContext *DC) const;
1991
1992 /// Find the nearest non-closure ancestor of this context,
1993 /// i.e. the innermost semantic parent of this context which is not
1994 /// a closure. A context may be its own non-closure ancestor.
1995 Decl *getNonClosureAncestor();
1996 const Decl *getNonClosureAncestor() const {
1997 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1998 }
1999
2000 // Retrieve the nearest context that is not a transparent context.
2001 DeclContext *getNonTransparentContext();
2002 const DeclContext *getNonTransparentContext() const {
2003 return const_cast<DeclContext *>(this)->getNonTransparentContext();
2004 }
2005
2006 /// getPrimaryContext - There may be many different
2007 /// declarations of the same entity (including forward declarations
2008 /// of classes, multiple definitions of namespaces, etc.), each with
2009 /// a different set of declarations. This routine returns the
2010 /// "primary" DeclContext structure, which will contain the
2011 /// information needed to perform name lookup into this context.
2012 DeclContext *getPrimaryContext();
2013 const DeclContext *getPrimaryContext() const {
2014 return const_cast<DeclContext*>(this)->getPrimaryContext();
2015 }
2016
2017 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2018 /// other entities of the same name, or where it is a redeclaration if the
2019 /// two entities are compatible. This skips through transparent contexts.
2020 DeclContext *getRedeclContext();
2021 const DeclContext *getRedeclContext() const {
2022 return const_cast<DeclContext *>(this)->getRedeclContext();
2023 }
2024
2025 /// Retrieve the nearest enclosing namespace context.
2026 DeclContext *getEnclosingNamespaceContext();
2027 const DeclContext *getEnclosingNamespaceContext() const {
2028 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2029 }
2030
2031 /// Retrieve the outermost lexically enclosing record context.
2032 RecordDecl *getOuterLexicalRecordContext();
2033 const RecordDecl *getOuterLexicalRecordContext() const {
2034 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2035 }
2036
2037 /// Test if this context is part of the enclosing namespace set of
2038 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2039 /// isn't a namespace, this is equivalent to Equals().
2040 ///
2041 /// The enclosing namespace set of a namespace is the namespace and, if it is
2042 /// inline, its enclosing namespace, recursively.
2043 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2044
2045 /// Collects all of the declaration contexts that are semantically
2046 /// connected to this declaration context.
2047 ///
2048 /// For declaration contexts that have multiple semantically connected but
2049 /// syntactically distinct contexts, such as C++ namespaces, this routine
2050 /// retrieves the complete set of such declaration contexts in source order.
2051 /// For example, given:
2052 ///
2053 /// \code
2054 /// namespace N {
2055 /// int x;
2056 /// }
2057 /// namespace N {
2058 /// int y;
2059 /// }
2060 /// \endcode
2061 ///
2062 /// The \c Contexts parameter will contain both definitions of N.
2063 ///
2064 /// \param Contexts Will be cleared and set to the set of declaration
2065 /// contexts that are semanticaly connected to this declaration context,
2066 /// in source order, including this context (which may be the only result,
2067 /// for non-namespace contexts).
2068 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2069
2070 /// decl_iterator - Iterates through the declarations stored
2071 /// within this context.
2072 class decl_iterator {
2073 /// Current - The current declaration.
2074 Decl *Current = nullptr;
2075
2076 public:
2077 using value_type = Decl *;
2078 using reference = const value_type &;
2079 using pointer = const value_type *;
2080 using iterator_category = std::forward_iterator_tag;
2081 using difference_type = std::ptrdiff_t;
2082
2083 decl_iterator() = default;
2084 explicit decl_iterator(Decl *C) : Current(C) {}
2085
2086 reference operator*() const { return Current; }
2087
2088 // This doesn't meet the iterator requirements, but it's convenient
2089 value_type operator->() const { return Current; }
2090
2091 decl_iterator& operator++() {
2092 Current = Current->getNextDeclInContext();
2093 return *this;
2094 }
2095
2096 decl_iterator operator++(int) {
2097 decl_iterator tmp(*this);
2098 ++(*this);
2099 return tmp;
2100 }
2101
2102 friend bool operator==(decl_iterator x, decl_iterator y) {
2103 return x.Current == y.Current;
2104 }
2105
2106 friend bool operator!=(decl_iterator x, decl_iterator y) {
2107 return x.Current != y.Current;
2108 }
2109 };
2110
2111 using decl_range = llvm::iterator_range<decl_iterator>;
2112
2113 /// decls_begin/decls_end - Iterate over the declarations stored in
2114 /// this context.
2115 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2116 decl_iterator decls_begin() const;
2117 decl_iterator decls_end() const { return decl_iterator(); }
2118 bool decls_empty() const;
2119
2120 /// noload_decls_begin/end - Iterate over the declarations stored in this
2121 /// context that are currently loaded; don't attempt to retrieve anything
2122 /// from an external source.
2123 decl_range noload_decls() const {
2124 return decl_range(noload_decls_begin(), noload_decls_end());
2125 }
2126 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2127 decl_iterator noload_decls_end() const { return decl_iterator(); }
2128
2129 /// specific_decl_iterator - Iterates over a subrange of
2130 /// declarations stored in a DeclContext, providing only those that
2131 /// are of type SpecificDecl (or a class derived from it). This
2132 /// iterator is used, for example, to provide iteration over just
2133 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2134 template<typename SpecificDecl>
2135 class specific_decl_iterator {
2136 /// Current - The current, underlying declaration iterator, which
2137 /// will either be NULL or will point to a declaration of
2138 /// type SpecificDecl.
2139 DeclContext::decl_iterator Current;
2140
2141 /// SkipToNextDecl - Advances the current position up to the next
2142 /// declaration of type SpecificDecl that also meets the criteria
2143 /// required by Acceptable.
2144 void SkipToNextDecl() {
2145 while (*Current && !isa<SpecificDecl>(*Current))
2146 ++Current;
2147 }
2148
2149 public:
2150 using value_type = SpecificDecl *;
2151 // TODO: Add reference and pointer types (with some appropriate proxy type)
2152 // if we ever have a need for them.
2153 using reference = void;
2154 using pointer = void;
2155 using difference_type =
2156 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2157 using iterator_category = std::forward_iterator_tag;
2158
2159 specific_decl_iterator() = default;
2160
2161 /// specific_decl_iterator - Construct a new iterator over a
2162 /// subset of the declarations the range [C,
2163 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2164 /// member function of SpecificDecl that should return true for
2165 /// all of the SpecificDecl instances that will be in the subset
2166 /// of iterators. For example, if you want Objective-C instance
2167 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2168 /// &ObjCMethodDecl::isInstanceMethod.
2169 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2170 SkipToNextDecl();
2171 }
2172
2173 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2174
2175 // This doesn't meet the iterator requirements, but it's convenient
2176 value_type operator->() const { return **this; }
2177
2178 specific_decl_iterator& operator++() {
2179 ++Current;
2180 SkipToNextDecl();
2181 return *this;
2182 }
2183
2184 specific_decl_iterator operator++(int) {
2185 specific_decl_iterator tmp(*this);
2186 ++(*this);
2187 return tmp;
2188 }
2189
2190 friend bool operator==(const specific_decl_iterator& x,
2191 const specific_decl_iterator& y) {
2192 return x.Current == y.Current;
2193 }
2194
2195 friend bool operator!=(const specific_decl_iterator& x,
2196 const specific_decl_iterator& y) {
2197 return x.Current != y.Current;
2198 }
2199 };
2200
2201 /// Iterates over a filtered subrange of declarations stored
2202 /// in a DeclContext.
2203 ///
2204 /// This iterator visits only those declarations that are of type
2205 /// SpecificDecl (or a class derived from it) and that meet some
2206 /// additional run-time criteria. This iterator is used, for
2207 /// example, to provide access to the instance methods within an
2208 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2209 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2210 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2211 class filtered_decl_iterator {
2212 /// Current - The current, underlying declaration iterator, which
2213 /// will either be NULL or will point to a declaration of
2214 /// type SpecificDecl.
2215 DeclContext::decl_iterator Current;
2216
2217 /// SkipToNextDecl - Advances the current position up to the next
2218 /// declaration of type SpecificDecl that also meets the criteria
2219 /// required by Acceptable.
2220 void SkipToNextDecl() {
2221 while (*Current &&
2222 (!isa<SpecificDecl>(*Current) ||
2223 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2224 ++Current;
2225 }
2226
2227 public:
2228 using value_type = SpecificDecl *;
2229 // TODO: Add reference and pointer types (with some appropriate proxy type)
2230 // if we ever have a need for them.
2231 using reference = void;
2232 using pointer = void;
2233 using difference_type =
2234 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2235 using iterator_category = std::forward_iterator_tag;
2236
2237 filtered_decl_iterator() = default;
2238
2239 /// filtered_decl_iterator - Construct a new iterator over a
2240 /// subset of the declarations the range [C,
2241 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2242 /// member function of SpecificDecl that should return true for
2243 /// all of the SpecificDecl instances that will be in the subset
2244 /// of iterators. For example, if you want Objective-C instance
2245 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2246 /// &ObjCMethodDecl::isInstanceMethod.
2247 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2248 SkipToNextDecl();
2249 }
2250
2251 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2252 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2253
2254 filtered_decl_iterator& operator++() {
2255 ++Current;
2256 SkipToNextDecl();
2257 return *this;
2258 }
2259
2260 filtered_decl_iterator operator++(int) {
2261 filtered_decl_iterator tmp(*this);
2262 ++(*this);
2263 return tmp;
2264 }
2265
2266 friend bool operator==(const filtered_decl_iterator& x,
2267 const filtered_decl_iterator& y) {
2268 return x.Current == y.Current;
2269 }
2270
2271 friend bool operator!=(const filtered_decl_iterator& x,
2272 const filtered_decl_iterator& y) {
2273 return x.Current != y.Current;
2274 }
2275 };
2276
2277 /// Add the declaration D into this context.
2278 ///
2279 /// This routine should be invoked when the declaration D has first
2280 /// been declared, to place D into the context where it was
2281 /// (lexically) defined. Every declaration must be added to one
2282 /// (and only one!) context, where it can be visited via
2283 /// [decls_begin(), decls_end()). Once a declaration has been added
2284 /// to its lexical context, the corresponding DeclContext owns the
2285 /// declaration.
2286 ///
2287 /// If D is also a NamedDecl, it will be made visible within its
2288 /// semantic context via makeDeclVisibleInContext.
2289 void addDecl(Decl *D);
2290
2291 /// Add the declaration D into this context, but suppress
2292 /// searches for external declarations with the same name.
2293 ///
2294 /// Although analogous in function to addDecl, this removes an
2295 /// important check. This is only useful if the Decl is being
2296 /// added in response to an external search; in all other cases,
2297 /// addDecl() is the right function to use.
2298 /// See the ASTImporter for use cases.
2299 void addDeclInternal(Decl *D);
2300
2301 /// Add the declaration D to this context without modifying
2302 /// any lookup tables.
2303 ///
2304 /// This is useful for some operations in dependent contexts where
2305 /// the semantic context might not be dependent; this basically
2306 /// only happens with friends.
2307 void addHiddenDecl(Decl *D);
2308
2309 /// Removes a declaration from this context.
2310 void removeDecl(Decl *D);
2311
2312 /// Checks whether a declaration is in this context.
2313 bool containsDecl(Decl *D) const;
2314
2315 /// Checks whether a declaration is in this context.
2316 /// This also loads the Decls from the external source before the check.
2317 bool containsDeclAndLoad(Decl *D) const;
2318
2319 using lookup_result = DeclContextLookupResult;
2320 using lookup_iterator = lookup_result::iterator;
2321
2322 /// lookup - Find the declarations (if any) with the given Name in
2323 /// this context. Returns a range of iterators that contains all of
2324 /// the declarations with this name, with object, function, member,
2325 /// and enumerator names preceding any tag name. Note that this
2326 /// routine will not look into parent contexts.
2327 lookup_result lookup(DeclarationName Name) const;
2328
2329 /// Find the declarations with the given name that are visible
2330 /// within this context; don't attempt to retrieve anything from an
2331 /// external source.
2332 lookup_result noload_lookup(DeclarationName Name);
2333
2334 /// A simplistic name lookup mechanism that performs name lookup
2335 /// into this declaration context without consulting the external source.
2336 ///
2337 /// This function should almost never be used, because it subverts the
2338 /// usual relationship between a DeclContext and the external source.
2339 /// See the ASTImporter for the (few, but important) use cases.
2340 ///
2341 /// FIXME: This is very inefficient; replace uses of it with uses of
2342 /// noload_lookup.
2343 void localUncachedLookup(DeclarationName Name,
2344 SmallVectorImpl<NamedDecl *> &Results);
2345
2346 /// Makes a declaration visible within this context.
2347 ///
2348 /// This routine makes the declaration D visible to name lookup
2349 /// within this context and, if this is a transparent context,
2350 /// within its parent contexts up to the first enclosing
2351 /// non-transparent context. Making a declaration visible within a
2352 /// context does not transfer ownership of a declaration, and a
2353 /// declaration can be visible in many contexts that aren't its
2354 /// lexical context.
2355 ///
2356 /// If D is a redeclaration of an existing declaration that is
2357 /// visible from this context, as determined by
2358 /// NamedDecl::declarationReplaces, the previous declaration will be
2359 /// replaced with D.
2360 void makeDeclVisibleInContext(NamedDecl *D);
2361
2362 /// all_lookups_iterator - An iterator that provides a view over the results
2363 /// of looking up every possible name.
2364 class all_lookups_iterator;
2365
2366 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2367
2368 lookups_range lookups() const;
2369 // Like lookups(), but avoids loading external declarations.
2370 // If PreserveInternalState, avoids building lookup data structures too.
2371 lookups_range noload_lookups(bool PreserveInternalState) const;
2372
2373 /// Iterators over all possible lookups within this context.
2374 all_lookups_iterator lookups_begin() const;
2375 all_lookups_iterator lookups_end() const;
2376
2377 /// Iterators over all possible lookups within this context that are
2378 /// currently loaded; don't attempt to retrieve anything from an external
2379 /// source.
2380 all_lookups_iterator noload_lookups_begin() const;
2381 all_lookups_iterator noload_lookups_end() const;
2382
2383 struct udir_iterator;
2384
2385 using udir_iterator_base =
2386 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2387 typename lookup_iterator::iterator_category,
2388 UsingDirectiveDecl *>;
2389
2390 struct udir_iterator : udir_iterator_base {
2391 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2392
2393 UsingDirectiveDecl *operator*() const;
2394 };
2395
2396 using udir_range = llvm::iterator_range<udir_iterator>;
2397
2398 udir_range using_directives() const;
2399
2400 // These are all defined in DependentDiagnostic.h.
2401 class ddiag_iterator;
2402
2403 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2404
2405 inline ddiag_range ddiags() const;
2406
2407 // Low-level accessors
2408
2409 /// Mark that there are external lexical declarations that we need
2410 /// to include in our lookup table (and that are not available as external
2411 /// visible lookups). These extra lookup results will be found by walking
2412 /// the lexical declarations of this context. This should be used only if
2413 /// setHasExternalLexicalStorage() has been called on any decl context for
2414 /// which this is the primary context.
2415 void setMustBuildLookupTable() {
2416 assert(this == getPrimaryContext() &&(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 2417, __extension__ __PRETTY_FUNCTION__))
2417 "should only be called on primary context")(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 2417, __extension__ __PRETTY_FUNCTION__))
;
2418 DeclContextBits.HasLazyExternalLexicalLookups = true;
2419 }
2420
2421 /// Retrieve the internal representation of the lookup structure.
2422 /// This may omit some names if we are lazily building the structure.
2423 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2424
2425 /// Ensure the lookup structure is fully-built and return it.
2426 StoredDeclsMap *buildLookup();
2427
2428 /// Whether this DeclContext has external storage containing
2429 /// additional declarations that are lexically in this context.
2430 bool hasExternalLexicalStorage() const {
2431 return DeclContextBits.ExternalLexicalStorage;
2432 }
2433
2434 /// State whether this DeclContext has external storage for
2435 /// declarations lexically in this context.
2436 void setHasExternalLexicalStorage(bool ES = true) const {
2437 DeclContextBits.ExternalLexicalStorage = ES;
2438 }
2439
2440 /// Whether this DeclContext has external storage containing
2441 /// additional declarations that are visible in this context.
2442 bool hasExternalVisibleStorage() const {
2443 return DeclContextBits.ExternalVisibleStorage;
2444 }
2445
2446 /// State whether this DeclContext has external storage for
2447 /// declarations visible in this context.
2448 void setHasExternalVisibleStorage(bool ES = true) const {
2449 DeclContextBits.ExternalVisibleStorage = ES;
2450 if (ES && LookupPtr)
2451 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2452 }
2453
2454 /// Determine whether the given declaration is stored in the list of
2455 /// declarations lexically within this context.
2456 bool isDeclInLexicalTraversal(const Decl *D) const {
2457 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2458 D == LastDecl);
2459 }
2460
2461 bool setUseQualifiedLookup(bool use = true) const {
2462 bool old_value = DeclContextBits.UseQualifiedLookup;
2463 DeclContextBits.UseQualifiedLookup = use;
2464 return old_value;
2465 }
2466
2467 bool shouldUseQualifiedLookup() const {
2468 return DeclContextBits.UseQualifiedLookup;
2469 }
2470
2471 static bool classof(const Decl *D);
2472 static bool classof(const DeclContext *D) { return true; }
2473
2474 void dumpDeclContext() const;
2475 void dumpLookups() const;
2476 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2477 bool Deserialize = false) const;
2478
2479private:
2480 /// Whether this declaration context has had externally visible
2481 /// storage added since the last lookup. In this case, \c LookupPtr's
2482 /// invariant may not hold and needs to be fixed before we perform
2483 /// another lookup.
2484 bool hasNeedToReconcileExternalVisibleStorage() const {
2485 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2486 }
2487
2488 /// State that this declaration context has had externally visible
2489 /// storage added since the last lookup. In this case, \c LookupPtr's
2490 /// invariant may not hold and needs to be fixed before we perform
2491 /// another lookup.
2492 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2493 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 bool hasLazyLocalLexicalLookups() const {
2499 return DeclContextBits.HasLazyLocalLexicalLookups;
2500 }
2501
2502 /// If \c true, this context may have local lexical declarations
2503 /// that are missing from the lookup table.
2504 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2505 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 bool hasLazyExternalLexicalLookups() const {
2511 return DeclContextBits.HasLazyExternalLexicalLookups;
2512 }
2513
2514 /// If \c true, the external source may have lexical declarations
2515 /// that are missing from the lookup table.
2516 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2517 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2518 }
2519
2520 void reconcileExternalVisibleStorage() const;
2521 bool LoadLexicalDeclsFromExternalStorage() const;
2522
2523 /// Makes a declaration visible within this context, but
2524 /// suppresses searches for external declarations with the same
2525 /// name.
2526 ///
2527 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2528 /// use of addDeclInternal().
2529 void makeDeclVisibleInContextInternal(NamedDecl *D);
2530
2531 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2532
2533 void loadLazyLocalLexicalLookups();
2534 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2535 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2536 bool Rediscoverable);
2537 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2538};
2539
2540inline bool Decl::isTemplateParameter() const {
2541 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2542 getKind() == TemplateTemplateParm;
2543}
2544
2545// Specialization selected when ToTy is not a known subclass of DeclContext.
2546template <class ToTy,
2547 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2548struct cast_convert_decl_context {
2549 static const ToTy *doit(const DeclContext *Val) {
2550 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2551 }
2552
2553 static ToTy *doit(DeclContext *Val) {
2554 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2555 }
2556};
2557
2558// Specialization selected when ToTy is a known subclass of DeclContext.
2559template <class ToTy>
2560struct cast_convert_decl_context<ToTy, true> {
2561 static const ToTy *doit(const DeclContext *Val) {
2562 return static_cast<const ToTy*>(Val);
2563 }
2564
2565 static ToTy *doit(DeclContext *Val) {
2566 return static_cast<ToTy*>(Val);
2567 }
2568};
2569
2570} // namespace clang
2571
2572namespace llvm {
2573
2574/// isa<T>(DeclContext*)
2575template <typename To>
2576struct isa_impl<To, ::clang::DeclContext> {
2577 static bool doit(const ::clang::DeclContext &Val) {
2578 return To::classofKind(Val.getDeclKind());
2579 }
2580};
2581
2582/// cast<T>(DeclContext*)
2583template<class ToTy>
2584struct cast_convert_val<ToTy,
2585 const ::clang::DeclContext,const ::clang::DeclContext> {
2586 static const ToTy &doit(const ::clang::DeclContext &Val) {
2587 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2588 }
2589};
2590
2591template<class ToTy>
2592struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2593 static ToTy &doit(::clang::DeclContext &Val) {
2594 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2595 }
2596};
2597
2598template<class ToTy>
2599struct cast_convert_val<ToTy,
2600 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2601 static const ToTy *doit(const ::clang::DeclContext *Val) {
2602 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2603 }
2604};
2605
2606template<class ToTy>
2607struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2608 static ToTy *doit(::clang::DeclContext *Val) {
2609 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2610 }
2611};
2612
2613/// Implement cast_convert_val for Decl -> DeclContext conversions.
2614template<class FromTy>
2615struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2616 static ::clang::DeclContext &doit(const FromTy &Val) {
2617 return *FromTy::castToDeclContext(&Val);
2618 }
2619};
2620
2621template<class FromTy>
2622struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2623 static ::clang::DeclContext *doit(const FromTy *Val) {
2624 return FromTy::castToDeclContext(Val);
2625 }
2626};
2627
2628template<class FromTy>
2629struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2630 static const ::clang::DeclContext &doit(const FromTy &Val) {
2631 return *FromTy::castToDeclContext(&Val);
2632 }
2633};
2634
2635template<class FromTy>
2636struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2637 static const ::clang::DeclContext *doit(const FromTy *Val) {
2638 return FromTy::castToDeclContext(Val);
2639 }
2640};
2641
2642} // namespace llvm
2643
2644#endif // LLVM_CLANG_AST_DECLBASE_H